Verify that dividing by zero raises a ZeroDivisionError
Preconditions (2)
✅ Expected Result: Test passes confirming ZeroDivisionError is raised when dividing by zero
import pytest def divide(a, b): return a / b def test_divide_by_zero_raises(): with pytest.raises(ZeroDivisionError): divide(10, 0)
The divide function simply divides two numbers.
The test test_divide_by_zero_raises uses pytest.raises as a context manager to check that calling divide(10, 0) raises a ZeroDivisionError.
This is the correct way to test exceptions in pytest because it clearly shows the expected error and keeps the test clean.
Now add data-driven testing with 3 different pairs of inputs where division by zero should raise ZeroDivisionError
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