1.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.
2.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.
Loading the interactive…
Can't use the interactive? Read a description instead
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.
3.Checkpoint: guided practice
Check what you just discovered before going on. Hints appear after a wrong answer.
Practice 1 · a fresh version every time
You are testing def current_ma(v, r_ohm): return v / r_ohm * 1000. To write assert abs(current_ma(9, 100) - EXPECTED) < 0.01, work EXPECTED out by hand with Ohm's law. What is it, in mA?
Practice 2
A correct function returns 129.99999999999997 for an expected 130. Which test is right?
4.Predict
Which single test input best separates a correct °C-to-°F function from (c + 32) * 9 / 5?
Guess first. Being wrong here is how the surprise works.
5.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
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.
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.
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.
6.Practice on your own
Practice, not a test. Wrong answers get a hint and another try.
Practice 3
Why shouldn't you run the function and paste its output into the test as the expected value?
Practice 4
Which set of inputs best tests c_to_f?
7.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.
8.Reflect
Concepts: Testing and debugging · Functions and decomposition