0
0
PyTesttesting~10 mins

pytest.raises context manager - 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 uses pytest.raises as a context manager to catch the exception and verify it happens as expected.

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 - 5 Steps
StepActionSystem StateAssertionResult
1Test startspytest test runner initialized-PASS
2Calls divide(10, 0) inside pytest.raises context managerFunction divide is called with a=10, b=0-PASS
3divide function raises ValueError("Cannot divide by zero")Exception ValueError is raisedpytest.raises catches ValueErrorPASS
4Assertion checks exception message equals "Cannot divide by zero"Exception info stored in exc_infoassert str(exc_info.value) == "Cannot divide by zero"PASS
5Test ends successfullyNo errors, test passed-PASS
Failure Scenario
Failing Condition: divide 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 logs the exception without failing the test
BIt prevents the function from running
CIt catches the expected exception to verify it was raised
DIt retries the function until no exception occurs
Key Result
Using pytest.raises as a context manager lets you verify that specific exceptions are raised and also inspect their details, making your tests precise and clear.