How do you unit test that a Python function raises an expected exception? | A1Lab@MZeeshanM to PythonEnglish • 2 days ago

How do you unit test that a Python function raises an expected exception?

message-square
0

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 with block:
    • If setup code and the target call both sit inside with pytest.raises(ValueError): and the setup code raises ValueError early, the test falsely passes without ever calling the function under test! Keep setup lines before with pytest.raises(...) and place only the exact statement expected to raise inside the context manager.
  • Always validate the exception message (match= / assertRaisesRegex) for generic built-in exceptions:
    • Broad exceptions like ValueError, TypeError, or KeyError can be raised for dozens of unintended reasons (e.g., typo in a dict key or bad unpacking). Passing match=r"expected pattern" ensures the exception came from your intended guard clause.
  • Never use pytest.raises(Exception) or pytest.raises(BaseException):
    • Catching bare Exception masks real bugs (AttributeError, NameError, ZeroDivisionError), and catching BaseException even swallows KeyboardInterrupt or pytest.fail(). Always assert the most specific exception subclass possible.
  • Inspecting custom exception attributes (exc_info.value vs. cm.exception):
    • After the with block exits cleanly (meaning the expected exception was raised), access the actual caught exception instance via exc_info.value in pytest or cm.exception in unittest—useful for asserting custom fields like assert exc_info.value.status_code == 404 or assert exc_info.value.__cause__ is not None.
  • Testing async def coroutines (await inside the with block):
    • Both with pytest.raises(MyError): await async_func() (with pytest-asyncio) and with self.assertRaises(MyError): await async_func() (inside unittest.IsolatedAsyncioTestCase) work identically—just make sure await is inside the with block, because calling an async function without await merely returns a coroutine object without executing its body.
  • Testing warnings (pytest.warns / assertWarns) vs. exceptions:
    • Warnings (DeprecationWarning, UserWarning) do not halt execution, so pytest.raises will fail on them—use with pytest.warns(UserWarning, match=r"..."): or with self.assertWarns(UserWarning): instead.

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