SyntaxStudy
Sign Up
Python Beginner 3 min read

Testing Exceptions

Exception Testing

Use pytest.raises as a context manager to assert that the expected exception is raised.

Example
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)
Pro Tip

The match parameter takes a regex — use it to verify the error message, not just the type.