Verify that the custom exception is raised with correct message
Preconditions (2)
✅ Expected Result: The function raises CustomError with message 'Negative value not allowed' when called with negative input
import pytest class CustomError(Exception): pass def risky_function(value: int): if value < 0: raise CustomError('Negative value not allowed') return value def test_risky_function_raises_custom_error(): with pytest.raises(CustomError) as exc_info: risky_function(-1) assert str(exc_info.value) == 'Negative value not allowed'
The code defines a custom exception CustomError and a function risky_function that raises this exception when the input is negative.
The test function test_risky_function_raises_custom_error uses pytest.raises as a context manager to catch the exception. It then asserts that the exception message matches the expected string.
This approach is clear, concise, and follows pytest best practices for testing exceptions.
Now add data-driven testing with 3 different inputs: -5 (should raise), 0 (should not raise), 10 (should not raise)
pytest.raises() in testing custom exceptions?pytest.raises()foo() raises a custom exception MyError using pytest?with and call the function inside the block.class MyError(Exception):
pass
def func():
raise MyError("Error happened")
def test_func():
with pytest.raises(MyError) as exc_info:
func()
assert str(exc_info.value) == "Error happened"def test_error():
with pytest.raises(ValueError):
raise TypeError("Wrong type")MyError that can be raised with different messages. How can you write a pytest test that checks the exception is raised and the message contains the word "timeout" regardless of other text?match argument to check if the exception message matches a regex or substring.with pytest.raises(MyError, match="timeout"): correctly uses the match parameter to verify the message contains "timeout". with pytest.raises(MyError) as e: followed by assert str(e.value) == "timeout" only checks for exact match, failing if there is extra text. Options C and D use invalid syntax.Pass the test and this pattern moves unknown