0
0
PyTesttesting~15 mins

Matching exception messages in PyTest - Build an Automation Script

Choose your learning style9 modes available
Verify that a function raises ValueError with correct message
Preconditions (2)
Step 1: Call the function divide with arguments 10 and 0
Step 2: Catch the exception raised
Step 3: Verify that the exception is of type ValueError
Step 4: Verify that the exception message contains the text 'division by zero is not allowed'
✅ Expected Result: The test should pass only if ValueError is raised and the message contains 'division by zero is not allowed'
Automation Requirements - pytest
Assertions Needed:
Assert that ValueError is raised
Assert that exception message contains 'division by zero is not allowed'
Best Practices:
Use pytest.raises context manager for exception testing
Use 'match' parameter in pytest.raises to check exception message
Keep test functions small and focused
Automated Solution
PyTest
import pytest

def divide(a, b):
    if b == 0:
        raise ValueError('division by zero is not allowed')
    return a / b

def test_divide_by_zero_raises_value_error():
    with pytest.raises(ValueError, match='division by zero is not allowed'):
        divide(10, 0)

The divide function raises a ValueError with a specific message when dividing by zero.

The test function test_divide_by_zero_raises_value_error uses pytest.raises as a context manager to check that calling divide(10, 0) raises a ValueError.

The match parameter in pytest.raises checks that the exception message contains the exact text 'division by zero is not allowed'. This ensures the error is not only the right type but also the right message.

This approach is clean, readable, and uses pytest best practices for exception testing.

Common Mistakes - 3 Pitfalls
Catching exception manually with try-except and asserting message inside except block
Not checking the exception message, only the exception type
Using assert inside the test to check exception message after catching exception
Bonus Challenge

Now add tests for a function that raises ValueError with different messages for zero and negative divisors

Show Hint