0
0
PyTesttesting~10 mins

Testing exception chains in PyTest - Test Execution Trace

Choose your learning style9 modes available
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.

Test Code - pytest
PyTest
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"
Execution Trace - 8 Steps
StepActionSystem StateAssertionResult
1Test startspytest test runner initialized-PASS
2Calls func_that_raises() inside pytest.raises contextFunction executes, raises ValueError internally-PASS
3func_that_raises catches ValueError and raises RuntimeError from itRuntimeError with cause set to ValueError is raised-PASS
4pytest.raises captures RuntimeError exceptionexc_info contains RuntimeError instance with __cause__ attributeCheck exception type is RuntimeErrorPASS
5Assert that exc_info.value.__cause__ is instance of ValueErrorException cause is ValueErrorassert isinstance(exc_info.value.__cause__, ValueError)PASS
6Assert that RuntimeError message is 'Secondary error'RuntimeError message matchesassert str(exc_info.value) == 'Secondary error'PASS
7Assert that ValueError message is 'Initial error'ValueError message matchesassert str(exc_info.value.__cause__) == 'Initial error'PASS
8Test ends successfullyAll assertions passed-PASS
Failure Scenario
Failing Condition: func_that_raises does not raise RuntimeError or the cause is not ValueError
Execution Trace Quiz - 3 Questions
Test your understanding
What exception does the test expect func_that_raises() to raise?
ARuntimeError
BValueError
CTypeError
DKeyError
Key Result
Always verify exception chains by checking both the raised exception and its cause to ensure error context is preserved.