How to Assert Exception in pytest: Simple Guide with Examples
In
pytest, you can assert that an exception is raised using the pytest.raises() context manager. Wrap the code that should raise the exception inside this context, and pytest will check if the expected exception occurs.Syntax
The basic syntax to assert an exception in pytest uses the pytest.raises() context manager. You pass the expected exception type to it, then run the code inside the with block.
pytest.raises(ExceptionType): Specifies the exception you expect.withblock: Contains the code that should raise the exception.
python
import pytest def test_example(): with pytest.raises(ValueError): int('invalid')
Example
This example shows how to test that converting a non-numeric string to an integer raises a ValueError. The test passes if the exception is raised, otherwise it fails.
python
import pytest def test_value_error(): with pytest.raises(ValueError): int('abc') # Run this test with: pytest -q --tb=short
Output
============================= test session starts ==============================
collected 1 item
test_value_error.py . [100%]
============================== 1 passed in 0.03s ===============================
Common Pitfalls
Common mistakes when asserting exceptions in pytest include:
- Not using
withblock, which means the exception won't be caught by pytest. - Expecting the wrong exception type, causing the test to fail unexpectedly.
- Placing code outside the
with pytest.raises()block that raises the exception.
Always ensure the code that should raise the exception is inside the with block.
python
import pytest def test_wrong_usage(): # Wrong: exception raised outside the context manager int('abc') # This will cause the test to error, not fail gracefully with pytest.raises(ValueError): pass # No exception raised here # Correct usage: def test_correct_usage(): with pytest.raises(ValueError): int('abc')
Quick Reference
Use this quick reference to remember how to assert exceptions in pytest:
| Action | Code Example |
|---|---|
| Assert exception raised | with pytest.raises(ValueError):\n code_that_raises() |
| Check exception message | with pytest.raises(ValueError) as exc_info:\n code_that_raises()\nassert 'invalid' in str(exc_info.value) |
| Fail if no exception | pytest.raises() fails test if exception not raised |
Key Takeaways
Use pytest.raises() as a context manager to assert exceptions.
Place the code that should raise the exception inside the with block.
Specify the exact exception type you expect to catch.
You can capture the exception info to check the message if needed.
Avoid raising exceptions outside the pytest.raises() block.