0
0
PyTesttesting~10 mins

Matching exception messages in PyTest - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test checks that a function raises a ValueError with the exact expected message when given invalid input.

Test Code - pytest
PyTest
import pytest

def divide(a, b):
    if b == 0:
        raise ValueError("Cannot divide by zero")
    return a / b

def test_divide_by_zero_message():
    with pytest.raises(ValueError, match="Cannot divide by zero") as exc_info:
        divide(10, 0)
    assert str(exc_info.value) == "Cannot divide by zero"
Execution Trace - 6 Steps
StepActionSystem StateAssertionResult
1Test startspytest test runner initialized-PASS
2Calls divide(10, 0)Function divide is executing with a=10, b=0-PASS
3Function raises ValueError with message 'Cannot divide by zero'Exception raised inside divide functionpytest checks exception type is ValueErrorPASS
4pytest matches exception message with 'Cannot divide by zero'Exception message available for matchingException message matches exactlyPASS
5Assertion checks exception message string equals 'Cannot divide by zero'Exception info captured in exc_infoassert str(exc_info.value) == 'Cannot divide by zero'PASS
6Test ends successfullyAll assertions passed-PASS
Failure Scenario
Failing Condition: The divide function raises ValueError with a different message or no exception
Execution Trace Quiz - 3 Questions
Test your understanding
What does the 'match' parameter in pytest.raises do?
AIt ignores the exception message
BIt checks that the exception message contains the given string
CIt changes the exception message
DIt catches any exception type
Key Result
Always verify both the exception type and the exact message to ensure your code fails as expected with clear error information.