How to Write a pytest Test Function with assert Equal in Python
Define simple pytest test functions that use assert to verify result equality and run them with pytest.main.
pip install pytest
Python code
19 linesimport pytest
def add(a, b):
return a + b
def test_add_positive_numbers():
result = add(2, 3)
assert result == 5
def test_add_negative_numbers():
result = add(-2, -3)
assert result == -5
def test_add_mixed_numbers():
result = add(2, -3)
assert result == -1
if __name__ == "__main__":
pytest.main([__file__, "-v"])
Output
============================= test session starts ==============================
platform darwin -- Python 3.11.0, pytest-7.4.0, pluggy-1.3.0
rootdir: /path/to/your/test
collected 3 items
test_file.py ... [100%]
============================== 3 passed in 0.01s ===============================
How it works
Each test function is named with a test_ prefix so pytest discovers it automatically. Inside the test, you call the function under test and use the assert statement to compare the actual result to the expected value. If the assertion fails, pytest reports a detailed diff showing both the expected and actual values. Running pytest.main([__file__, "-v"]) lets you execute the tests directly from the script with verbose output.
Common mistakes
- Forgetting the test_ prefix on function names, causing pytest to skip them
- Using `assert result == expected` without any message; adding a helpful message improves debugging
- Naming the test file without a `test_` prefix, so pytest doesn't collect it by default
Variations
- Use `pytest.approx` for floating-point comparisons to avoid precision issues
- Parameterize the test with `@pytest.mark.parametrize` to test multiple input sets without duplicating code
Real-world use cases
- Verifying that a data transformation function returns the correct result for known inputs.
- Ensuring that an API client correctly parses a response payload into expected fields.
- Checking that a validation helper returns the expected error dictionary for invalid data.
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.