0
0
PytestHow-ToBeginner · 3 min read

How to Use Custom Assertion Message in pytest for Clearer Tests

In pytest, you can add a custom assertion message by using a comma after the assertion expression followed by a string message, like assert condition, "custom message". This message will show up if the assertion fails, helping you understand the problem quickly.
📐

Syntax

The syntax for adding a custom assertion message in pytest is simple. You write assert followed by the condition you want to check, then a comma, and then a string message that explains the failure.

Here’s what each part means:

  • assert: The keyword to check a condition.
  • condition: The expression that should be true.
  • , "message": A string that shows if the condition is false.
python
assert condition, "custom message"
💻

Example

This example shows how to use a custom assertion message in a pytest test function. If the assertion fails, pytest will display the message to help you understand what went wrong.

python
def test_sum():
    total = 2 + 2
    assert total == 5, f"Sum should be 5 but got {total}"
Output
E AssertionError: Sum should be 5 but got 4 E assert 4 == 5
⚠️

Common Pitfalls

One common mistake is forgetting to add the comma before the message, which causes a syntax error or unexpected behavior. Another is using the message without formatting dynamic values, so the message does not show useful details.

Always use a comma and format your message if you want to include variable values.

python
def test_wrong():
    total = 2 + 2
    # Wrong: missing comma, this is a syntax error
    # assert total == 5 "Sum should be 5"

    # Right: with comma and formatted message
    assert total == 5, f"Sum should be 5 but got {total}"
📊

Quick Reference

  • Use assert condition, "message" to add custom messages.
  • Include variable values with f-strings for clarity.
  • Always separate the message with a comma.
  • Custom messages help debug test failures faster.

Key Takeaways

Add a custom message after a comma in the assert statement to clarify failures.
Use f-strings to include dynamic values in your assertion messages.
Never forget the comma between the condition and the message to avoid syntax errors.
Custom messages make test failures easier to understand and fix.