pytest assert message customization with variable introspection

you could use Python built-in capability to show custom exception message:

assert response.status_code == 200, f"My custom msg: actual status code {response.status_code}"

Or you can built a helper assert functions:

def assert_status(response, status=200):  # you can assert other status codes too
    assert response.status_code == status, \
        f"Expected {status}. Actual status {response.status_code}. Response text {response.text}"

# here is how you'd use it
def test_api_call(self, client):
    response = client.get(reverse('api:my_api_call'))
    assert_status(response)

also checkout: https://wiki.python.org/moin/UsingAssertionsEffectively

Leave a Comment

tech