How to Assert True in pytest: Simple Syntax and Examples
assert keyword followed by the condition you expect to be true, like assert condition. If the condition is true, the test passes; if false, pytest reports a failure.Syntax
The basic syntax to assert true in pytest is simple. Use the assert keyword followed by the condition you want to check. If the condition evaluates to True, the test passes. If it evaluates to False, pytest raises an assertion error and marks the test as failed.
Optionally, you can add a message after a comma to show a custom error message when the assertion fails.
assert condition assert condition, "Custom failure message"
Example
This example shows a simple pytest test function that asserts a condition is true. The test will pass if the condition is true and fail if it is false.
def test_is_true(): value = 5 > 3 assert value def test_is_true_with_message(): value = (2 + 2) == 5 assert value, "Math is broken!"
Common Pitfalls
One common mistake is to write assert True == condition or assert condition == True, which is unnecessary and less readable. Simply use assert condition.
Another pitfall is forgetting that assert checks the truthiness of the expression, so if the expression is not a boolean, it still works as long as it evaluates to a truthy value.
def test_wrong_way(): value = 10 # Less readable and unnecessary assert value == True def test_right_way(): value = 10 assert value # This passes because 10 is truthy
Quick Reference
- assert condition: Passes if condition is true.
- assert condition, "message": Shows message if assertion fails.
- Use simple
assert conditionfor clarity. - pytest automatically reports assertion failures with details.
Key Takeaways
assert condition to check truth in pytest.