Sub topic 5
Testing expected errors with pytest.raises
This chapter assumes you can write and run pytest test functions, use plain assert, and know how Python raises and catches exceptions. If a test file runs for you with pytest -v, you have what you need.
Why test the error path
A function's contract includes what it refuses to do. If total should reject a negative tax rate, a test should prove it. Without that test, someone can delete the check and nothing fails.
You could write this with try and except, but it is easy to get wrong:
def test_negative_tax_rate_bad():
try:
total([1], tax_rate=-0.5)
except ValueError:
passThis test passes when the exception is raised. It also passes when nothing is raised, because the try block simply finishes. A test that cannot fail checks nothing. pytest.raises fixes this by failing when the expected exception does not occur.
The basic form
Here is the function under test again.
# cart.py
def total(prices, tax_rate=0.0):
if tax_rate < 0:
raise ValueError("tax_rate must be non-negative")
return sum(prices) * (1 + tax_rate)pytest.raises is a context manager. It runs the code in the with block and checks what happens.
# test_cart.py
import pytest
from cart import total
def test_negative_tax_rate_is_rejected():
with pytest.raises(ValueError):
total([1], tax_rate=-0.5)The outcomes are:
| What happens inside the block | Result |
|---|---|
| A `ValueError` (or subclass) is raised | Test passes, and the exception is swallowed |
| No exception is raised | Test fails with `DID NOT RAISE` |
| A different exception is raised, such as `TypeError` | Test fails, and the original exception propagates |
The second row is the one that try/except misses.
Matching the message
Checking only the type is often too loose. Many different problems raise ValueError. Use match to check the message:
def test_negative_tax_rate_message():
with pytest.raises(ValueError, match="non-negative"):
total([1], tax_rate=-0.5)match is a regular expression, applied with re.search against str(exception). That has three consequences:
- It matches anywhere in the message, so
"non-negative"matches"tax_rate must be non-negative". - Special characters carry regex meaning. A
.matches any character, and(or+can cause errors or surprising matches. - To match literal text, escape it with
re.escape.
import re
import pytest
def parse_port(text):
if not text.isdigit():
raise ValueError(f"invalid port (got {text!r})")
return int(text)
def test_parse_port_message_is_literal():
message = "invalid port (got 'abc')"
with pytest.raises(ValueError, match=re.escape(message)):
parse_port("abc")Without re.escape, the parentheses would form a regex group, and the pattern would no longer match the literal parentheses in the message.
Inspecting the exception object
Use as to capture an ExceptionInfo object. It wraps the exception and exposes it through .value.
import pytest
class InsufficientFunds(Exception):
def __init__(self, needed, available):
super().__init__(f"need {needed}, have {available}")
self.needed = needed
self.available = available
def withdraw(balance, amount):
if amount > balance:
raise InsufficientFunds(amount, balance)
return balance - amount
def test_withdraw_reports_shortfall():
with pytest.raises(InsufficientFunds) as excinfo:
withdraw(50, 80)
assert excinfo.value.needed == 80
assert excinfo.value.available == 50
assert excinfo.type is InsufficientFundsUseful attributes of ExceptionInfo:
excinfo.valueis the exception instance, so you can read custom attributes.excinfo.typeis the exception class.excinfo.tracebackis the traceback, which is rarely needed in unit tests.
Place the assertions after the with block, not inside it. Once an exception is raised inside the block, execution leaves the block, so any line after the raising call would never run.
# Wrong: the assert never executes
with pytest.raises(ValueError) as excinfo:
total([1], tax_rate=-0.5)
assert "non-negative" in str(excinfo.value)Also, excinfo.value is only populated after the block ends. Reading it inside the block raises an error.
Keep the block small
Put only the line you expect to raise inside the with block. If you put setup code in the block, a failure in that setup can raise the expected exception type and make the test pass for the wrong reason.
# Risky: build_cart might itself raise ValueError
with pytest.raises(ValueError):
cart = build_cart(items)
total(cart, tax_rate=-0.5)
# Better: setup is outside the block
cart = build_cart(items)
with pytest.raises(ValueError):
total(cart, tax_rate=-0.5)Likewise, prefer a specific exception class over Exception. pytest.raises(Exception) passes on almost any bug, including a NameError from a typo.
Subclasses and exact types
pytest.raises(E) accepts E and any subclass of E. For example, pytest.raises(LookupError) passes when a KeyError or IndexError is raised. This is usually what you want when the contract is about a family of errors.
If you need the exact class, check it explicitly:
def test_missing_key_is_exactly_keyerror():
with pytest.raises(LookupError) as excinfo:
{}["missing"]
assert excinfo.type is KeyErrorTo accept several unrelated types, pass a tuple:
def test_bad_conversion():
with pytest.raises((ValueError, TypeError)):
int(None)Parametrizing error cases
When several inputs should all fail, combine raises with parametrization (covered fully in a later chapter). Each case is reported separately.
import pytest
from cart import total
@pytest.mark.parametrize("rate", [-1, -0.01, -100])
def test_any_negative_rate_is_rejected(rate):
with pytest.raises(ValueError, match="non-negative"):
total([10], tax_rate=rate)Related tools
pytest.warns(UserWarning)checks that code emits a warning, and it works likeraises.pytest.fail("message")fails a test explicitly.@pytest.mark.xfail(raises=ValueError)marks a known bug and only tolerates that exception type. This differs fromraises: it records a test that is expected to fail, whilepytest.raisesasserts intended behavior.
Common mistakes
- Using
try/exceptwithpass, which passes when nothing is raised. - Putting assertions inside the
withblock after the raising line. - Forgetting that
matchis a regex, then getting failures on messages with(,., or+. - Wrapping too much code in the block, or using
Exceptionas the expected type. - Reading
excinfo.valuebefore the block has finished.
Exercises
Exercise
A test uses with pytest.raises(ValueError): around a call, and the call returns normally without raising. What does pytest report, and why is this better than a try/except ValueError: pass version?
Show answer
pytest fails the test with DID NOT RAISE. The try/except version passes silently when no exception occurs, so it cannot detect a missing error check.
Exercise
Write a test for parse_port("8o80") that confirms a ValueError is raised and that the message contains the text got '8o80'. Which function do you use to make the quotes and text match literally?
Show answer
Use re.escape for the pattern:
import re
import pytest
def testparseportreportsbadtext():
with pytest.raises(ValueError, match=re.escape("got '8o80'")):
parseport("8o80")
Here re.escape is optional for this particular text, but it is the safe habit whenever the message contains regex characters.
Exercise
This test never checks the attribute. Why, and how do you fix it? with pytest.raises(InsufficientFunds) as excinfo: withdraw(50, 80) assert excinfo.value.needed == 80
Show answer
withdraw(50, 80) raises, so execution leaves the block and the assert line never runs. Move the assert out of the with block, dedented to the function level.