How to Test Exceptions in pytest: Simple Guide with Examples
In
pytest, you test exceptions using the raises context manager. Wrap the code that should raise an exception inside with pytest.raises(ExpectedException): to assert that the exception occurs as expected.Syntax
The basic syntax to test exceptions in pytest uses the raises context manager. You write with pytest.raises(ExpectedException): followed by the code that should raise the exception.
- pytest.raises(): Context manager to catch exceptions.
- ExpectedException: The specific exception type you expect.
- The code inside the
withblock should raise the exception.
python
import pytest with pytest.raises(ValueError): int('invalid')
Example
This example shows how to test a function that raises a ZeroDivisionError when dividing by zero. The test passes if the exception is raised.
python
import pytest def divide(a, b): return a / b def test_divide_by_zero(): with pytest.raises(ZeroDivisionError): divide(10, 0)
Output
============================= test session starts ==============================
collected 1 item
test_example.py . [100%]
============================== 1 passed in 0.03s ===============================
Common Pitfalls
Common mistakes when testing exceptions in pytest include:
- Not using the
withblock, which causes the test to pass even if no exception is raised. - Testing for the wrong exception type.
- Putting code outside the
with pytest.raises()block that should raise the exception.
python
import pytest def divide(a, b): return a / b def test_wrong_usage(): # Wrong: exception raised outside the context manager divide(10, 0) # This will raise and fail the test with pytest.raises(ZeroDivisionError): pass # No exception here # Correct usage: def test_correct_usage(): with pytest.raises(ZeroDivisionError): divide(10, 0)
Quick Reference
| Usage | Description |
|---|---|
| with pytest.raises(ExceptionType): | Start context to expect an exception |
| code_that_raises() | Code inside this block should raise the exception |
| as exc_info | Optional: capture exception info for further checks |
| assert 'message' in str(exc_info.value) | Check exception message content |
Key Takeaways
Use pytest.raises() as a context manager to test exceptions.
Place the code that should raise the exception inside the with block.
Specify the exact exception type you expect to catch.
Avoid putting exception-raising code outside the pytest.raises() block.
You can capture exception details with 'as' to assert on the message.