Python Testing Tip #10 / Sept. 16, 2025

How to customize assertion error message

Understanding test failures can be challenging without proper context. When writing end-to-end tests and asserting the expected status code, without a custom message, you'll know only that the API call failed, but you'll have no idea why.

The Solution

You can simply add a comma and a message after the assertion itself. This technique proves particularly useful in two scenarios:

  • Testing boolean flags
  • Validating API status codes

Example

response = client.get("/api/users/")
assert response.status_code == 200, f"Expected 200, got {response.status_code}. Response: {response.text}"

Practical Application

Custom messages significantly improve debugging efficiency. It's very helpful to retrieve the response's text when the response status doesn't match the expectations and use it as a custom message.

Key Takeaway

Customization makes it much easier to understand what went wrong and how to fix it, especially for API testing scenarios where developers need immediate insight into failure causes.

Share this tip

Get Python Testing Tips in Your Inbox

Practical Python testing advice delivered to your inbox.