Test Overview
This test checks that a function raises a specific exception and that this exception is caused by another exception, verifying the exception chain.
This test checks that a function raises a specific exception and that this exception is caused by another exception, verifying the exception chain.
import pytest def func_that_raises(): try: raise ValueError("Initial error") except ValueError as e: raise RuntimeError("Secondary error") from e def test_exception_chain(): with pytest.raises(RuntimeError) as exc_info: func_that_raises() assert isinstance(exc_info.value.__cause__, ValueError) assert str(exc_info.value) == "Secondary error" assert str(exc_info.value.__cause__) == "Initial error"
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts | pytest test runner initialized | — | PASS |
| 2 | Calls func_that_raises() inside pytest.raises context | Function executes, raises ValueError internally | — | PASS |
| 3 | func_that_raises catches ValueError and raises RuntimeError from it | RuntimeError with cause set to ValueError is raised | — | PASS |
| 4 | pytest.raises captures RuntimeError exception | exc_info contains RuntimeError instance with __cause__ attribute | Check exception type is RuntimeError | PASS |
| 5 | Assert that exc_info.value.__cause__ is instance of ValueError | Exception cause is ValueError | assert isinstance(exc_info.value.__cause__, ValueError) | PASS |
| 6 | Assert that RuntimeError message is 'Secondary error' | RuntimeError message matches | assert str(exc_info.value) == 'Secondary error' | PASS |
| 7 | Assert that ValueError message is 'Initial error' | ValueError message matches | assert str(exc_info.value.__cause__) == 'Initial error' | PASS |
| 8 | Test ends successfully | All assertions passed | — | PASS |
raise NewException() from OriginalException() to chain exceptions.pytest.raises() context must match the exception actually raised, here TypeError.excinfo.value.__cause__ be?
def func():
try:
raise ValueError("original error")
except ValueError as e:
raise TypeError("new error") from e
def test_func():
with pytest.raises(TypeError) as excinfo:
func()def test_chain():
with pytest.raises(TypeError) as excinfo:
raise TypeError("error") from ValueError("cause")
assert isinstance(excinfo.value.__cause__, TypeError)RuntimeError caused by a KeyError. Which pytest test code correctly verifies both exceptions?Pass the test and this pattern moves unknown