[Python] Raising an exception with pytest not working as expected

Discussão em 'Python' iniciado por Stack, Junho 13, 2025.

  1. Stack

    Stack Membro Participativo

    I have a function that makes an http request and throws an error if the response is not a 200. It looks like this:

    def put_request(param1, param2):
    url = f"api/v1/some/route"
    response = requests.put(
    url,
    json=param2,
    verify="test",
    )

    if response.status_code != 200:
    raise CustomError()

    return response.json()


    I want to test that the exception is correct so my test code looks like:

    def test_put_request_error(mocker):
    requests_mock = mocker.patch("path.to.file.requests")
    requests_mock.put.return_value.status_code = 500

    with pytest.raises(CustomError) as error:
    put_request(param1=param1, param2={some data})

    assert error.value.code == 500


    Problem is, the error gets raise in the code gets raised and execution stops. It never makes it back to the assertion in the my test. I could use some advice on fixing this!

    This pattern seems to work for my other test cases so I'm not sure what the problem here is!

    Continue reading...

Compartilhe esta Página