Writing tests is easy. Writing good tests, the ones that really find errors, requires thinking about which cases to choose.
Boundary values
Most errors hide at the boundaries of the intervals, where the behaviour changes. If a function classifies ages, it is not enough to test 5, 30 and 80: you have to test the value just before, right on and just after each boundary.
def classify_age(age):
if age < 0 or age > 120:
return "Invalid"
if age <= 12:
return "Child"
if age <= 17:
return "Teenager"
if age <= 64:
return "Adult"
return "Senior"
for age in [-1, 0, 12, 13, 17, 18, 64, 65, 120, 121]:
print(age, classify_age(age))
# -1 Invalid
# 0 Child
# 12 Child
# 13 Teenager
# 17 Teenager
# 18 Adult
# 64 Adult
# 65 Senior
# 120 Senior
# 121 Invalid
Notice: the values 12 and 13 are on both sides of a boundary. If in the code we had written age < 12 instead of <= 12, only 12 would have detected it. Practice with Boundary values.
Checklist of cases
For any function, think about these cases:
| Case | Example |
|---|---|
| Empty | An empty list [], a text "" |
| A single element | [7] |
| Several elements | The normal case |
| Zero | Divisors, quantities, prices |
| Negatives | Especially if the function assumes positives |
| Repeated | [3, 3, 3] |
| Very large | Performance and logic overflows |
| Invalid data | A text where a number is expected |
def average(items):
return sum(items) / len(items)
print(average([4, 6])) # 5.0
# print(average([])) # ZeroDivisionError: the empty case fails!
Testing the empty list reveals that the function needs to decide what to do: raise a clear error, return 0, return None? That is design, and tests force you to do it.
Also testing the errors
A good test does not only check what works: it checks that what is incorrect fails the way it should.
def average(items):
if not items:
raise ValueError("The list cannot be empty")
return sum(items) / len(items)
try:
average([])
except ValueError as e:
print("Correct:", e) # Correct: The list cannot be empty
Tests in the documentation itself: doctest
The doctest module runs the examples you write in the documentation of a function, and checks that they give the indicated result:
def double(x):
"""Return double x.
>>> double(4)
8
>>> double(0)
0
"""
return x * 2
import doctest
print(doctest.testmod()) # TestResults(failed=0, attempted=2)
It is an excellent way for the documentation to never go out of date: if the example stops being true, it is detected.
Writing the test first
There is a technique called TDD (*Test-Driven Development*): first you write the test, which fails because the function does not exist yet; then you write just enough code for it to pass; finally you improve it. You do not always need to follow it, but writing the cases before the code helps you understand the problem.
Good practices
- Test each function separately, with small, fast cases.
- Each test checks one single thing, with a name that explains what.
- Test the boundaries and the odd cases, not only the happy path.
- Run all the tests again every time you change something: that way you detect what you have accidentally broken.
- When you find a bug, write a test that reproduces it before fixing it, and it will stay there forever.
- Debug with method: reproduce, locate, hypothesis, check, fix one thing at a time.
Lesson summary
- There are syntax, runtime and logic errors; the traceback is read from bottom to top.
- Debug with traces, logging or the debugger (
breakpoint()). assertchecks assumptions; it is not for validating user data.unittestruns organized tests and gives a report; pytest is the popular alternative.- Choose the cases well: boundaries, empty, zero, negatives and expected errors.