Test Overview
This test checks that a function correctly handles invalid input by raising an error. It verifies that the program does not crash and handles errors gracefully, ensuring robustness.
This test checks that a function correctly handles invalid input by raising an error. It verifies that the program does not crash and handles errors gracefully, ensuring robustness.
import pytest def divide(a, b): if b == 0: raise ValueError("Cannot divide by zero") return a / b def test_divide_by_zero_raises_error(): with pytest.raises(ValueError) as exc_info: divide(10, 0) assert str(exc_info.value) == "Cannot divide by zero"
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts | Test runner is ready to execute test_divide_by_zero_raises_error | — | PASS |
| 2 | Calls divide(10, 0) | Function divide is executing with b=0 | — | PASS |
| 3 | Function raises ValueError with message 'Cannot divide by zero' | Exception is raised and caught by pytest.raises context manager | Check that ValueError is raised | PASS |
| 4 | Assert exception message equals 'Cannot divide by zero' | Exception message is available in exc_info.value | Exception message matches expected string | PASS |
| 5 | Test ends successfully | Test runner records test as passed | — | PASS |
def test_divide():
with pytest.raises(ZeroDivisionError):
result = 10 / 0
def test_value_error():
with pytest.raises(ValueError):
int('abc')
process_data() raises a KeyError when a required key is missing in input. Which pytest test best ensures robustness by checking this error path?Pass the test and this pattern moves unknown