Sub topic 5
Testing expected errors with pytest.raises
This chapter assumes you can write and run a basic pytest test, and that you know how Python raises and catches exceptions. It builds on plain assert from the previous chapter.
Why test errors
A function's contract includes what it refuses to do. If total is given a negative tax rate, it should fail loudly instead of returning a wrong number. A test that checks this keeps the guard in place when the code changes later.
Here is the function under test:
# 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)The basic form
pytest.raises is a context manager. The test passes only if the code inside the with block raises the named exception type.
# test_cart.py
import pytest
from cart import total
def test_negative_tax_rate_is_rejected():
with pytest.raises(ValueError, match="non-negative"):
total([1], tax_rate=-0.5)The test fails in two cases:
- The block finishes without raising anything.
- The block raises a different exception type, such as
TypeError. That exception is not caught, so it appears as the failure.
Subclasses count as a match. pytest.raises(Exception) accepts almost anything, so name the most specific type you expect.
Checking the message with match
The match argument is a regular expression. pytest applies it with re.search to the string form of the exception. It does not need to match the whole message.
Because it is a regex, characters such as ., ( and + have special meaning. If your message contains them, wrap the text with re.escape:
import re
import pytest
def test_message_with_special_characters():
with pytest.raises(ValueError, match=re.escape("bad value (got -1)")):
raise ValueError("bad value (got -1)")Inspecting the exception
Use as to get an ExceptionInfo object. Its .value attribute holds the exception instance, and .type holds its class.
import pytest
from cart import total
def test_exception_details():
with pytest.raises(ValueError) as excinfo:
total([1], tax_rate=-1)
assert excinfo.type is ValueError
assert "non-negative" in str(excinfo.value)Read excinfo after the with block, as shown. Inside the block, the exception has not been raised yet.
Common mistakes
| Mistake | Result | Fix |
|---|---|---|
| Catching `Exception` | Passes on unrelated bugs | Name the specific type |
| Omitting `match` | Passes with the wrong message | Add `match` for important messages |
| Several calls in the block | Only the first raising call is tested | One raising call per block |
| Unescaped regex characters in `match` | False failures | Use `re.escape` |
How the flow works
Exercise
A test uses with pytest.raises(ValueError): and the code inside raises TypeError. Does the test pass? What if the code inside raises KeyError and the test expects LookupError?
Show answer
The first test does not pass. TypeError is not a ValueError, so it propagates and the test fails. The second test passes, because KeyError is a subclass of LookupError and pytest.raises accepts subclasses.
Exercise
Write a test that checks total([1], tax_rate=-0.5) raises ValueError, and then asserts that the message contains the text "tax_rate".
Show answer
def testmessagementionsparameter(): with pytest.raises(ValueError) as excinfo: total([1], taxrate=-0.5) assert "tax_rate" in str(excinfo.value)