Tests that catch you before the robot does
Your planner returned a path for six weeks. Then someone added a wall at the map edge and it crashed. Which test would have caught it on day one?
About 35 min · 3 goals · Checked by automated tests
1.Why should I care?
Every module you write is a promise to the rest of the program. Tests are how you check that promise automatically, every time anything changes. They are cheapest to write while you still remember what the function is meant to do.
- ◇ Write assert-based tests that compare a function's output with answers worked out by hand.
- ◇ Choose edge cases (empty, zero, boundary, invalid) that are most likely to expose bugs.
- ◇ Guard a module's demo code with if __name__ == "__main__": so importing it runs nothing.
2.Predict
You test mean(values) with [2, 4, 6] and it returns 4. Which extra test is MOST likely to find a bug?
Guess first. Being wrong here is how the surprise works.
3.Discover
In the Code Lab, write clamp(value, low, high) and five assert tests: inside the range, below, above, exactly on each limit. Then deliberately break clamp (swap low and high) and run the tests again. How many fail, and do their messages tell you why?
Can't use the interactive? Read a description instead
The Code Lab activity can be done on paper: write clamp(value, low, high) and work out by hand the expected result for 50, −5, 130, 0 and 100 with limits 0 and 100. Then imagine low and high swapped inside the function and predict which of the five checks fail.
4.Checkpoint: guided practice
Check what you just discovered before going on. Hints appear after a wrong answer.
Practice 1
Which input is the best edge case for a function that returns the last reading of a sensor log?
5.Understand
A test is a hand-worked answer
assert clamp(150, 0, 100) == 100 states an answer you worked out without the code. If the code disagrees, Python raises AssertionError. A good test is small, names what it checks and has a known right answer.
Hunt the edges
Bugs cluster at boundaries: the first and last item, exactly on a limit, empty input, zero, negative numbers, a goal surrounded by walls. For each function, list the edges before you write tests; most of your tests should live there.
Importable modules
Code at the top level runs when a module is imported. Put demos and quick checks under if __name__ == "__main__":. That block runs when you execute the file directly, but not when a test or another module imports it.
Explain it another way
A test is like a pre-flight checklist: a list of things that must be true before you trust the aircraft, checked the same way every time.
Tools such as pytest collect functions named test_* and report each assert that fails along with the values involved. For floating-point results compare with a tolerance: abs(got - want) < 1e-9 or math.isclose(got, want), never ==.
Safety-critical teams often run thousands of automated tests on every change; a change that breaks one is rejected before it reaches hardware. Your five-line test file is the first step of the same habit.
Worked example 1
Test a clamp function, including both limits, and keep the demo out of imports.
# file: limits.py
def clamp(value, low, high):
"""Return value limited to the range [low, high]. Requires low <= high."""
if low > high:
raise ValueError("low must not exceed high")
return max(low, min(value, high))
if __name__ == "__main__":
print(clamp(130, 0, 100)) # only runs when limits.py is run directlyfrom limits import clamp
def test_clamp():
assert clamp(50, 0, 100) == 50 # inside
assert clamp(-5, 0, 100) == 0 # below
assert clamp(130, 0, 100) == 100 # above
assert clamp(0, 0, 100) == 0 # on the low limit
assert clamp(100, 0, 100) == 100 # on the high limit
test_clamp()
print("all clamp tests passed")Common mix-ups
- Passing tests prove the code is correct.
✓ They prove it is correct for the cases tested. Choosing the right cases, especially edges, is the skill. - Tests are written after the code is finished.
✓ Writing the expected answers first often reveals what the function should do in odd cases before you code it.
6.Practice on your own
Practice, not a test. Wrong answers get a hint and another try.
Practice 2
Which test is safest for mean([0.1, 0.2]) (true answer 0.15)?
Practice 3
Why put demo code under if __name__ == "__main__":?
Practice 4
assert clamp(-5, 0, 100) == 0 fails with clamp returning 100. What is the most likely bug?
Practice 5
Which set of tests gives the most confidence for clamp(value, low, high)?
7.Apply it
For your wheel_rpm or battery_runtime_h function, write a test function with at least five asserts: two normal values worked by hand, one boundary and two that check a ValueError is raised (use try/except and assert inside it). Guard any demo code with if __name__ == "__main__":.
8.Reflect
9.Go further
- Python docs: unittest ↗Python's built-in testing framework, if you want named, organised test cases.
Concepts: Testing and debugging · Functions and decomposition