How to Assert Equal in pytest: Simple Syntax and Examples
In pytest, you assert equality using the simple Python
assert statement with the == operator, like assert actual == expected. Pytest automatically reports failures with detailed information when the assertion is false.Syntax
The basic syntax to assert equality in pytest is:
assert actual == expected: Checks ifactualvalue equalsexpectedvalue.- If the assertion fails, pytest shows a clear error message with both values.
python
assert actual == expectedExample
This example shows a simple test function that checks if the sum of two numbers equals the expected result using assert.
python
def test_sum(): result = 2 + 3 expected = 5 assert result == expected
Output
============================= test session starts =============================
collected 1 item
test_sample.py . [100%]
============================== 1 passed in 0.01s ==============================
Common Pitfalls
Common mistakes when asserting equality in pytest include:
- Using
=instead of==(assignment vs comparison). - Not understanding that
assertis a Python keyword, not a pytest function. - Comparing incompatible types that always fail.
python
def test_wrong_assert(): value = 10 # Wrong: assignment instead of comparison # assert value = 10 # SyntaxError # Correct: assert value == 10
Quick Reference
Tips for asserting equality in pytest:
- Use
assert actual == expectedfor clear, readable tests. - Pytest shows detailed error messages automatically on failure.
- Use descriptive variable names to make tests easy to understand.
Key Takeaways
Use Python's
assert actual == expected to check equality in pytest.Pytest provides clear failure messages without extra code.
Avoid using
= instead of == in assertions.Write simple, readable assertions for easy debugging.
Test functions must start with
test_ for pytest to discover them.