We test multiple exceptions to make sure our code handles different errors correctly. This helps catch bugs and improves program reliability.
Testing multiple exceptions in PyTest
import pytest with pytest.raises((ExceptionType1, ExceptionType2)): # code that should raise one of the exceptions
You list exceptions inside a tuple to check for multiple possible errors.
The test passes if any one of the exceptions is raised.
ZeroDivisionError, which is in the tuple.import pytest def test_divide(): with pytest.raises((ZeroDivisionError, TypeError)): result = 10 / 0 # raises ZeroDivisionError
TypeError, which is in the tuple.import pytest def test_add(): with pytest.raises((ZeroDivisionError, TypeError)): result = 'a' + 1 # raises TypeError
This test checks that risky_operation raises either ZeroDivisionError or TypeError for bad inputs. It also confirms normal input works.
import pytest def risky_operation(value): if value == 0: raise ZeroDivisionError("Cannot divide by zero") elif not isinstance(value, int): raise TypeError("Value must be an integer") return 10 / value def test_risky_operation(): with pytest.raises((ZeroDivisionError, TypeError)): risky_operation(0) # should raise ZeroDivisionError with pytest.raises((ZeroDivisionError, TypeError)): risky_operation('a') # should raise TypeError # This call should NOT raise an exception assert risky_operation(2) == 5.0
Always use a tuple to list multiple exceptions inside pytest.raises().
If the code does not raise any of the listed exceptions, the test fails.
Use this to keep tests simple when multiple errors are acceptable.
Use pytest.raises() with a tuple to test multiple exceptions.
The test passes if any one of the exceptions is raised.
This helps verify your code handles different error cases properly.
Practice
pytest.raises((ValueError, TypeError)) do in a test?Solution
Step 1: Understand pytest.raises with tuple
Using a tuple inside pytest.raises means the test expects any one of those exceptions.Step 2: Effect on test pass/fail
If the code raises either ValueError or TypeError, the test passes. If no exception or a different exception is raised, it fails.Final Answer:
It passes if either ValueError or TypeError is raised during the test. -> Option AQuick Check:
pytest.raises with tuple = any exception in tuple passes [OK]
- Thinking both exceptions must be raised simultaneously
- Assuming it passes without exceptions
- Confusing tuple with multiple separate pytest.raises calls
Solution
Step 1: Recall pytest.raises syntax
pytest.raises expects a single exception or a tuple of exceptions inside parentheses.Step 2: Identify correct tuple syntax
Only with pytest.raises((ValueError, TypeError)): uses a tuple (parentheses with comma-separated exceptions) correctly.Final Answer:
with pytest.raises((ValueError, TypeError)): -> Option DQuick Check:
Tuple syntax with parentheses and comma = correct [OK]
- Using multiple arguments without tuple
- Using list brackets instead of tuple
- Using curly braces which are invalid syntax
def test_func():
with pytest.raises((KeyError, IndexError)):
d = {'a': 1}
value = d['b']
Solution
Step 1: Identify exception raised by d['b']
Accessing a missing key in a dictionary raises KeyError.Step 2: Check if KeyError is in the tuple
KeyError is in (KeyError, IndexError), so pytest.raises expects it and test passes.Final Answer:
Test passes because KeyError is raised. -> Option BQuick Check:
Missing dict key = KeyError, in tuple = pass [OK]
- Thinking IndexError is raised instead
- Assuming no exception is raised
- Confusing KeyError with ValueError
def test_divide():
with pytest.raises((ZeroDivisionError, ValueError)):
result = 10 / 0
int('abc')
Solution
Step 1: Analyze exception flow in with block
ZeroDivisionError occurs at 10 / 0, so the next line int('abc') is never executed.Step 2: Understand pytest.raises behavior
ZeroDivisionError is in the expected tuple, so test passes. ValueError is unreachable.Step 3: Confirm test outcome
Since a matching exception (ZeroDivisionError) is raised first, the test passes.Final Answer:
The test will pass because ZeroDivisionError is raised first. -> Option AQuick Check:
Exception stops code, later lines unreachable; matching exc = pass [OK]
- Thinking both exceptions must be raised simultaneously
- Thinking test fails due to syntax
- Ignoring unreachable code after exception
IndexError or KeyError depending on input. Which pytest test code correctly checks both exceptions in one test?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 CQuick Check:
Tuple of exceptions in pytest.raises = correct [OK]
- Passing exceptions as separate arguments
- Using list or set instead of tuple
- Forgetting parentheses around exceptions
Ready to prove it?
Pass the test and this pattern moves unknown
