Verify function raises correct exceptions for invalid inputs
Preconditions (2)
✅ Expected Result: The function raises the expected exceptions for each invalid input
import pytest # Example function to test def process_input(data): if not isinstance(data, dict): raise TypeError("Input must be a dictionary") if 'key' not in data: raise KeyError("Missing 'key' in input") value = data['key'] if value < 0: raise ValueError("Value must be non-negative") return value * 2 def test_process_input_raises_value_error(): with pytest.raises(ValueError) as exc_info: process_input({'key': -1}) assert str(exc_info.value) == "Value must be non-negative" def test_process_input_raises_type_error(): with pytest.raises(TypeError) as exc_info: process_input(['not', 'a', 'dict']) assert str(exc_info.value) == "Input must be a dictionary" def test_process_input_raises_key_error(): with pytest.raises(KeyError) as exc_info: process_input({'wrong_key': 10}) assert str(exc_info.value) == "'Missing \'key\' in input'" or str(exc_info.value) == "'key'"
The code defines a sample function process_input that raises different exceptions based on input.
Each test function uses pytest.raises as a context manager to check for the expected exception.
Assertions check the exception message to ensure the correct error was raised.
This approach keeps tests clear and focused on one exception each, following best practices.
Now add data-driven testing with 3 different invalid inputs to check all exceptions in one parameterized test
pytest.raises((ValueError, TypeError)) do in a test?def test_func():
with pytest.raises((KeyError, IndexError)):
d = {'a': 1}
value = d['b']
def test_divide():
with pytest.raises((ZeroDivisionError, ValueError)):
result = 10 / 0
int('abc')
IndexError or KeyError depending on input. Which pytest test code correctly checks both exceptions in one test?Pass the test and this pattern moves unknown