Testing failures in Python
pytest.raises asserts that the call fails, and how.
import pytest
def stars(value):
if not 0 <= value <= 3:
raise ValueError(f"stars out of range: {value}")
return value
def test_rejects_too_many():
with pytest.raises(ValueError, match="out of range"):
stars(9)
def test_reports_the_bad_value():
with pytest.raises(ValueError) as excinfo:
stars(-1)
assert "-1" in str(excinfo.value)
def test_accepts_the_range():
assert [stars(n) for n in range(4)] == [0, 1, 2, 3]
How it works
- The
withblock must contain the failing call and nothing else. matchchecks the message against a regular expression.excinfo.valueis the exception itself, for further assertions.
Keywords and builtins used here
asassertdefforifraiserangereturnstarsstrtest_accepts_the_rangetest_rejects_too_manytest_reports_the_bad_valuewith
The run, in numbers
- Lines
- 22
- Characters to type
- 420
- Tokens
- 114
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 68 seconds.
Step 2 of 3 in Writing tests, step 2 of 9 in Testing with pytest.