Sub topic 12
Testing that the right exception is raised
This chapter assumes you can write a custom exception, raise it with raise ... from, and run basic tests with pytest. A test for an exception checks the type, the message, and the data the exception carries. It also checks that the original cause was kept.
Checking type and message
pytest.raises is a context manager. The test passes only if the code inside the with block raises the given exception type or a subclass of it. If nothing is raised, or a different exception is raised, the test fails.
import pytest
class AppError(Exception):
"""Base class for errors raised by this application."""
class ConfigError(AppError):
"""Raised when configuration is missing or invalid."""
def load_port(raw):
try:
return int(raw)
except ValueError as exc:
raise ConfigError(f"invalid port: {raw!r}") from exc
def test_load_port_rejects_text():
with pytest.raises(ConfigError, match="invalid port") as info:
load_port("abc")
assert isinstance(info.value.__cause__, ValueError)The match argument is a regular expression checked with re.search against str(exception). It does not need to match the whole message. The as info name is an ExceptionInfo object, and info.value is the exception instance. Read it after the with block ends, because the block stops at the line that raises.
The last assertion checks __cause__. This confirms that raise ... from exc ran and the low-level ValueError was preserved.
Escaping special characters
Messages often contain characters that mean something in a regular expression, such as ., (, or ?. Wrap the text in re.escape when you want a literal match.
import re
with pytest.raises(ConfigError, match=re.escape("invalid port: 'abc'")):
load_port("abc")Testing attributes instead of text
If your exception carries data, assert on the attributes. Message wording can change without breaking callers, but attribute names are part of your interface.
import pytest
class InsufficientFundsError(Exception):
"""Raised when a withdrawal exceeds the available balance."""
def __init__(self, balance, amount):
super().__init__(balance, amount)
self.balance = balance
self.amount = amount
def __str__(self):
return f"Cannot withdraw {self.amount}; balance is {self.balance}"
def withdraw(balance, amount):
if amount > balance:
raise InsufficientFundsError(balance, amount)
return balance - amount
def test_withdraw_reports_shortfall():
with pytest.raises(InsufficientFundsError) as info:
withdraw(50, 80)
assert info.value.balance == 50
assert info.value.amount == 80
assert str(info.value) == "Cannot withdraw 80; balance is 50"Testing the hierarchy
Because pytest.raises accepts subclasses, you can test the promise that callers can catch the whole family through the base class. Use the exact subclass when you test one function. Use the base class in one test that guards the hierarchy.
def test_config_error_belongs_to_app_errors():
assert issubclass(ConfigError, AppError)
def test_callers_can_catch_base_class():
with pytest.raises(AppError):
load_port("abc")Testing that pickling works
If you followed the args rule from the earlier chapter, a pickle round trip should rebuild the exception. A short test protects that rule.
import pickle
def test_insufficient_funds_survives_pickle():
original = InsufficientFundsError(balance=50, amount=80)
clone = pickle.loads(pickle.dumps(original))
assert clone.balance == 50
assert clone.amount == 80This test fails if __init__ takes arguments that never reach super().__init__. Unpickling then calls the constructor with the wrong arguments.
Common test mistakes
- Putting setup code inside the
withblock. If the setup raises the expected exception, the test passes for the wrong reason. Keep only the call under test inside the block. - Putting assertions inside the
withblock after the raising line. They never run. - Testing with
pytest.raises(Exception). This passes for almost any bug, including aTypeErrorfrom a typo.
Exercise
A test contains with pytest.raises(ConfigError): value = load_port("abc"); assert value == 80. Why does the assertion never run, and where should you move it?
Show answer
load_port("abc") raises ConfigError, so the block ends at that line and the assert is skipped. Because pytest.raises swallows the exception, the test passes without ever checking the assertion. Remove it, and put any checks about the exception after the block, using info.value from with pytest.raises(ConfigError) as info:.