Test Overview
This test checks that a function raises a ValueError with the correct message when given invalid input.
This test checks that a function raises a ValueError with the correct message when given invalid input.
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"
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts | Test runner is ready to execute test_divide_by_zero | — | PASS |
| 2 | Calls divide(10, 0) | Function divide is executing with a=10, b=0 | — | PASS |
| 3 | Raises ValueError with message 'Cannot divide by zero' | Exception is raised inside divide function | — | PASS |
| 4 | pytest.raises context captures the ValueError as exc_info | Exception info stored in exc_info variable | — | PASS |
| 5 | Assert exc_info.value.args[0] equals 'Cannot divide by zero' | Checking exception message content | Exception message is exactly 'Cannot divide by zero' | PASS |
| 6 | Test ends successfully | Test passed with no errors | — | PASS |
pytest.raises?pytest.raises with as exc_infoexc_info.valueexc_info.value, allowing attribute checks like the message.with pytest.raises(ValueError) as exc_info: and then check exc_info.value. -> Option Dexc_info.valueexc_info.value.str(exc_info.value) returns the exception message text.def divide(x, y):
if y == 0:
raise ZeroDivisionError('Cannot divide by zero')
return x / y
def test_divide():
with pytest.raises(ZeroDivisionError) as exc_info:
divide(5, 0)
assert str(exc_info.value) == 'Cannot divide by zero'pytest.raises captures the exception, and str(exc_info.value) matches the expected message.def test_error():
with pytest.raises(ValueError) as exc_info:
raise ValueError('Invalid input')
assert exc_info.message == 'Invalid input'exc_info.message, but must be accessed via str(exc_info.value).assert exc_info.message == 'Invalid input' with assert str(exc_info.value) == 'Invalid input'.exc_info.message instead of str(exc_info.value) to check message. -> Option AMyError that has an attribute code. Which pytest code correctly checks both the exception type and the code attribute value?as exc_infocode on exc_info.valueexc_info.value, so exc_info.value.code accesses the attribute.Pass the test and this pattern moves unknown