Part 11 / Topic 1 of 12
Why test?
A test is a small piece of code that runs your code and checks the answer. Testing helps you:
- Catch bugs early, before a customer sees a wrong bill.
- Refactor safely. To refactor means to change how code is written without changing what it does. If the tests still pass after the change, you did not break anything.
Think of a car's dashboard warning lights: they tell you about a problem before the engine breaks down.
| Manual testing | Automated testing | |
|---|---|---|
| How | Run the program, look at the output | Code compares the output with the expected answer |
| Speed | Slow, every time | Seconds, every time |
| Mistakes | Easy to miss a wrong number | Never gets tired |
| Best for | Trying a new screen once | Everything you want to keep working |
from shop import apply_discount
# Manual: you must look and decide
print(apply_discount(1000, 10)) # 900.0
# Automated: the expected answer is written down
cases = [(10, 900), (50, 500), (100, 0)]
passed = sum(apply_discount(1000, pct) == want for pct, want in cases)
print(f"{passed}/{len(cases)} passed") # 3/3 passed
shop.py is in examples/. It has small functions for a cart total, a discount and 18% GST. It is our "code under test" in this part. Full demo: 01_manual_vs_automated.py.
๐ Going deeper: a unit test checks one small piece (one function). An integration test checks that several pieces work together (for example code + a real database). Start with unit tests: they are fast and point straight at the bug.
Done here? The practice set for Part 11 โ 7 exercises with solutions โ is on the part page.