pytest.raises: Assert Exceptions in Python Tests
What you’ll learn
Section titled “What you’ll learn”- Why hand-written
try/excepttests pass by accident, and howpytest.raisesprevents it. - What
pytest.raisesmatches (type and subclasses, tuples), and what happens when the wrong exception or none is raised. - How to check the message with
match=, inspect the exception throughExceptionInfo, and add a predicate withcheck=. - How to assert on exception groups with
pytest.RaisesGroupandpytest.RaisesExc(pytest 8.4). - How to test chained exceptions and keep error tests specific.
Summary
Section titled “Summary”pytest.raises(ExpectedException) is a context manager that passes only if the code in its block raises that exception type or a subclass. It fails with DID NOT RAISE when nothing is raised, and lets any other exception propagate so the test fails with the real error. Optional match= and check= arguments narrow the expectation, and the as target gives you the exception for further assertions. It is current in pytest 9.2.0 (the latest release at the time of writing).
The problem it solves
Section titled “The problem it solves”An error test has to fail in two situations: the wrong exception is raised, or no exception is raised at all. Hand-written tests usually cover only the first. In this OrdersPortal sample, a refactor deleted the check that stops refunds larger than the order total.
The samples are pytest test modules: install pytest in a virtual environment, save the files side by side and run pytest -v. They were run with pytest 9.2.0 on CPython 3.14.6; header lines are trimmed from the output.
from decimal import Decimal
def refund(order_total: Decimal, amount: Decimal) -> Decimal: if amount <= 0: raise ValueError("refund amount must be positive") # Bug: the check that amount <= order_total was deleted in a refactor. return order_total - amountfrom decimal import Decimal
import pytest
from refunds import refund
def test_over_refund_rejected_try_except(): # Before: hand-written. Nothing is raised, nothing is asserted, the test passes. try: refund(Decimal("30.00"), Decimal("45.00")) except ValueError as exc: assert "exceeds order total" in str(exc)
def test_over_refund_rejected(): # After: pytest.raises fails when nothing is raised. with pytest.raises(ValueError, match="exceeds order total"): refund(Decimal("30.00"), Decimal("45.00"))test_refunds.py::test_over_refund_rejected_try_except PASSED [ 50%]test_refunds.py::test_over_refund_rejected FAILED [100%]
=================================== FAILURES ===================================__________________________ test_over_refund_rejected ___________________________
def test_over_refund_rejected(): # After: pytest.raises fails when nothing is raised.> with pytest.raises(ValueError, match="exceeds order total"): ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^E Failed: DID NOT RAISE ValueError
test_refunds.py:18: Failed========================= 1 failed, 1 passed in 0.02s ==========================The try/except version is green while the bug ships. Fixing it needs an else: pytest.fail(...) branch in every such test; pytest.raises builds that in.
How it works
Section titled “How it works”pytest.raises behaves like an except clause wrapped around the block:
- Type matching follows
exceptrules: the expected class matches itself and its subclasses, and a tuple matches any of its members. - No exception raises
Failed: DID NOT RAISE <type>. - A different exception is not caught. It propagates, so the test fails with the original traceback (for example
KeyError: 'k'), which is usually what you want to see. - The block stops at the raise. Lines after the raising call inside the
withnever run; put assertions on the exception after the block. as excinfobinds apytest.ExceptionInfo. Its.type,.value(the exception object) and.tracebackare filled in when the block exits, and.match(pattern)runs the same regex check asmatch=.
The message checks:
match=takes a string or compiled pattern and runsre.searchagainststr(exception)and its PEP 678__notes__. It is a search, not equality: anchor with^...$when you need the whole message, and usere.escape()for literal text containing(,.,|or$. An empty string matches everything, so pytest warns aboutmatch=""; use"^$"to require an empty message.check=(added in pytest 8.4) takes a function that receives the exception and returns a bool. It runs after the type andmatchchecks, which makes it the place for attribute checks such as an error code.expected_exceptionis optional whenmatch=orcheck=is given, but naming the type keeps the test readable.
import re
import pytest
class OrderError(Exception): pass
class OrderNotFound(OrderError, LookupError): def __init__(self, order_id: str): super().__init__(f"order {order_id} not found") self.order_id = order_id
def load_order(order_id: str): raise OrderNotFound(order_id)
def test_subclasses_match(): # Like `except`, a base class (or a tuple of types) matches subclasses. with pytest.raises(OrderError): load_order("ORD-404") with pytest.raises((KeyError, LookupError)): load_order("ORD-404")
def test_inspect_the_exception(): with pytest.raises(OrderNotFound) as excinfo: load_order("ORD-404") # Assertions go after the with block: code after the raising line never runs. assert excinfo.type is OrderNotFound assert excinfo.value.order_id == "ORD-404" assert excinfo.match(r"ORD-\d+")
def test_match_is_a_regex_search(): # match= uses re.search on str(exc); escape literal text that has metacharacters. with pytest.raises(ValueError, match=re.escape("price (EUR) must be > 0")): raise ValueError("price (EUR) must be > 0; got -5")
def test_match_includes_notes(): with pytest.raises(ValueError, match="row 42"): exc = ValueError("bad quantity") exc.add_note("while importing row 42") raise exc
def test_check_callable(): # check= (pytest 8.4+) runs after the type and match checks. with pytest.raises(OrderNotFound, check=lambda e: e.order_id.startswith("ORD-")): load_order("ORD-404")
def test_wrong_message_fails(): with pytest.raises(OrderNotFound, match="ORD-999"): load_order("ORD-404")test_semantics.py::test_subclasses_match PASSED [ 16%]test_semantics.py::test_inspect_the_exception PASSED [ 33%]test_semantics.py::test_match_is_a_regex_search PASSED [ 50%]test_semantics.py::test_match_includes_notes PASSED [ 66%]test_semantics.py::test_check_callable PASSED [ 83%]test_semantics.py::test_wrong_message_fails FAILED [100%]
=================================== FAILURES ===================================___________________________ test_wrong_message_fails ___________________________
def test_wrong_message_fails():> with pytest.raises(OrderNotFound, match="ORD-999"): ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^E AssertionError: Regex pattern did not match.E Expected regex: 'ORD-999'E Actual message: 'order ORD-404 not found'
test_semantics.py:57: AssertionError========================= 1 failed, 5 passed in 0.02s ==========================The last test fails on purpose to show the report: pytest prints the pattern and the actual message side by side.
Exception groups
Section titled “Exception groups”An ExceptionGroup (Python 3.11+) is not a subclass of the exceptions it contains, so pytest.raises(ValueError) does not match a group of ValueErrors. pytest.raises(ExceptionGroup) matches, but says nothing about the contents. pytest 8.4 added pytest.RaisesGroup, which describes the expected members, and pytest.RaisesExc, which adds match= and check= to a single member. RaisesGroup is strict: an unexpected extra member fails with Unexpected exception(s): [TypeError('b')]. The flatten_subgroups and allow_unwrapped flags relax nesting and unwrapped exceptions to behave more like except*.
Realistic example
Section titled “Realistic example”OrdersPortal imports order lines from a CSV upload. A bad row raises ImportRowError that names the row and chains the original error; a whole import reports every bad row at once in an ExceptionGroup. The tests pin each of those promises down.
from dataclasses import dataclassfrom decimal import Decimal, InvalidOperation
class ImportRowError(ValueError): def __init__(self, row: int, reason: str): super().__init__(f"row {row}: {reason}") self.row = row
@dataclass(frozen=True)class OrderLine: order_id: str quantity: int unit_price: Decimal
def parse_line(row: int, raw: dict[str, str]) -> OrderLine: try: price = Decimal(raw["unit_price"]) except InvalidOperation as exc: raise ImportRowError(row, f"unit_price {raw['unit_price']!r} is not a number") from exc quantity = int(raw["quantity"]) if quantity <= 0: raise ImportRowError(row, "quantity must be positive") return OrderLine(raw["order_id"], quantity, price)
def import_lines(rows: list[dict[str, str]]) -> list[OrderLine]: """Parse every row; report all bad rows together instead of stopping at the first.""" lines, errors = [], [] for number, raw in enumerate(rows, start=1): try: lines.append(parse_line(number, raw)) except ImportRowError as exc: errors.append(exc) if errors: raise ExceptionGroup(f"{len(errors)} of {len(rows)} rows rejected", errors) return linesfrom decimal import InvalidOperation
import pytest
from orders_import import ImportRowError, import_lines, parse_line
GOOD = {"order_id": "ORD-1", "quantity": "2", "unit_price": "9.50"}
def test_bad_price_is_reported_with_row_and_cause(): with pytest.raises(ImportRowError, match=r"^row 3: unit_price 'abc'") as excinfo: parse_line(3, {**GOOD, "unit_price": "abc"}) assert excinfo.value.row == 3 # The original decimal error is kept as the explicit cause (raise ... from exc). assert isinstance(excinfo.value.__cause__, InvalidOperation)
def test_all_bad_rows_are_reported_together(): rows = [GOOD, {**GOOD, "quantity": "0"}, {**GOOD, "unit_price": "n/a"}] with pytest.RaisesGroup( pytest.RaisesExc(ImportRowError, match="row 2: quantity must be positive"), pytest.RaisesExc(ImportRowError, check=lambda e: e.row == 3), match=r"^2 of 3 rows rejected$", ): import_lines(rows)
def test_non_numeric_quantity_is_not_wrapped(): # int("two") raises a plain ValueError, which is NOT an ImportRowError: # it escapes the per-row handler, so import_lines raises it directly. with pytest.raises(ValueError, match="invalid literal for int") as excinfo: import_lines([{**GOOD, "quantity": "two"}]) assert not isinstance(excinfo.value, ImportRowError)test_orders_import.py::test_bad_price_is_reported_with_row_and_cause PASSED [ 33%]test_orders_import.py::test_all_bad_rows_are_reported_together PASSED [ 66%]test_orders_import.py::test_non_numeric_quantity_is_not_wrapped PASSED [100%]
============================== 3 passed in 0.02s ===============================What each test teaches:
- The first anchors the message with
^and checks__cause__, so a refactor that dropsfrom exc(see raise … from) is caught. - The second describes the whole group: which members, what they say, and the group message. Extra or missing members fail the test.
- The third documents a real gap.
ImportRowErrorsubclassesValueError, sopytest.raises(ValueError)alone would also pass for a wrapped error; theisinstancecheck makes the test say which one it expects. The fix (wrappingint()failures too) can then be made test-first.
To run the same error assertion over many inputs, put pytest.raises(...) objects into a parametrize table; the pytest parametrize page shows that pattern with contextlib.nullcontext for rows that must not raise.
Common mistakes
Section titled “Common mistakes”- Assertions inside the
withblock after the raising call. They never run, so the test passes without checking anything. Dedent them. - Too much code inside the block. If setup inside the block raises the same type, the test passes for the wrong reason. Keep only the call under test inside.
pytest.raises(Exception). Matches nearly everything, including aTypeErrorfrom a typo. The pytest docs warn against it; name the specific type.- Literal messages with regex characters.
match="total (USD) exceeded"treats(USD)as a group and fails to match the literal text. Usere.escape(). - Expecting
match=to compare the whole message. It isre.search;match="row 1"also matches"row 12". Anchor or include a delimiter. - Catching a group with
pytest.raises(ValueError). AnExceptionGroupis not aValueError; usepytest.RaisesGroup. - Using the old callable form.
pytest.raises(ValueError, func, arg)still works but the docs call it not recommended; the context manager reads better and supportsmatch=.
When to use it and when not to
Section titled “When to use it and when not to”| Need | Tool |
|---|---|
| Code must raise a specific exception | pytest.raises(Type, match=...) |
| Code must raise an exception group with known members | pytest.RaisesGroup(...) with pytest.RaisesExc(...) |
| Code must emit a warning, not raise | pytest.warns(Warning, match=...) |
| A known bug currently raises and you want to track it | @pytest.mark.xfail(raises=Type, strict=True) |
| Code must not raise | Just call it; any exception already fails the test |
unittest.TestCase suites |
self.assertRaises / assertRaisesRegex |
Compatibility
Section titled “Compatibility”pytest.raises as a context manager, match= and ExceptionInfo are long-standing and current in pytest 9.2.0. check=, pytest.RaisesGroup and pytest.RaisesExc were added in pytest 8.4.0, along with the warning for match="". Matching against __notes__ relies on PEP 678 notes (Python 3.11+). ExceptionGroup requires Python 3.11; pytest 9 itself supports Python 3.10 and later.
Interview questions
Section titled “Interview questions”1. Why is pytest.raises safer than try/except in a test?
A bare try/except passes when nothing is raised unless you remember an else: fail branch. pytest.raises fails with DID NOT RAISE, lets unexpected exception types propagate with their traceback, and gives you message and attribute checks.
2. Does pytest.raises(ValueError, match="row 1") pass for the message "row 12: bad quantity"?
Yes. match uses re.search, so any substring match passes. Use match=r"^row 1:" or another delimiter to be exact.
3. Where do assertions about the exception belong, and why?
After the with block. The exception leaves the block at the raising line, so later lines inside the block never execute. excinfo.value is populated once the block exits.
4. Senior scenario: OrdersPortal’s checkout runs payment, stock and fraud checks concurrently with asyncio.TaskGroup, so failures arrive as an ExceptionGroup. A test uses pytest.raises(ExceptionGroup) and has never failed. What is wrong and how do you test this properly?
The test proves only that some group was raised; a group holding an unrelated TypeError would pass too. Use pytest.RaisesGroup with one pytest.RaisesExc per expected failure (with match= or check= for error codes), so unexpected or missing members fail the test. Decide deliberately whether nesting matters (flatten_subgroups) and whether a single unwrapped exception is acceptable (allow_unwrapped). Add one test per failure combination the business cares about rather than one catch-all.
Key takeaways
Section titled “Key takeaways”pytest.raisesfails when nothing is raised and lets unexpected types through, whichtry/excepttests often miss.match=is a regex search over the message and notes; anchor it andre.escape()literal text.- Put assertions after the
withblock, and keep only the call under test inside it. check=(pytest 8.4) handles attribute checks;RaisesGroupandRaisesExchandle exception groups.- Prefer specific exception types;
pytest.raises(Exception)hides bugs.
Related pages
Section titled “Related pages”- pytest parametrize: tables of valid and invalid input.
- pytest fixtures: shared setup for error tests.
- unittest.mock.patch: making a dependency raise with
side_effect. - raise … from: exception chaining and
__cause__. - Exceptions:
try,exceptand custom exception classes. - Error handling: designing error flows in applications.