How to Use Assert in pytest for Simple and Effective Testing
In pytest, use the
assert statement to check if a condition is true. If the condition is false, pytest reports a test failure with helpful details automatically. This makes writing tests simple and readable without extra syntax.Syntax
The basic syntax for using assert in pytest is simple: assert condition. If the condition is true, the test passes silently. If false, pytest raises an AssertionError and shows the failing expression.
You can also add an optional message: assert condition, 'error message' to show custom info on failure.
python
assert x == 5 assert y > 0, 'y must be positive'
Example
This example shows a simple pytest test function using assert to check if a function returns the expected result.
python
def add(a, b): return a + b def test_add(): result = add(2, 3) assert result == 5 assert result != 4, 'Result should not be 4' # Run this with pytest to see the test pass
Output
============================= test session starts ==============================
collected 1 item
test_sample.py . [100%]
============================== 1 passed in 0.01s ===============================
Common Pitfalls
Common mistakes when using assert in pytest include:
- Using
assertwith expressions that have side effects, which can cause flaky tests. - Not writing clear assertions, making failures hard to understand.
- Using
assertinside try-except blocks that catch AssertionError, hiding test failures.
Always write simple, clear assertions and avoid catching assertion errors.
python
def test_wrong(): x = 3 # Wrong: catching AssertionError hides failure try: assert x == 5 except AssertionError: pass # This hides the test failure def test_right(): x = 3 assert x == 3 # Clear and simple assertion
Quick Reference
Here is a quick summary of using assert in pytest:
| Usage | Description |
|---|---|
| assert condition | Passes if condition is true, fails if false |
| assert condition, 'message' | Fails with custom message if condition is false |
| assert x == y | Checks equality between x and y |
| assert x in y | Checks if x is contained in y |
| assert isinstance(obj, type) | Checks object type |
Key Takeaways
Use simple assert statements to check conditions in pytest tests.
Pytest shows detailed info automatically when asserts fail.
Avoid catching AssertionError to prevent hiding test failures.
Add custom messages to asserts for clearer failure explanations.
Write clear and side-effect-free assertions for reliable tests.