Sub topic 12
Testing that the right exception is raised
This chapter assumes you can write a custom exception, raise it, and chain it with raise ... from, as covered earlier in this tutorial. You should also know the basics of pytest: test functions, assert, and running pytest from a terminal. Here you will learn what a good exception test checks, how to check it with pytest.raises, and which mistakes make a test pass when it should fail.
What an exception test should prove
A custom exception is part of your code's public contract. Callers write except ConfigError: because you promised that bad configuration raises that type. A test protects that promise. A thorough test can check four things:
- The type: the code raises the class you documented, or a subclass of it.
- The message: the text is readable and names the offending value.
- The data: attributes such as
balanceandamounthold the right values. - The cause: when you used
raise ... from exc,__cause__points to the original error.
You do not need all four every time. Check the type always, and add the others when callers depend on them.
The code under test
The examples use one small module. Save it as app_errors.py.
class AppError(Exception):
"""Base class for errors raised by this application."""
class ConfigError(AppError):
"""Raised when configuration is missing or invalid."""
class InsufficientFundsError(AppError):
"""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 load_port(raw):
try:
return int(raw)
except ValueError as exc:
raise ConfigError(f"invalid port: {raw!r}") from exc
def withdraw(balance, amount):
if amount > balance:
raise InsufficientFundsError(balance, amount)
return balance - amountChecking the type and the message
pytest.raises is a context manager. The test passes only if the block raises the given exception type or a subclass of it. If the block finishes without raising, pytest fails the test with DID NOT RAISE.
import pytest
from app_errors import ConfigError, load_port
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 as info clause gives you an ExceptionInfo object. The exception itself is info.value. Its other useful attributes are info.type (the class) and info.traceback.
The match argument is a regular expression. pytest applies it with re.search to str(exception). It does not need to match the whole message.
Checking attributes
If callers read exc.balance and exc.amount, test those attributes directly. This is more stable than comparing message text, because you can reword a message without breaking callers.
import pytest
from app_errors import InsufficientFundsError, withdraw
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 info.value.amount - info.value.balance == 30The assertions sit after the with block, not inside it. Once an exception is raised inside the block, execution jumps to the end of the block. Any line below the raising call is skipped, so an assertion placed there never runs and the test passes without checking anything.
Escaping special characters in match
Because match is a regular expression, characters such as ., (, ), [, + and ? carry special meaning. A message like "balance is (50)" would not match the pattern "balance is (50)" as written, because the parentheses form a group. Use re.escape when you want a literal comparison.
import re
import pytest
from app_errors import InsufficientFundsError, withdraw
def test_message_is_literal():
expected = "Cannot withdraw 80; balance is 50"
with pytest.raises(InsufficientFundsError, match=re.escape(expected)):
withdraw(50, 80)Testing the hierarchy
The point of a common base class is that one except AppError: catches the whole family. Test that promise in two ways. First, check the class relationships with issubclass. Second, check that raising a specific error is caught through the base class.
import pytest
from app_errors import AppError, ConfigError, InsufficientFundsError, withdraw
@pytest.mark.parametrize("exc_type", [ConfigError, InsufficientFundsError])
def test_inherits_from_app_error(exc_type):
assert issubclass(exc_type, AppError)
def test_base_class_catches_specific_error():
with pytest.raises(AppError):
withdraw(1, 2)Because pytest.raises accepts subclasses, the second test passes even if withdraw is later changed to raise some other AppError subclass. That is sometimes what you want and sometimes not. When the exact class matters, assert it after the block.
import pytest
from app_errors import ConfigError, load_port
def test_exact_type():
with pytest.raises(ConfigError) as info:
load_port("abc")
assert type(info.value) is ConfigErrorUse the exact-type check sparingly. Callers should depend on the base class or the documented class, and an exact check makes harmless refactors, such as splitting ConfigError into two subclasses, break your tests.
Choosing what to assert
The diagram summarizes how to pick checks for a given exception.
Testing chaining and suppressed context
With raise ... from exc, Python stores the original error in __cause__. Check it with isinstance, and for a stricter test also check the message of the cause.
If your code uses raise ... from None to hide an implementation detail, test that too. Python records __suppress_context__ = True in that case, and the original error is still reachable in __context__.
import pytest
from app_errors import ConfigError
def parse_flag(raw):
try:
return {"yes": True, "no": False}[raw]
except KeyError:
raise ConfigError(f"invalid flag: {raw!r}") from None
def test_flag_hides_keyerror():
with pytest.raises(ConfigError) as info:
parse_flag("maybe")
assert info.value.__cause__ is None
assert info.value.__suppress_context__ is TrueTesting pickling
Exceptions cross process boundaries when you use multiprocessing or concurrent.futures.ProcessPoolExecutor. An exception that cannot be rebuilt from its args fails there with a confusing error. A round-trip test catches this in seconds.
import pickle
from app_errors import InsufficientFundsError
def test_insufficient_funds_survives_pickle():
original = InsufficientFundsError(balance=50, amount=80)
clone = pickle.loads(pickle.dumps(original))
assert type(clone) is InsufficientFundsError
assert (clone.balance, clone.amount) == (50, 80)
assert str(clone) == str(original)This test passes because __init__ forwards balance and amount to super().__init__, so args matches the constructor signature. If you removed that call and passed only a formatted string, unpickling would call InsufficientFundsError("Cannot withdraw...") with one argument and raise TypeError. The test would then fail, which is the point of having it.
Testing notes (Python 3.11+)
If you attach context with add_note, the notes are stored in the __notes__ list. Assert on that list instead of parsing a traceback. You can also use info.value.__notes__ directly.
import pytest
from app_errors import ConfigError
def check_section(name):
try:
raise ConfigError("missing key")
except ConfigError as exc:
exc.add_note(f"while reading section {name!r}")
raise
def test_note_names_the_section():
with pytest.raises(ConfigError) as info:
check_section("database")
assert info.value.__notes__ == ["while reading section 'database'"]Recent pytest versions also check notes in match, but reading __notes__ is clearer and works the same across versions.
Common mistakes in exception tests
| Mistake | Why it hurts | Fix |
|---|---|---|
| `pytest.raises(Exception)` | Passes for any error, including a typo that raises `NameError` | Name the custom class |
| Assertions inside the `with` block | They never run after the raise | Move them below the block |
| Unescaped `match` text | Regex characters change the meaning, giving false failures or false passes | Use `re.escape` for literal text |
| Comparing full message strings everywhere | Rewording a message breaks many tests | Assert attributes, and keep one message test |
| Testing only the failure path | A function that always raises would pass | Add a test for the success path |
| Using `try/except` with `pass` in tests | If nothing is raised, the test passes | Use `pytest.raises` |
The standard library alternative
If a project uses unittest, the equivalent is self.assertRaises as a context manager. It works the same way: with self.assertRaises(ConfigError) as ctx: gives you ctx.exception. Use assertRaisesRegex for message matching. The same rules apply, including keeping assertions outside the with block.
Exercise
A teammate wrote this test for withdraw. It always passes, even if withdraw is broken to return a number instead of raising. Find two problems and write a corrected version.
def test_withdraw():
with pytest.raises(Exception):
withdraw(50, 80)
assert False
Show answer
First, pytest.raises(Exception) is too broad. It would also pass if withdraw raised an unrelated error such as TypeError. Second, the code inside the block does not prove the right thing, and assert False is unreachable when withdraw raises. If withdraw returned normally, the assert False would raise AssertionError, which is an Exception, so pytest.raises would swallow it and the test would pass anyway. A corrected version:
def testwithdrawrejects_overdraft():
with pytest.raises(InsufficientFundsError) as info:
withdraw(50, 80)
assert info.value.balance == 50
assert info.value.amount == 80
If withdraw returned normally, pytest would fail the test with DID NOT RAISE.
Exercise
You change InsufficientFundsError.__init__ so it calls super().__init__(f"Cannot withdraw {amount}; balance is {balance}") and stores balance and amount as attributes. Which test from this chapter now fails, and why?
Show answer
The pickle round-trip test fails. Unpickling rebuilds the exception by calling the class with args, which is now a single formatted string. The constructor needs two arguments, balance and amount, so Python raises TypeError. Passing balance and amount to super().__init__ and defining __str__ fixes it.