Wrap the function call inside with pytest.raises(ExpectedException, match=r"...") as exc_info: when using pytest (recommended) or with self.assertRaisesRegex(ExpectedException, r"...") as cm: (or self.assertRaises(ExpectedException)) when using Python’s built-in unittest—passing match= (or assertRaisesRegex) so the test verifies both the exact exception class and its error message rather than passing accidentally on an unrelated ValueError or TypeError.
Basic Example
import pytest
import unittest
def withdraw(balance: float, amount: float) -> float:
if amount <= 0:
raise ValueError("Withdrawal amount must be positive")
if amount > balance:
raise RuntimeError(f"Insufficient funds: requested {amount}, available {balance}")
return balance - amount
# 1. Recommended (`pytest.raises` with `match=` regex verification):
def test_withdraw_insufficient_funds():
with pytest.raises(RuntimeError, match=r"Insufficient funds: requested 200") as exc_info:
withdraw(100.0, 200.0)
# Optional: Inspect custom attributes or exact message on `exc_info.value`
assert "available 100.0" in str(exc_info.value)
# 2. Standard-library `unittest` (`assertRaisesRegex` / `assertRaises`):
class TestWithdraw(unittest.TestCase):
def test_negative_amount(self):
with self.assertRaisesRegex(ValueError, r"must be positive"):
withdraw(100.0, -5.0)
Key Details & Edge Cases
- Put ONLY the single failing statement inside the
withblock:- If setup code and the target call both sit inside
with pytest.raises(ValueError):and the setup code raisesValueErrorearly, the test falsely passes without ever calling the function under test! Keep setup lines beforewith pytest.raises(...)and place only the exact statement expected to raise inside the context manager.
- If setup code and the target call both sit inside
- Always validate the exception message (
match=/assertRaisesRegex) for generic built-in exceptions:- Broad exceptions like
ValueError,TypeError, orKeyErrorcan be raised for dozens of unintended reasons (e.g., typo in a dict key or bad unpacking). Passingmatch=r"expected pattern"ensures the exception came from your intended guard clause.
- Broad exceptions like
- Never use
pytest.raises(Exception)orpytest.raises(BaseException):- Catching bare
Exceptionmasks real bugs (AttributeError,NameError,ZeroDivisionError), and catchingBaseExceptioneven swallowsKeyboardInterruptorpytest.fail(). Always assert the most specific exception subclass possible.
- Catching bare
- Inspecting custom exception attributes (
exc_info.valuevs.cm.exception):- After the
withblock exits cleanly (meaning the expected exception was raised), access the actual caught exception instance viaexc_info.valueinpytestorcm.exceptioninunittest—useful for asserting custom fields likeassert exc_info.value.status_code == 404orassert exc_info.value.__cause__ is not None.
- After the
- Testing
async defcoroutines (awaitinside thewithblock):- Both
with pytest.raises(MyError): await async_func()(withpytest-asyncio) andwith self.assertRaises(MyError): await async_func()(insideunittest.IsolatedAsyncioTestCase) work identically—just make sureawaitis inside thewithblock, because calling anasyncfunction withoutawaitmerely returns a coroutine object without executing its body.
- Both
- Testing warnings (
pytest.warns/assertWarns) vs. exceptions:- Warnings (
DeprecationWarning,UserWarning) do not halt execution, sopytest.raiseswill fail on them—usewith pytest.warns(UserWarning, match=r"..."):orwith self.assertWarns(UserWarning):instead.
- Warnings (
Comparison of Exception-Testing Mechanisms in Python
| Method | Framework | Validates Error Message Regex? | Exposes Caught Exception Instance? | Best Used When |
|---|---|---|---|---|
with pytest.raises(Exc, match=r"...") as exc_info: (Recommended) |
pytest |
Yes (match= parameter) |
Yes (exc_info.value) |
Modern Python test suites using pytest (clearest syntax and rich failure diffs). |
with self.assertRaisesRegex(Exc, r"...") as cm: |
unittest (standard library) |
Yes (2nd positional/keyword arg) | Yes (cm.exception) |
Zero-dependency projects using Python’s built-in unittest module. |
with self.assertRaises(Exc) as cm: |
unittest (standard library) |
No (checks exception type only) | Yes (cm.exception) |
Custom domain-specific exception subclasses (InsufficientFundsError) where type alone is unambiguous. |
Manual try: ... except Exc: ... else: pytest.fail(...) |
Any | Manual (assert "..." in str(e)) |
Yes (except Exc as e:) |
Complex multi-assertion exception checks where a with block is awkward (avoid when pytest.raises suffices). |
You must log in or register to comment.
