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.
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.
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"
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts | pytest test runner initialized | — | PASS |
| 2 | Calls divide(10, 0) inside pytest.raises context manager | Function divide is called with a=10, b=0 | — | PASS |
| 3 | divide function raises ValueError("Cannot divide by zero") | Exception ValueError is raised | pytest.raises catches ValueError | PASS |
| 4 | Assertion checks exception message equals "Cannot divide by zero" | Exception info stored in exc_info | assert str(exc_info.value) == "Cannot divide by zero" | PASS |
| 5 | Test ends successfully | No errors, test passed | — | PASS |
pytest.raises in a test?pytest.raises to check for a ValueError?with keyword and the exception class without quotes.with pytest.raises(ValueError):. Options A and B miss the with keyword. with pytest.raises('ValueError'):\n function_call() incorrectly uses quotes around the exception.import pytest
def test_divide():
with pytest.raises(ZeroDivisionError):
x = 1 / 0
pytest.raises:import pytest
def test_key_error():
with pytest.raises(KeyError):
d = {'a': 1}
x = d['b']
d = {'a': 1} and x = d['b'] are not indented properly.parse_int(s) that should raise ValueError when given a non-integer string. Which of these test snippets correctly uses pytest.raises to check this behavior and also verifies the error message contains 'invalid'?as excinfo to capture the exception object for later inspection.Pass the test and this pattern moves unknown