0
0
PyTesttesting~15 mins

Testing custom exceptions in PyTest - Build an Automation Script

Choose your learning style9 modes available
Verify that the custom exception is raised with correct message
Preconditions (2)
Step 1: Call risky_function with a negative number as input
Step 2: Catch the exception raised
Step 3: Verify that the exception is of type CustomError
Step 4: Verify that the exception message is 'Negative value not allowed'
✅ Expected Result: The function raises CustomError with message 'Negative value not allowed' when called with negative input
Automation Requirements - pytest
Assertions Needed:
Assert that CustomError is raised
Assert that the exception message equals 'Negative value not allowed'
Best Practices:
Use pytest.raises context manager to catch exceptions
Check exception message using the 'match' parameter or by accessing exception info
Keep test functions small and focused
Name test functions clearly to indicate what is tested
Automated Solution
PyTest
import pytest

class CustomError(Exception):
    pass

def risky_function(value: int):
    if value < 0:
        raise CustomError('Negative value not allowed')
    return value

def test_risky_function_raises_custom_error():
    with pytest.raises(CustomError) as exc_info:
        risky_function(-1)
    assert str(exc_info.value) == 'Negative value not allowed'

The code defines a custom exception CustomError and a function risky_function that raises this exception when the input is negative.

The test function test_risky_function_raises_custom_error uses pytest.raises as a context manager to catch the exception. It then asserts that the exception message matches the expected string.

This approach is clear, concise, and follows pytest best practices for testing exceptions.

Common Mistakes - 3 Pitfalls
Not using pytest.raises and instead using try-except blocks manually
Not checking the exception message, only the exception type
Catching a too broad exception like Exception instead of the specific custom exception
Bonus Challenge

Now add data-driven testing with 3 different inputs: -5 (should raise), 0 (should not raise), 10 (should not raise)

Show Hint