Read Code Fast
Lesson 18 Tests as the spec
what a test really checks, and the missing test
What you'll learn
- Read test names as a spec
- Judge whether an assertion could really fail
- Spot the missing test
Tests are the one place that says what the code is supposed to do. But a test can pass and prove nothing, so read each one twice.
The idea
Read the test names like a spec. Each name is a promise about the code. Then read the assertion, the line that can fail, and ask: would this fail if the code were wrong? A weak assertion such as assert result passes for almost any answer.
Last, look for the missing test: something the code does that no test name mentions, such as an unknown code, an empty list or a zero. A quick trick: break the code on purpose, change a number, and see which tests notice.
1from app.discounts import apply_discount234def test_vip_gets_25_percent_off():5 assert apply_discount({"total": 100}, "VIP") == 75678def test_spring_gets_10_percent_off():9 result = apply_discount({"total": 100}, "SPRING")10 assert result111213def test_does_not_change_the_order():14 order = {"total": 100}15 apply_discount(order, "VIP")16 assert order["total"] == 100
- Line 4 The names read as a spec: VIP 25 percent, SPRING 10 percent, and the input isn't changed.
- Line 5 A strong assertion: an exact value. If the VIP rate is wrong, this fails.
- Line 10 A weak assertion: any non-zero result passes. A SPRING discount of 0%, or 90%, would still pass.
- Line 16 The end of the file. Nothing here mentions an unknown code, a total of 0 or a negative total. Those promises are missing.
Take away
- Read the test names like a spec: each one is a promise.
- Read the assertion and ask: would this fail if the code were wrong?
- Look for the missing test: a promise the code makes that no test names.
Quiz: test yourself
7 questions: a quick quiz, then a review drill. Pick an answer to see why it's right.