0
0
PyTesttesting~10 mins

Checking exception attributes in PyTest - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test checks that a function raises a ValueError with the correct 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():
    with pytest.raises(ValueError) as exc_info:
        divide(10, 0)
    assert exc_info.value.args[0] == "Cannot divide by zero"
Execution Trace - 6 Steps
StepActionSystem StateAssertionResult
1Test startsTest runner is ready to execute test_divide_by_zero-PASS
2Calls divide(10, 0)Function divide is executing with a=10, b=0-PASS
3Raises ValueError with message 'Cannot divide by zero'Exception is raised inside divide function-PASS
4pytest.raises context captures the ValueError as exc_infoException info stored in exc_info variable-PASS
5Assert exc_info.value.args[0] equals 'Cannot divide by zero'Checking exception message contentException message is exactly 'Cannot divide by zero'PASS
6Test ends successfullyTest passed with no errors-PASS
Failure Scenario
Failing Condition: The divide function does not raise ValueError or raises with wrong message
Execution Trace Quiz - 3 Questions
Test your understanding
What does the test check about the exception?
AThe exception type and its message content
BOnly that an exception is raised, no message check
CThat no exception is raised
DThe exception stack trace
Key Result
Always check both the type and the message of exceptions to ensure your code fails as expected with clear error information.