0
0
PyTesttesting~15 mins

Testing multiple exceptions in PyTest - Build an Automation Script

Choose your learning style9 modes available
Verify function raises correct exceptions for invalid inputs
Preconditions (2)
Step 1: Call 'process_input' with input that should raise ValueError
Step 2: Verify that ValueError is raised
Step 3: Call 'process_input' with input that should raise TypeError
Step 4: Verify that TypeError is raised
Step 5: Call 'process_input' with input that should raise KeyError
Step 6: Verify that KeyError is raised
✅ Expected Result: The function raises the expected exceptions for each invalid input
Automation Requirements - pytest
Assertions Needed:
Assert that ValueError is raised for invalid value input
Assert that TypeError is raised for invalid type input
Assert that KeyError is raised for missing key input
Best Practices:
Use pytest.raises context manager for exception testing
Write separate test functions or parameterize tests for clarity
Keep test code simple and readable
Automated Solution
PyTest
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.

Common Mistakes - 3 Pitfalls
Not using pytest.raises and instead using try-except blocks manually
Catching too broad exceptions or multiple exceptions in one test without clarity
Not asserting the exception message
Bonus Challenge

Now add data-driven testing with 3 different invalid inputs to check all exceptions in one parameterized test

Show Hint