How to Write pytest Test Function Assert Equal in Python
Write three pytest test functions that assert the result of an add() function equals an expected numeric value.
Requires third-party packages — install first
pip install pytest
Python code
16 linesimport pytest
def add(a, b):
return a + b
def test_add_positive_numbers():
assert add(2, 3) == 5
def test_add_negative_numbers():
assert add(-1, -2) == -3
def test_add_mixed_numbers():
assert add(5, -3) == 2
if __name__ == "__main__":
pytest.main([__file__, "-v"])
Output
============================= test session starts ==============================
platform linux -- Python 3.11.0, pytest-7.4.0, pluggy-1.0.0
rootdir: /home/user
collected 3 items
test_example.py ... [100%]
============================== 3 passed in 0.01s ===============================
How it works
Each test function starts with test_ so pytest auto-discovers it. The assert statement checks that add(a, b) equals the expected result; if false, pytest raises AssertionError and marks the test failed. Using functions keeps tests isolated and readable. Running pytest.main([__file__, "-v"]) when the script executes directly runs the tests with verbose output.
Common mistakes
- Forgetting to import pytest even though it's only used for main invocation
- Not naming test functions with the `test_` prefix, so pytest skips them
- Comparing floats with `==` without tolerance, causing flaky tests
Variations
- Use `@pytest.mark.parametrize` to generate multiple test cases from one function
- Use the `unittest` module with `self.assertEqual()` instead of pytest style
Real-world use cases
- Verifying pure functions (add, string transformations) in a library's test suite.
- Running regression checks in CI pipelines after every commit to catch broken logic.
- Validating math-heavy code like price calculations in a web application.
Sponsored
More from Testing & modern typing
- Capture stdout and stderr with pytest capsys easy
- Characterization Test for Legacy Python Code medium
- Dataclass with Type Hints Fields in Python easy
- Dependency Injection in Python for Testability easy
- Design Data Helpers with Python TypedDict and Literal easy
- Fix and Test a Regression Bug in Python with Unit Tests easy
Keep learning
Related tutorials and quizzes for this topic.