0
0
PyTesttesting~10 mins

Asserting exceptions (pytest.raises) - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test checks that a function raises a ValueError when given invalid input. It verifies that the exception is correctly thrown and caught using pytest.raises.

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 str(exc_info.value) == "Cannot divide by zero"
Execution Trace - 6 Steps
StepActionSystem StateAssertionResult
1Test startspytest test runner is ready to execute test_divide_by_zero-PASS
2Calls divide(10, 0)Function divide is executing with a=10, b=0-PASS
3Function detects b=0 and raises ValueError("Cannot divide by zero")Exception ValueError is raised inside divide function-PASS
4pytest.raises context catches the ValueError exceptionException is caught and stored in exc_infoCheck that exception type is ValueErrorPASS
5Assert that exception message equals "Cannot divide by zero"Exception message is accessible via exc_info.valueassert str(exc_info.value) == "Cannot divide by zero"PASS
6Test ends successfullyTest framework records test_divide_by_zero as passed-PASS
Failure Scenario
Failing Condition: The divide function does not raise ValueError when dividing by zero
Execution Trace Quiz - 3 Questions
Test your understanding
What does pytest.raises do in this test?
AIt ignores any exceptions during the test
BIt prevents the exception from being raised
CIt catches the expected exception to verify it was raised
DIt retries the function until no exception occurs
Key Result
Use pytest.raises to confirm your code raises the right exception with the expected message. This helps catch errors early and documents expected failure cases clearly.