Verify exception type and message when dividing by zero
Preconditions (2)
✅ Expected Result: Test passes confirming the exception type and message are as expected
import pytest def divide(a: float, b: float) -> float: return a / b def test_divide_by_zero_raises(): with pytest.raises(ZeroDivisionError) as exc_info: divide(10, 0) assert 'division by zero' in str(exc_info.value)
This test defines a simple divide function that divides two numbers.
In the test test_divide_by_zero_raises, we use pytest.raises as a context manager to catch the ZeroDivisionError when dividing by zero.
The as exc_info part captures the exception details, allowing us to check the exception message.
We assert that the string 'division by zero' is part of the exception message to confirm the error is as expected.
Now add data-driven testing to check exception messages for dividing by zero with different numerators
pytest.raises?pytest.raises with as exc_infoexc_info.valueexc_info.value, allowing attribute checks like the message.with pytest.raises(ValueError) as exc_info: and then check exc_info.value. -> Option Dexc_info.valueexc_info.value.str(exc_info.value) returns the exception message text.def divide(x, y):
if y == 0:
raise ZeroDivisionError('Cannot divide by zero')
return x / y
def test_divide():
with pytest.raises(ZeroDivisionError) as exc_info:
divide(5, 0)
assert str(exc_info.value) == 'Cannot divide by zero'pytest.raises captures the exception, and str(exc_info.value) matches the expected message.def test_error():
with pytest.raises(ValueError) as exc_info:
raise ValueError('Invalid input')
assert exc_info.message == 'Invalid input'exc_info.message, but must be accessed via str(exc_info.value).assert exc_info.message == 'Invalid input' with assert str(exc_info.value) == 'Invalid input'.exc_info.message instead of str(exc_info.value) to check message. -> Option AMyError that has an attribute code. Which pytest code correctly checks both the exception type and the code attribute value?as exc_infocode on exc_info.valueexc_info.value, so exc_info.value.code accesses the attribute.Pass the test and this pattern moves unknown