One test, one fact
A tempting habit: cram every assert into one big test_everything. Two problems.
- Remember from lesson 1-3 that a test function stops at its first failed assert. In a mega-test, one failure hides the status of everything after it.
- The name tells you nothing.
FAIL test_everythingsends you digging.FAIL test_zero_weight_rejectedis already half the diagnosis.
So the rule: one behavior per test, named as a sentence about that behavior. A good pattern is test_<situation>_<expected result>, like test_heavy_parcel_adds_per_kg. If you cannot name the test in one short sentence, it is probably testing two things. Split it.
Code exercise · python
Run this. shipping_cost has three behaviors, so it gets three focused tests, each named for its fact. The last one shows how to test that a function raises an error: call it, and if no ValueError arrives, force a failure with assert False.
Quiz
Your suite reports: FAIL test_negative_balance_blocks_withdrawal. What do you know before opening any code?
Code exercise · python
Your turn: test_everything below bundles three behaviors of clamp. Split it into three focused tests named test_inside_range_unchanged, test_below_range_clamps_to_low, and test_above_range_clamps_to_high, then run them with the loop so each prints a PASS line.
Quiz
You need a test proving that expired coupons are not applied at checkout. Which name earns its keep six months from now?