0
0
PyTesttesting~7 mins

Testing exception chains in PyTest

Choose your learning style9 modes available
Introduction

Sometimes one error causes another error. Testing exception chains helps check that the right errors happen in the right order.

When a function catches one error and raises a new error based on it.
When you want to make sure the original error is not lost after a new error is raised.
When debugging complex code that handles multiple errors.
When you want to confirm the full error history is available for logging or user messages.
Syntax
PyTest
with pytest.raises(ExpectedError) as exc_info:
    function_that_raises()

assert isinstance(exc_info.value.__cause__, OriginalError)

Use pytest.raises to catch the expected error.

Check exc_info.value.__cause__ to see the original error that caused it.

Examples
This example raises a ValueError caused by a KeyError. The test checks the cause.
PyTest
with pytest.raises(ValueError) as exc_info:
    raise ValueError('New error') from KeyError('Original error')

assert isinstance(exc_info.value.__cause__, KeyError)
This example converts a string to int, catches ValueError, then raises RuntimeError with the original error as cause.
PyTest
with pytest.raises(RuntimeError) as exc_info:
    try:
        int('abc')
    except ValueError as e:
        raise RuntimeError('Failed conversion') from e

assert isinstance(exc_info.value.__cause__, ValueError)
Sample Program

This test calls func() which raises a RuntimeError caused by a ValueError. The test confirms the cause is correct.

PyTest
import pytest

def func():
    try:
        int('not a number')
    except ValueError as e:
        raise RuntimeError('Conversion failed') from e

def test_func_exception_chain():
    with pytest.raises(RuntimeError) as exc_info:
        func()
    assert isinstance(exc_info.value.__cause__, ValueError)

if __name__ == '__main__':
    pytest.main([__file__])
OutputSuccess
Important Notes

Always check __cause__ to verify the original exception in a chain.

Exception chaining helps keep error context clear for debugging.

Summary

Testing exception chains ensures the right error causes are preserved.

Use pytest.raises and check exc_info.value.__cause__.

This helps find where errors really start in your code.