Exception Testing
Use pytest.raises as a context manager to assert that the expected exception is raised.
Use pytest.raises as a context manager to assert that the expected exception is raised.
import pytest
def test_divide_by_zero():
with pytest.raises(ZeroDivisionError):
result = 1 / 0
def test_invalid_age():
with pytest.raises(ValueError, match="Age must be"):
create_user(age=-5)
def test_exception_details():
with pytest.raises(ValueError) as exc_info:
create_user(age=-5)
assert "positive" in str(exc_info.value)
The match parameter takes a regex — use it to verify the error message, not just the type.