Pytest raises: Testing Exceptions, match and excinfo
pytest raises lets a test assert that code fails in exactly the way it should. Learn the context manager, matching messages with regular expressions, inspecting the exception with excinfo, custom exceptions and chained causes, parametrized error cases, pytest.warns, and the three mistakes that make exception tests lie, with every test run.
with pytest.raises(ValueError):passes only if the block raises that exception type or a subclass.match=takes a regular expression searched in the message; usere.escapefor literal text with brackets or dots.as excgives you the exception object to check custom attributes and causes.- Code after the line that raises never runs, so keep only the failing call inside the block.
Good code fails loudly and predictably: withdrawing more than the balance should raise an error, not quietly produce a negative number. Those failure paths deserve tests as much as the happy path, and pytest raises is the tool pytest provides for them. It is simple, but a couple of details decide whether your exception tests protect you or silently pass.
All tests ran with Python 3.13.6 and pytest 9.2.0. The main suite produced 11 passed, and a second file of deliberate mistakes produced the failures shown below. New to pytest? Start with our pytest tutorial.
Why test exceptions?
- They prove that invalid input is rejected instead of corrupting data.
- They pin down the error type and message that callers and API clients depend on.
- They stop regressions where a refactor accidentally removes a validation check.
The code under test
# bank.py
class InsufficientFunds(ValueError):
def __init__(self, balance, amount):
super().__init__(f"balance {balance} is less than {amount}")
self.balance, self.amount = balance, amount
def withdraw(balance, amount):
if amount <= 0:
raise ValueError("amount must be positive")
if amount > balance:
raise InsufficientFunds(balance, amount)
return balance - amount
def parse_qty(s):
try:
return int(s)
except ValueError as e:
raise TypeError(f"qty must be a whole number, got {s!r}") from e
A custom exception that subclasses ValueError, carries useful attributes and chains from a lower-level error: typical of real code. Our exception handling guide covers how to design exceptions like this.
Basic usage: the context manager
import pytest
from bank import withdraw
def test_raises_type():
with pytest.raises(ValueError):
withdraw(100, -5)
The test passes because withdraw raised ValueError inside the with block. If no exception is raised, or a different type escapes, the test fails. The context manager form is the one to use; an older form, pytest.raises(ValueError, func, *args), still exists but is harder to read.
Matching the error message
def test_match_message():
with pytest.raises(ValueError, match="must be positive"):
withdraw(100, 0)
Checking the type alone can pass for the wrong reason: many things raise ValueError. Adding match ties the test to the specific failure. The pattern is searched within the message, like re.search, so a distinctive fragment is enough; you do not need the whole sentence.
match is a regular expression
def test_match_is_regex():
with pytest.raises(InsufficientFunds, match=r"balance \d+ is less than 150"):
withdraw(100, 150)
Because match is a regex, you can match variable parts like \d+. Use raw strings (r"...") so backslashes reach the regex engine untouched. The flip side: characters like (, ., [ and $ have special meaning, which causes one of the mistakes shown below. Our Python regex guide explains the syntax.
Inspecting the exception with excinfo
def test_excinfo_attributes():
with pytest.raises(InsufficientFunds) as exc:
withdraw(100, 150)
assert exc.value.amount == 150
assert exc.type is InsufficientFunds
assert "less than" in str(exc.value)
as exc gives you an ExceptionInfo object. exc.value is the exception instance, exc.type its class, and exc.traceback the traceback. Put the extra assertions after the with block; inside it, nothing after the raising call would run.
Subclasses count as a match
def test_subclass_is_accepted():
with pytest.raises(ValueError):
withdraw(100, 150) # raises InsufficientFunds, a ValueError subclass
Like an except clause, pytest.raises(ValueError) also accepts subclasses. That is convenient but can hide a change in behaviour. If the exact type matters, assert it with exc.type is InsufficientFunds. Never write pytest.raises(Exception): almost anything, including a typo that causes NameError, would pass.
Testing chained exceptions
def test_chained_cause():
with pytest.raises(TypeError, match="whole number") as exc:
parse_qty("two")
assert isinstance(exc.value.__cause__, ValueError)
When code uses raise ... from e, the original error is stored in __cause__. Testing it confirms that debugging context is preserved, which matters when logs are your only clue in production.
Many error cases with parametrize
@pytest.mark.parametrize("amount,msg", [(0, "positive"), (-1, "positive"), (500, "less than")])
def test_many(amount, msg):
with pytest.raises(ValueError, match=msg):
withdraw(100, amount)
Combining raises with parametrize gives one readable table of invalid inputs and expected messages, and each row is reported as its own test. Boundary values like 0 and -1 belong here.
Accepting one of several types
def test_tuple_of_types():
with pytest.raises((TypeError, KeyError)):
{}["missing"]
Pass a tuple when more than one type is acceptable, for example when a function may raise KeyError or TypeError depending on input. Use it sparingly; a precise type usually makes a better contract.
Testing warnings with pytest.warns
import warnings
def test_warns():
with pytest.warns(DeprecationWarning, match="old"):
warnings.warn("old api", DeprecationWarning)
Warnings are not exceptions, so pytest.raises does not catch them. pytest.warns works the same way, including match. For messages written with the logging module, use the caplog fixture instead.
Three mistakes our tests caught
We wrote a second test file containing common mistakes. The result: 3 failed, 2 passed.
1. Nothing was raised.
with pytest.raises(ValueError):
withdraw(100, 50) # valid withdrawal, no exception
# Failed: DID NOT RAISE ValueError
This is the main safety feature: if a validation check is deleted, the test fails.
2. Wrong message.
with pytest.raises(ValueError, match="insufficient"):
withdraw(100, 0)
# AssertionError: Regex pattern did not match.
# Expected regex: 'insufficient'
# Actual message: 'amount must be positive'
The right exception type but the wrong reason. Without match, this test would have passed and hidden the bug.
3. Special characters in the message.
with pytest.raises(ValueError, match="balance 100 is less than 150 (USD)"):
raise ValueError("balance 100 is less than 150 (USD)")
# AssertionError: Regex pattern did not match.
# Did you mean to `re.escape()` the regex?
with pytest.raises(ValueError, match=re.escape("less than 150 (USD)")): # passes
raise ValueError("balance 100 is less than 150 (USD)")
The message and pattern look identical, but (USD) is a regex group that matches USD without brackets. pytest even suggests the fix: wrap literal text in re.escape().
One more: code after the raising line inside the block never runs. Our test with assert False after withdraw(100, 0) passed, because execution jumped straight out of the block. Put follow-up assertions after the with.
Tip: keep exactly one statement inside a pytest.raises block, the call you expect to fail. Setup goes before it; assertions go after it.
Alternatives: try/except and unittest
A manual try/except with assert False in the try works but is longer and easy to get wrong. In unittest-style tests, self.assertRaises and self.assertRaisesRegex do the same job; pytest runs those tests too. See our Python unittest guide. For faking the dependency that should fail, combine raises with monkeypatch to make a function raise on demand.
Tips for reliable exception tests
- Always add
matchfor built-in exception types. - Use custom exception classes in your code; they make tests precise without long messages.
- Use
re.escapefor literal messages. - Test boundaries: 0, negative numbers, empty strings,
None. - Assert attributes and causes through
exc.value.
Exception testing checklist
Use this list when reviewing a test file that covers error paths:
- Every public function has at least one test for invalid input, not only the happy path.
- Each
pytest.raisesnames the most specific exception type available. - Built-in exception types are paired with a
matchpattern that identifies the real reason. - Literal messages containing brackets, dots or question marks use
re.escape. - Only the failing call sits inside the
withblock; assertions onexc.valuecome after it. - Boundary values are covered: zero, negative numbers, empty strings, missing keys and
None. - Chained causes are checked where debugging context matters.
- Warnings are tested with
pytest.warnsand logs withcaplog, not withraises.
A suite that ticks these boxes fails for the right reasons and tells you exactly which validation broke.
Final thoughts
pytest raises turns “this should fail” into an executable promise. Use the context manager with the most specific exception type, add a match regex for the message, inspect exc.value for details, and keep only the failing call inside the block. Our deliberate mistakes showed how each rule protects you: a missing exception, a wrong message and an unescaped bracket were all caught. Pair it with fixtures to set up the state that triggers each error.
Frequently asked questions
How do I test that a function raises an exception in pytest?
Wrap the call in with pytest.raises(ExpectedError): and call the function inside the block. The test passes only if that exception type, or a subclass, is raised.
How do I check the exception message in pytest?
Pass match with a regular expression, for example the pattern must be positive. pytest searches the exception message for the pattern and fails if it is not found.
Why does my match fail even though the message looks the same?
match is a regular expression, so characters like brackets and dots have special meaning. Wrap literal text in re.escape to match it exactly.
How do I access the exception object in pytest?
Use with pytest.raises(MyError) as exc: and then read exc.value after the block. exc.type gives the class and exc.value gives the instance with its attributes.
Does pytest.raises catch subclasses?
Yes. Like an except clause it matches the given type and any subclass. Check exc.type after the block if the exact class matters.
Keep learning
Need help with testing, WordPress or SEO?
We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.