Test Overview
This test checks if a custom exception is raised correctly when a function receives invalid input. It verifies that the exception type and message are as expected.
This test checks if a custom exception is raised correctly when a function receives invalid input. It verifies that the exception type and message are as expected.
import pytest class CustomError(Exception): pass def divide(a, b): if b == 0: raise CustomError("Cannot divide by zero") return a / b def test_divide_raises_custom_error(): with pytest.raises(CustomError) as exc_info: divide(10, 0) assert str(exc_info.value) == "Cannot divide by zero"
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts | pytest test runner initialized | — | PASS |
| 2 | Calls divide(10, 0) | Function divide is executing with a=10, b=0 | — | PASS |
| 3 | Raises CustomError with message 'Cannot divide by zero' | Exception raised inside divide function | pytest.raises context captures CustomError | PASS |
| 4 | Checks exception message equals 'Cannot divide by zero' | Exception message available in exc_info.value | assert str(exc_info.value) == 'Cannot divide by zero' | PASS |
| 5 | Test ends | Test passed successfully | — | PASS |
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