Skip to content

pytest.raises: Assert Exceptions in Python Tests

  • Why hand-written try/except tests pass by accident, and how pytest.raises prevents it.
  • What pytest.raises matches (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 through ExceptionInfo, and add a predicate with check=.
  • How to assert on exception groups with pytest.RaisesGroup and pytest.RaisesExc (pytest 8.4).
  • How to test chained exceptions and keep error tests specific.

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).

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.

refunds.py
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 - amount
test_refunds.py
from 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.

pytest.raises behaves like an except clause wrapped around the block:

  • Type matching follows except rules: 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 with never run; put assertions on the exception after the block.
  • as excinfo binds a pytest.ExceptionInfo. Its .type, .value (the exception object) and .traceback are filled in when the block exits, and .match(pattern) runs the same regex check as match=.

The message checks:

  • match= takes a string or compiled pattern and runs re.search against str(exception) and its PEP 678 __notes__. It is a search, not equality: anchor with ^...$ when you need the whole message, and use re.escape() for literal text containing (, ., | or $. An empty string matches everything, so pytest warns about match=""; 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 and match checks, which makes it the place for attribute checks such as an error code.
  • expected_exception is optional when match= or check= is given, but naming the type keeps the test readable.
test_semantics.py
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.

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*.

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.

orders_import.py
from dataclasses import dataclass
from 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 lines
test_orders_import.py
from 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 drops from 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. ImportRowError subclasses ValueError, so pytest.raises(ValueError) alone would also pass for a wrapped error; the isinstance check makes the test say which one it expects. The fix (wrapping int() 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.

  • Assertions inside the with block 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 a TypeError from 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. Use re.escape().
  • Expecting match= to compare the whole message. It is re.search; match="row 1" also matches "row 12". Anchor or include a delimiter.
  • Catching a group with pytest.raises(ValueError). An ExceptionGroup is not a ValueError; use pytest.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 supports match=.
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

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.

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.

  • pytest.raises fails when nothing is raised and lets unexpected types through, which try/except tests often miss.
  • match= is a regex search over the message and notes; anchor it and re.escape() literal text.
  • Put assertions after the with block, and keep only the call under test inside it.
  • check= (pytest 8.4) handles attribute checks; RaisesGroup and RaisesExc handle exception groups.
  • Prefer specific exception types; pytest.raises(Exception) hides bugs.