0
0
PyTesttesting~10 mins

Testing custom exceptions in PyTest - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test checks if a custom exception is raised correctly when a function receives invalid input. It verifies that the exception type and message are as expected.

Test Code - pytest
PyTest
import pytest

class CustomError(Exception):
    pass

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

def test_divide_raises_custom_error():
    with pytest.raises(CustomError) as exc_info:
        divide(10, 0)
    assert str(exc_info.value) == "Cannot divide by zero"
Execution Trace - 5 Steps
StepActionSystem StateAssertionResult
1Test startspytest test runner initialized-PASS
2Calls divide(10, 0)Function divide is executing with a=10, b=0-PASS
3Raises CustomError with message 'Cannot divide by zero'Exception raised inside divide functionpytest.raises context captures CustomErrorPASS
4Checks exception message equals 'Cannot divide by zero'Exception message available in exc_info.valueassert str(exc_info.value) == 'Cannot divide by zero'PASS
5Test endsTest passed successfully-PASS
Failure Scenario
Failing Condition: Function divide does not raise CustomError when dividing by zero
Execution Trace Quiz - 3 Questions
Test your understanding
What does the test verify about the divide function?
AIt raises ValueError when dividing by zero
BIt returns zero when dividing by zero
CIt raises CustomError when dividing by zero
DIt returns None when dividing by zero
Key Result
Always use pytest.raises context manager to verify that your code raises the expected custom exceptions with the correct message.