Test Overview
This test checks that a function raises a ValueError with the exact expected message when given invalid input.
This test checks that a function raises a ValueError with the exact expected 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_message(): with pytest.raises(ValueError, match="Cannot divide by zero") as exc_info: divide(10, 0) assert str(exc_info.value) == "Cannot divide by zero"
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts | pytest test runner initialized | — | PASS |
| 2 | Calls divide(10, 0) | Function divide is executing with a=10, b=0 | — | PASS |
| 3 | Function raises ValueError with message 'Cannot divide by zero' | Exception raised inside divide function | pytest checks exception type is ValueError | PASS |
| 4 | pytest matches exception message with 'Cannot divide by zero' | Exception message available for matching | Exception message matches exactly | PASS |
| 5 | Assertion checks exception message string equals 'Cannot divide by zero' | Exception info captured in exc_info | assert str(exc_info.value) == 'Cannot divide by zero' | PASS |
| 6 | Test ends successfully | All assertions passed | — | PASS |
pytest.raises() in a test?pytest.raises() function is used to verify that a block of code raises a specific exception.exc_info object stores the caught exception. To get its message as a string, use str(exc_info.value).assert 'error' in str(exc_info.value). Directly accessing exc_info.value without converting to string won't work.def test_divide_by_zero():
with pytest.raises(ZeroDivisionError) as exc_info:
x = 1 / 0
assert 'division by zero' in str(exc_info.value)ZeroDivisionError as expected.ZeroDivisionError in Python includes 'division by zero', so the assertion passes.def test_key_error():
with pytest.raises(KeyError) as exc_info:
d = {'a': 1}
value = d['b']
assert 'b' in exc_info.valued['b'] raises a KeyError because 'b' is not in the dictionary.exc_info.value directly, but exc_info.value is an exception object, not a string. It should be converted to string first.ValueError with message "Invalid input: 0" when input is zero. Which pytest test code correctly verifies both exception type and exact message?args tuple; the first element args[0] holds the message string.exc_info.value.args[0] allows exact message comparison. Using str(exc_info.value) works but may include extra formatting. exc_info.value.message does not exist.Pass the test and this pattern moves unknown