0
0
PytestHow-ToBeginner ยท 3 min read

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 if actual value equals expected value.
  • If the assertion fails, pytest shows a clear error message with both values.
python
assert actual == expected
๐Ÿ’ป

Example

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 assert is 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 == expected for 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.