Verify application handles error paths correctly
Preconditions (2)
✅ Expected Result: Function returns correct result for valid input and raises expected exceptions for invalid inputs
import pytest def process_data(data): if not isinstance(data, str): raise TypeError("Input must be a string") if data == "": raise ValueError("Input cannot be empty") return data.upper() def test_process_data_valid(): result = process_data("hello") assert result == "HELLO" def test_process_data_empty_string(): with pytest.raises(ValueError) as exc_info: process_data("") assert str(exc_info.value) == "Input cannot be empty" def test_process_data_wrong_type(): with pytest.raises(TypeError) as exc_info: process_data(123) assert str(exc_info.value) == "Input must be a string"
This test script defines a simple function process_data that converts a string to uppercase.
It raises a TypeError if the input is not a string, and a ValueError if the input is an empty string.
The tests cover the normal path with valid input, and two error paths: empty string and wrong type.
Using pytest.raises ensures we check that the function raises the correct exceptions, which helps confirm the application handles error cases robustly.
Each test is small and focused, making it clear what behavior is tested.
Now add data-driven testing with 3 different invalid inputs to verify error handling
def test_divide():
with pytest.raises(ZeroDivisionError):
result = 10 / 0
def test_value_error():
with pytest.raises(ValueError):
int('abc')
process_data() raises a KeyError when a required key is missing in input. Which pytest test best ensures robustness by checking this error path?Pass the test and this pattern moves unknown