Complete worked example
python
import pytest
def batch_size(value):
if value <= 0:
raise ValueError("size must be positive")
return value
def test_valid_size():
assert batch_size(2) == 2
def test_zero_size_rejected():
with pytest.raises(ValueError, match="must be positive"):
batch_size(0)- Reasoning
- pytest.raises acts as a context manager. Put only the operation expected to fail inside its block. If nothing raises, pytest fails the test; if the wrong exception type escapes, the test also fails. The match argument searches the exception message with a regular expression. The complete example checks a valid batch and the zero case. The message is deliberately short and stable. Literal punctuation with regex meaning requires escaping or re.escape. Do not assert a complete traceback, temporary path or incidental formatting as if it were part of the public API.