TS·00
Start Here: Your First Tests
For readers who have written code but few or no tests: what a test is and what it buys you, one small billing function tested three ways (example tests, a property test that finds a real bug, a regression test), arrange-act-assert, why money needs Decimal, the levels of testing from unit to chaos, the vocabulary of the volume, and how to study it.
Start here: how to use this volume
Two reading paths
This volume is about gaining justified confidence that software works: why and how much to test, unit tests, integration tests against real dependencies, contract tests between services, end-to-end tests through a browser, performance tests and chaos experiments. Every chapter has the same shape: a plain-language Start here section with small, verified examples; a How deep to go ladder; the full-depth sections; a Lab of real measurements; and a Revision sheet.
- New to testing? Read this chapter, then the chapters in order. The examples use free tools: pytest and Hypothesis, PostgreSQL, Pact, Playwright, k6 and Toxiproxy. Everything runs on your own machine.
- Experienced? Skip this chapter. In each chapter read the revision sheet first, take its quiz, then use How deep to go to choose the sections and lab experiments to study.
Mastery levels
Every chapter uses the same six levels:
| Level | Name | You can… | Example for unit testing |
|---|---|---|---|
| L1 | Recognition | define it and spot it | "that test depends on the clock, so it's flaky" |
| L2 | Working | apply it in your own code | write fast, isolated tests for a module |
| L3 | Internals | explain why it works | explain how fixtures, mocks and property-based shrinking work |
| L4 | Debugging | find and fix problems | track down a flaky test or a test that can't fail |
| L5 | Design | choose the strategy for a system | decide what to test at which level for a service |
| L6 | Production | run it at scale | run test strategy, CI and quality metrics for an organisation |
What a test is
A test is a small program that runs your code with known inputs and checks the result. It turns "I think this works" into "this works for these cases, and the computer will tell me the moment it stops". That second half is the real value: tests let you change code without fear, because a mistake shows up in seconds instead of in a customer's bill.
The function under test
The tiffin centre's bill: add up the items, apply a coupon, add 5% GST, round to paise.
from decimal import Decimal, ROUND_HALF_UP
GST = Decimal("0.05")
def total(items, coupon_pct=0):
"""items: list of (price_in_rupees: str, qty: int)."""
subtotal = sum(Decimal(p) * q for p, q in items)
discounted = subtotal * (1 - Decimal(coupon_pct) / 100)
return (discounted * (1 + GST)).quantize(Decimal("0.01"), ROUND_HALF_UP)
Money uses Decimal, not floating point, because binary floats can't represent most decimal fractions exactly:
float: 0.1 + 0.2 = 0.30000000000000004
float: round(2.675, 2) = 2.67 (you meant 2.68)
Decimal: 3 × 33.10 × 1.05 = 104.2650 (exact)
Three example tests
def test_one_thali():
assert total([("120", 1)]) == Decimal("126.00")
def test_two_items_with_coupon():
assert total([("120", 2), ("40", 1)], coupon_pct=10) == Decimal("264.60")
def test_empty_order_is_free():
assert total([]) == Decimal("0.00")
Each follows arrange, act, assert: set up inputs, call the code once, check one outcome. They're named for the behaviour they protect, so a failure message reads like a bug report. All three passed. That only means these three cases work.
A property test finds what the examples missed
Instead of picking inputs, a property-based test states something that must be true for every input and lets a library (Hypothesis) generate hundreds of cases:
@given(st.lists(st.tuples(st.integers(1, 500).map(str), st.integers(1, 5)), max_size=5),
st.integers(0, 150))
def test_total_is_never_negative(items, coupon):
assert total(items, coupon) >= 0
items = [('1', 1)], coupon = 101
E AssertionError: assert Decimal('-0.01') >= 0
1 failed, 3 passed in 1.30s
Hypothesis found a 101% coupon that makes the bill negative, then shrank the failing case to the simplest one it could (one ₹1 item). Nobody writing examples by hand thought to try a coupon over 100.
Fix it, and keep the bug from coming back
if not 0 <= coupon_pct <= 100:
raise ValueError(f"coupon must be 0-100%, got {coupon_pct}")
def test_coupon_over_100_is_rejected():
with pytest.raises(ValueError):
total([("1", 1)], 101)
5 passed in 0.16s
The new test is a regression test: it encodes the bug, so if anyone removes the check later, the suite fails. Five tests ran in 0.16 seconds, fast enough to run on every save.
The levels of testing
From one function to the whole system
| Level | Checks | Example for the tiffin centre | Typical speed |
|---|---|---|---|
| Unit | one unit of behaviour in isolation | total() above |
milliseconds |
| Integration | your code against a real dependency | saving an order to PostgreSQL | tens of ms to seconds |
| Contract | two services agree on their interface | orders and kitchen agree on the order JSON | seconds |
| End-to-end | a whole user journey | open the site, order a thali, see the confirmation | seconds to minutes |
| Performance | behaviour under load | p99 latency at 200 orders per second | minutes |
| Chaos | behaviour under failure | the database is slow; do orders still go through? | minutes |
Lower levels are fast, precise and cheap, so you have many of them; higher levels are slow and broad but catch problems the lower ones can't, so you have a few, chosen carefully. Chapter 114 turns that into a strategy.
How to study testing
A routine that works
- Write the test before or with the code, and watch it fail first, so you know it can.
- Name tests for behaviour ("rejects a coupon over 100"), not for methods ("test_total_2").
- Break the code on purpose and check a test goes red; a test that can't fail protects nothing.
- Keep the suite fast; slow suites stop being run.
- When a bug escapes, write the test that would have caught it before fixing it.
Warm-up exercises
- Install pytest and Hypothesis, copy
total()and the tests above, and reproduce the failure and the fix. - Add a property: applying a 0% coupon never changes the total.
- Rewrite
total()with floats and find an order where it is a paisa off. - Find the slowest test in a project you work on (
pytest --durations=5) and work out why it is slow.
Glossary
- Unit test: a fast, isolated test of one behaviour.
- Assertion: the check that decides pass or fail.
- Fixture: reusable setup for tests.
- Property-based test: a test of a rule over generated inputs.
- Shrinking: simplifying a failing generated input.
- Regression test: a test that pins a fixed bug.
- Flaky test: a test that passes and fails without the code changing.
- Test double (mock, stub, fake): a stand-in for a real dependency.