What if you could catch all your code's error problems with just one neat test?
Why Testing multiple exceptions in PyTest? - Purpose & Use Cases
Imagine you have a function that can fail in several ways, like dividing by zero or accessing a missing file. You try to test each error by running the function and watching closely for crashes.
Manually checking each error means running the function many times, guessing which error might happen, and writing repeated code. It's slow, easy to miss errors, and hard to keep track of all possible failures.
Testing multiple exceptions with pytest lets you write simple, clear tests that check many error cases at once. You can tell pytest to expect different errors in one place, so your tests stay neat and catch all problems reliably.
try: func() except ZeroDivisionError: pass try: func() except FileNotFoundError: pass
import pytest @pytest.mark.parametrize('error', [ZeroDivisionError, FileNotFoundError]) def test_errors(error): with pytest.raises(error): func()
This approach makes testing many error cases fast, clear, and less error-prone, so you can trust your code works well in all bad situations.
When building a calculator app, you want to test that dividing by zero or entering invalid input both raise the right errors without writing separate tests for each.
Manual error testing is slow and repetitive.
pytest lets you test many exceptions in one simple test.
This saves time and improves test coverage.
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
