Small Tests
A small test checks a function on an input where you already know the answer.
If the output is 8, this one case behaves as expected.
Known Inputs
Choose inputs that are simple enough to check by hand.
For a mean function:
A good test is:
print(mean(4, 6))
Expected output:
5.0
The arithmetic is visible.
Use assert for Checks
assert checks that a condition is true:
assert mean(4, 6) == 5
If the condition is true, the program continues silently. If it is false,
Python reports an AssertionError.
Silence can be useful. It means all checks passed.
Tiny tests
The final print runs only if the assertions pass.
Ready to run.
Test Edges
A useful test set often includes:
- a typical case
- a small case
- a boundary case
- a case that once failed
For beginner code, two or three clear checks are better than a large test suite you do not understand.
Test the Behavior, Not the Implementation
Do not only test the case you just mentally used while writing the function. Try at least one different input.
Edit the code so the assertion passes and the output contains checks passed.
Fix the returned value
Ready to run.
HintMatch the asserted behavior
The assertion expects the function to add its two inputs. Inspect the return operator.
SolutionReturn the sum
Change the function body to return a + b. Then add(2, 3) returns 5, the
assertion passes, and the final message is printed.
Small Tests Protect Small Functions
Small tests are not bureaucracy. They are executable examples of what the function should do.