Tests do not prove that bugs are absent, but they catch most of them. For algorithms, the most important skill is choosing the edge cases.

What we test

A test calls the function on a given input and compares the result with the expected one. Two principles:

  1. Tests can show that a bug exists, never that it does not.
  2. Bugs usually hide at boundaries: empty input, one element, the first and last index.
An edge-case checklist
An edge-case checklist
CaseExampleWhat it checks
Empty input[]access to the first element
One element[5]a loop that never runs
Duplicates[3, 3, 3]the difference between < and <=
Negative numbers[-4, -1, -9]the starting value

Simple tests with assert

python
def find_max(items):
    best = items[0]
    for x in items:
        if x > best:
            best = x
    return best