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

  1. Import pytest.
  2. Wrap the failing code in with pytest.raises(ExpectedException):.
  3. 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

  • match accepts a regex pattern to verify the exception message.
  • In unittest, use self.assertRaises() or self.assertRaisesRegex().
  • Testing exceptions ensures that your error paths are exercised and behave correctly.

Common issues

  • pytest.raises without the context manager syntax does not work in recent versions.
  • Forgetting to call the function inside the with block means the exception is never raised.
  • Catching a parent exception class when testing can mask unexpected subclass exceptions.