Lessons · Python · edge cases first
Test the ends first: nothing, one, everything the same
Most bugs live at the edges of the input: the empty case, the single item, all items equal, and the zero that divides. Test those first; the middle usually follows.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
sum(xs) / len(xs) works for every list you tried and crashes the first time a real user has no data. The empty list is not rare in production; it is the first thing production sends.
How to think about it
For any input, ask: what is the smallest possible one? The one-item one? The one where nothing differs? The one that makes a divisor zero? Decide the answer on purpose, write the test, then write the code.
Worked example
def average(xs):
if not xs:The empty case, decided on purpose.
return None
return sum(xs) / len(xs)
assert average([]) is NoneNothing.
assert average([4]) == 4One.
assert average([3, 3, 3]) == 3Everything the same.
print(average([1, 2, 3, 6]))3.0
Your turn
Decide the empty case for percent.
def percent(part, whole):
if whole == 0:
return
return round(100 * part / whole, 1)Solve one with the tests running
The trap
Testing only the happy path. It passes, ships, and the empty list arrives on the first day.