0
0
PytestHow-ToBeginner ยท 3 min read

How to Assert True in pytest: Simple Syntax and Examples

In pytest, you assert true by using the 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.

python
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.

python
def test_is_true():
    value = 5 > 3
    assert value

def test_is_true_with_message():
    value = (2 + 2) == 5
    assert value, "Math is broken!"
Output
============================= test session starts ============================= collected 2 items test_sample.py .F [100%] ================================== FAILURES =================================== __________________________ test_is_true_with_message _________________________ def test_is_true_with_message(): value = (2 + 2) == 5 > assert value, "Math is broken!" E AssertionError: Math is broken! E assert False test_sample.py:7: AssertionError =========================== short test summary info =========================== FAILED test_sample.py::test_is_true_with_message - AssertionError: Math is broken! ============================== 1 failed, 1 passed ==============================
โš ๏ธ

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.

python
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 condition for clarity.
  • pytest automatically reports assertion failures with details.
โœ…

Key Takeaways

Use simple assert statements like assert condition to check truth in pytest.
Add a custom message after a comma to explain failures clearly.
Avoid comparing with True explicitly; just assert the condition directly.
pytest shows detailed failure info automatically when assertions fail.