How do I test that code raises exceptions with pytest?
· Category: Python Programming
Short answer
Use pytest.raises(ExceptionType) as a context manager to assert that a block of code raises a specific exception. You can also inspect the raised exception's message and attributes.
Steps
- Import
pytest. - Wrap the failing code in
with pytest.raises(ExpectedException):. - Optionally capture the exception info for further assertions.
import 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, match="Cannot divide by zero"):
divide(10, 0)
# Inspecting the exception
def test_divide_exception_info():
with pytest.raises(ValueError) as exc_info:
divide(10, 0)
assert "zero" in str(exc_info.value)
Tips
matchaccepts a regex pattern to verify the exception message.- In
unittest, useself.assertRaises()orself.assertRaisesRegex(). - Testing exceptions ensures that your error paths are exercised and behave correctly.
Common issues
pytest.raiseswithout the context manager syntax does not work in recent versions.- Forgetting to call the function inside the
withblock means the exception is never raised. - Catching a parent exception class when testing can mask unexpected subclass exceptions.