Framework Mode - Testing exception chains
Folder Structure
tests/ ├── test_exception_chains.py utilities/ ├── exception_helpers.py conftest.py pytest.ini
tests/ ├── test_exception_chains.py utilities/ ├── exception_helpers.py conftest.py pytest.ini
test_exception_chains.py where exception chain tests are written using pytest.raises() and __cause__ or __context__ checks.exception_helpers.py to create custom chained exceptions or extract messages.pytest.ini and conftest.py for test setup, fixtures, and environment configuration.pytest-html for readable HTML reports showing exception details.pytest.raises() context manager to catch exceptions and assert on the exception chain explicitly.__cause__ and __context__ attributes to verify the chain of exceptions is correct.Where would you add a new helper function to create a custom chained exception for reuse in multiple tests?
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