Verify that a function raises ValueError with correct message
Preconditions (2)
✅ Expected Result: The test should pass only if ValueError is raised and the message contains 'division by zero is not allowed'
import pytest def divide(a, b): if b == 0: raise ValueError('division by zero is not allowed') return a / b def test_divide_by_zero_raises_value_error(): with pytest.raises(ValueError, match='division by zero is not allowed'): divide(10, 0)
The divide function raises a ValueError with a specific message when dividing by zero.
The test function test_divide_by_zero_raises_value_error uses pytest.raises as a context manager to check that calling divide(10, 0) raises a ValueError.
The match parameter in pytest.raises checks that the exception message contains the exact text 'division by zero is not allowed'. This ensures the error is not only the right type but also the right message.
This approach is clean, readable, and uses pytest best practices for exception testing.
Now add tests for a function that raises ValueError with different messages for zero and negative divisors
pytest.raises() in a test?pytest.raises() function is used to verify that a block of code raises a specific exception.exc_info object stores the caught exception. To get its message as a string, use str(exc_info.value).assert 'error' in str(exc_info.value). Directly accessing exc_info.value without converting to string won't work.def test_divide_by_zero():
with pytest.raises(ZeroDivisionError) as exc_info:
x = 1 / 0
assert 'division by zero' in str(exc_info.value)ZeroDivisionError as expected.ZeroDivisionError in Python includes 'division by zero', so the assertion passes.def test_key_error():
with pytest.raises(KeyError) as exc_info:
d = {'a': 1}
value = d['b']
assert 'b' in exc_info.valued['b'] raises a KeyError because 'b' is not in the dictionary.exc_info.value directly, but exc_info.value is an exception object, not a string. It should be converted to string first.ValueError with message "Invalid input: 0" when input is zero. Which pytest test code correctly verifies both exception type and exact message?args tuple; the first element args[0] holds the message string.exc_info.value.args[0] allows exact message comparison. Using str(exc_info.value) works but may include extra formatting. exc_info.value.message does not exist.Pass the test and this pattern moves unknown