Lite / Building Machines That Respond / Week 7
Promises and proof: tests with assert
Three versions of a °C-to-°F function all run without errors. Only one is right. How can three lines of tests tell them apart instantly?
Why should I care?
A function's docstring is a promise; a test is the proof. Tests take seconds to write and run every time the code changes, so a bug introduced next month is caught before it reaches a machine.
- Write assert-based tests whose expected values are worked out independently.
- Compare float results within a tolerance in tests.
- Choose test inputs that cover typical, special and boundary cases.
Predict
Which single test input best separates a correct °C-to-°F function from (c + 32) * 9 / 5?
- Any input: they always differ
- 0 °C (should give 32 °F)
- There is no way to tell
Guess first, then reveal
0 °C. The correct function gives 32.0; the wrong one gives (0 + 32) × 9 / 5 = 57.6. Known reference points (freezing, boiling, −40 where the scales meet) make excellent tests.
Discover
Choose c_to_f and run the tests on versions A, B and C. Then choose led_resistor_ohm: version B is correct, but why would assert led_resistor_ohm(3.3, 2.0, 10) == 130 fail for it? Look at the value it actually returns.
What the interactive shows (text version)
The function machine's c_to_f has three versions: A, c * 9 / (5 + 32), gives 0.0 at 0 °C; B, (c + 32) * 9 / 5, gives 57.6; C, c * 9 / 5 + 32, gives 32.0 and passes all tests (0 → 32, 100 → 212, −40 → −40). For led_resistor_ohm, version B returns 129.99999999999997 for (3.3, 2.0, 10), so its tests compare within 1e-9.
Understand
A test is an assert
def c_to_f(c):
"""Convert a temperature in °C to °F."""
return c * 9 / 5 + 32
assert c_to_f(0) == 32
assert c_to_f(100) == 212
assert c_to_f(-40) == -40
print("all tests passed")assert condition does nothing if the condition is True and stops with AssertionError if it is False.
Expected values must be independent
Work out each expected value from somewhere other than the code: a reference point (water freezes at 0 °C = 32 °F), a hand calculation or a datasheet. If you copy the function's own output into the test, the test will happily confirm a bug.
Floats need a tolerance
(3.3 - 2.0) / 0.01 is 129.99999999999997, so == 130 fails even though the function is right. Write assert abs(led_resistor_ohm(3.3, 2.0, 10) - 130) < 1e-9, or math.isclose(...). Pick a tolerance that makes physical sense for the quantity.
Explain it another way
Intuitive
A test is like checking a new kitchen scale with a 1 kg bag of sugar: you already know the right answer, so the scale has to match it.
Technical
assert raises AssertionError when its expression is falsy. Unit tests pin a function's contract at chosen points: typical inputs, special values and boundaries. Frameworks such as pytest collect and run them automatically.
Applied
Engineering software teams run thousands of tests automatically on every change. A failing test blocks the change until someone fixes the code or proves the test wrong.
Worked example 1
Write tests for current_ma(v, r_ohm), which returns the current in mA.
Hand calculations: 5 V / 250 Ω = 0.02 A = 20 mA; 3.3 V / 1000 Ω = 3.3 mA; 0 V gives 0 mA. Tests: assert abs(current_ma(5, 250) - 20) < 1e-9, assert abs(current_ma(3.3, 1000) - 3.3) < 1e-9, assert current_ma(0, 100) == 0.
Common mix-ups
If code runs without an error, it is correct.
✓ Running proves only that it does not crash. Tests against known answers show whether it is right.A failing test always means the function is wrong.
✓ Sometimes the test is wrong, for example by comparing floats with ==. Check both.
Practice
Practice, not a test. Answers are checked on our server; a wrong answer gets a hint and another try. Nothing is saved.
Apply it
Write three tests for your rpm_for_speed function and three for the wheel speed function, with expected values worked out by hand. Break each function on purpose (change 60 to 6) and check a test catches it.
Reflect
What is one function from this term you would not trust until it had tests, and which inputs would you test it with?
Write your answer on paper or in your own notes. Lite never stores what you write.