Hint: Exception stops code; lines after are not run [OK]
Common Mistakes:
Thinking both exceptions must be raised simultaneously
Thinking test fails due to syntax
Ignoring unreachable code after exception
5. You want to test a function that can raise either IndexError or KeyError depending on input. Which pytest test code correctly checks both exceptions in one test?
hard
A. def test_func():
with pytest.raises(IndexError, KeyError):
func_that_raises()
B. def test_func():
with pytest.raises([IndexError, KeyError]):
func_that_raises()
C. def test_func():
with pytest.raises((IndexError, KeyError)):
func_that_raises()
D. def test_func():
with pytest.raises({IndexError, KeyError}):
func_that_raises()
Solution
Step 1: Recall correct syntax for multiple exceptions
pytest.raises expects a tuple of exceptions to check multiple exceptions in one block.
Step 2: Identify correct tuple usage
def test_func():
with pytest.raises((IndexError, KeyError)):
func_that_raises() uses a tuple (parentheses with comma-separated exceptions), which is correct syntax.
Step 3: Check other options
Options A, B, and D use invalid syntax: multiple arguments without tuple, list, or set instead of tuple.
Final Answer:
def test_func():
with pytest.raises((IndexError, KeyError)):
func_that_raises() -> Option C
Quick Check:
Tuple of exceptions in pytest.raises = correct [OK]
Hint: Use tuple (parentheses, commas) for multiple exceptions in pytest.raises [OK]
Common Mistakes:
Passing exceptions as separate arguments
Using list or set instead of tuple
Forgetting parentheses around exceptions
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.