Recall & Review
beginner
What is an exception chain in Python testing?
An exception chain happens when one exception causes another. It shows the sequence of errors leading to the final failure. Testing exception chains helps check if the right errors happen in the right order.
Click to reveal answer
intermediate
How do you test exception chains using pytest?
Use pytest.raises() with the 'match' parameter to check the final exception message. To check the chain, access the '__cause__' or '__context__' attributes of the caught exception inside the 'as excinfo' block.
Click to reveal answer
intermediate
What is the difference between __cause__ and __context__ in exception chaining?
__cause__ is set when an exception is raised directly from another using 'raise ... from ...'. __context__ is set automatically when an exception occurs during handling another exception without 'from'.
Click to reveal answer
intermediate
Write a simple pytest test snippet to check an exception chain where ValueError causes a RuntimeError.
def test_exception_chain():
import pytest
with pytest.raises(RuntimeError) as excinfo:
try:
raise ValueError("bad value")
except ValueError as e:
raise RuntimeError("runtime failed") from e
assert isinstance(excinfo.value.__cause__, ValueError)
assert str(excinfo.value.__cause__) == "bad value"Click to reveal answer
beginner
Why is testing exception chains important in software testing?
It ensures that errors are handled properly and the root cause is not lost. This helps developers understand what really went wrong and fix bugs faster.
Click to reveal answer
In pytest, which attribute holds the original exception when using 'raise ... from ...'?
✗ Incorrect
The __cause__ attribute stores the original exception when an exception is raised from another using 'raise ... from ...'.
What does pytest.raises() do in a test?
✗ Incorrect
pytest.raises() verifies that the code inside its block raises the expected exception.
If an exception occurs during handling another exception without 'from', which attribute links them?
✗ Incorrect
__context__ links exceptions when one happens during handling another without explicit chaining.
Which pytest feature helps check the message text of an exception?
✗ Incorrect
The 'match' parameter in pytest.raises() lets you check if the exception message matches a pattern.
Why should you test exception chains instead of just the final exception?
✗ Incorrect
Testing chains helps confirm the root cause and the sequence of errors, improving debugging.
Explain how to test an exception chain in pytest with an example.
Think about how to access the original exception inside the pytest.raises block.
You got /4 concepts.
Describe the difference between __cause__ and __context__ in Python exception chaining.
One is set explicitly, the other automatically.
You got /3 concepts.