Verify that dividing by zero raises a ZeroDivisionError
Preconditions (2)
✅ Expected Result: The test should pass only if 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 function test_divide_by_zero_raises uses pytest.raises as a context manager to check that dividing by zero raises a ZeroDivisionError.
If the exception is raised, the test passes. If not, pytest fails the test.
This approach is clean and clear, following pytest best practices.
Now add data-driven testing to check that dividing by zero raises ZeroDivisionError for multiple numerators: 10, -5, and 0
pytest.raises in a test?pytest.raisespytest.raises is used to verify that a certain exception is raised by the code inside its with block.with block correctly states that it checks for a specific exception. Other options describe unrelated behaviors.with block -> Option DValueError is raised when calling func() using pytest.raises?pytest.raises syntaxwith statement with pytest.raises(ExceptionType): followed by the code that should raise the exception.with block and exception type. pytest.raises(ValueError, func()) calls the function inside the argument, which runs before checking. with pytest.raises('ValueError'): func() uses a string instead of the exception class. pytest.raises(ValueError): func() misses the with keyword.import pytest
def test_zero_division():
with pytest.raises(ZeroDivisionError) as exc_info:
1 / 0
assert 'division by zero' in str(exc_info.value)with pytest.raises(ZeroDivisionError) as exc_info: block raises a ZeroDivisionError by dividing 1 by 0.def test_key_error():
with pytest.raises(KeyError):
d = {'a': 1}
value = d['b']
assert value == 1value = d['b'] raises a KeyError, so value is never assigned inside the with block.with block, the code tries to assert value == 1, but value is undefined because the assignment never happened due to the exception.parse_int(s) that should raise ValueError with message containing 'invalid literal' when given a non-integer string. Which pytest code correctly asserts this behavior and checks the error message?with pytest.raises(ValueError) as e: to catch the exception and store info in e.str(e.value). This converts the exception to string for message checking.e outside the block without capturing it. pytest.raises(ValueError, parse_int('abc'))
assert 'invalid literal' in e.value calls the function inside pytest.raises incorrectly and uses e undefined. with pytest.raises('ValueError') as e:
parse_int('abc')
assert 'invalid literal' in str(e.value) uses exception name as string instead of class.Pass the test and this pattern moves unknown