Testing Exceptions with pytest.raises
Sometimes you need to verify that your code raises an exception under certain conditions. pytest provides the pytest.raises context manager for this purpose.
Basic Usage
Wrap the code that should raise an exception inside pytest.raises:
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):
divide(10, 0)
If divide(10, 0) raises a ValueError, the test passes. If it does not raise an exception, the test fails.
Checking the Exception Message
You can verify the exact error message using match:
def test_divide_by_zero_message():
with pytest.raises(ValueError, match="Cannot divide by zero"):
divide(10, 0)
def test_divide_by_zero_partial_match():
with pytest.raises(ValueError, match="divide"):
divide(10, 0)
The match parameter uses regex matching, so partial matches work too.
Accessing the Exception
You can capture the exception object to inspect it further:
def test_exception_details():
with pytest.raises(ValueError) as exc_info:
divide(10, 0)
assert str(exc_info.value) == "Cannot divide by zero"
assert exc_info.type is ValueError
Using pytest.raises as a Decorator
Instead of a context manager, you can use it as a decorator:
@pytest.mark.parametrize("a,b", [(1, 0), (5, 0), (-3, 0)])
def test_divide_all_by_zero(a, b):
with pytest.raises(ValueError):
divide(a, b)