How to Assert Exceptions in Python with pytest.raises
Use pytest.raises as a context manager to assert that a function raises an expected exception and inspect its message in pytest tests.
pip install pytest
Python code
19 linesimport pytest
def divide(a, b):
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
def test_divide_by_zero():
with pytest.raises(ValueError) as exc_info:
divide(10, 0)
assert str(exc_info.value) == "Cannot divide by zero"
assert "zero" in str(exc_info.value)
def test_divide_normal():
assert divide(10, 2) == 5
if __name__ == "__main__":
import sys
sys.exit(pytest.main([__file__, "-v"]))
Output
============================= test session starts ==============================
platform linux -- Python 3.11.0, pytest-8.0.0, pluggy-1.3.0
rootdir: /path/to/test
collected 2 items
test_example.py::test_divide_by_zero PASSED [ 50%]
test_example.py::test_divide_normal PASSED [100%]
============================== 2 passed in 0.01s ===============================
How it works
pytest.raises(ValueError) wraps the call divide(10, 0) and fails the test if no ValueError is raised. Assigning the context to exc_info gives access to the raised exception via exc_info.value, letting you assert on its type and message. The context manager ensures the rest of the test only runs if the exception is raised, keeping your checks focused. This pattern is the standard way to validate error handling in pytest. It also works with any exception class and can match subclasses.
Common mistakes
- Using `pytest.raises` without the `as exc_info` clause when you need to check the message.
- Forgetting to call the function inside the `with` block, so a missing exception goes unnoticed.
- Asserting on `exc_info.type` instead of `exc_info.value` for the message.
Variations
- Use `pytest.raises(ValueError, match='zero')` to check the message with a regex.
- Use `with pytest.raises(ValueError):` without capturing details when only the exception type matters.
Real-world use cases
- Verifying that a config parser raises a clear error when a required key is missing.
- Checking that an API client raises a custom exception on non-200 HTTP responses.
- Validating that a payment processor rejects invalid amounts with the expected error.
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.