Project: a suite for the checkout service that runs in under two minutes
Four tiers, a flaky test cured, a coverage floor and a mutation score you set and defend, all behind one gate with a clock on every stage
You are Abiy. The lab is labs/testing, the checkout service you have worked on for the whole module. The system under test is small and honest: it prices a cart, reserves stock, charges a payment provider and writes the order. Nothing here calls a real provider.
You finish with one command, scripts/gate.py, that runs lint, four tiers of tests with branch coverage, the smoke test and mutation testing, prints the seconds each stage took, and exits 1 if anything is wrong. You already met each technique in a chapter. The project is about putting them together and making the pieces fit a time budget. Start from a clean copy of the lab, because the earlier chapters ask you to delete what you added; you rebuild what you need here, and your earlier work is your reference.
What the suite must contain
| Tier | Where | What it proves | Chapter it comes from |
|---|---|---|---|
| Unit | tests/unit/ |
The pure rules in pricing.py and money.py, at their edges |
The shape of a suite, Coverage and mutation testing |
| Integration | tests/integration/ |
Stock, orders and the API, on a real sqlite file per test, plus the real client against a real provider process | Integration tests with a real database, Test data and fixtures |
| Contract | tests/contract/ |
The provider still answers as fake_provider/contract.json says, and the client reads only what it needs |
API and contract tests |
| Browser | tests/e2e/ |
One customer places one order through the page | End-to-end and browser tests |
Three numbers are yours to choose and defend: the time budget (the brief says 120 seconds), a coverage floor and a mutation floor. A number you cannot defend is a number someone will lower on a bad Friday.
Where the time goes
You do not know where the time will go until you measure, and guesses are usually wrong in the same direction: people blame the big tests and the real cost is a wait inside a small one. Three things in this suite cost real seconds. The browser test starts two servers and a browser, about 1.3 seconds. A real HTTP timeout test waits as long as its timeout. And the provider’s slow mode waits FAKE_PROVIDER_SLOW_S, 1.0 second by default. Unit tests cost nothing you can see.
You will write the slow tests with the defaults first, read --durations, then cut the waits. That is the order to work in on a real suite too: write the test that proves the behaviour, then ask what it costs.
Parallel runs are not free
pytest -n auto from pytest-xdist starts one worker process per CPU and shares the tests out. Each worker imports pytest, FastAPI and the app before it runs anything, and tests that cannot be split, such as one browser test, still take as long as they take. On a suite that finishes in a few seconds the start-up can cost more than it saves. The lab measures it, so you decide with numbers and keep -n for when the serial run is long.
Measure the tests, not the lines
Coverage says which lines ran. Mutation testing says whether the tests would notice if a line were wrong: the tool changes the code one small step at a time (a >= becomes >, a + 5000 becomes + 5001) and reruns the tests, and a mutant that no test fails on has survived. The starter suite covers 92% of pricing.py and kills under half its mutants. Some survivors are equivalent mutants that no test can kill, so the score never reaches 100%, and the floor you set has to allow for them and nothing more.
Where it goes wrong
A gate that skips. A browser test that skips without Chromium turns the gate green with a tier missing. Fail on any skip.
Parallel by reflex. You add -n auto because it is on every blog post, the suite gets slower, and shared state such as the provider’s in-memory charges starts to matter. Measure first.
A threshold nobody defends. A 95% mutation floor with two provably equivalent mutants leaves room for two real survivors. A floor of 100% would fail forever, and a floor of 60% would fail never. Write down why yours is where it is.
A cure nobody checked. Replace a sleep with flush(), see one green run, and call it fixed. A fault that fails half the time looks fixed one time in two. The twenty-run loop is the check, and the break at the end shows it can see the fault.
Work from labs/testing with .venv in place. Export the browser path once per terminal:
export PLAYWRIGHT_BROWSERS_PATH="$PWD/.playwright-browsers"The browser test and the smoke test use ports 8094 and 8095. If something else holds them, set E2E_API_PORT, E2E_PROVIDER_PORT, SMOKE_API_PORT and SMOKE_PROVIDER_PORT to free ports. Times below are from a 12-core Mac and will differ on yours; the shape of them should not.
1. Take the baseline. Start from a clean lab: none of the files the earlier chapters created, and git status showing nothing under tests/, scripts/ or pyproject.toml (the earlier labs end with a put-the-lab-back step). Write down four numbers before you change anything.
time ./scripts/check.sh
.venv/bin/pytest -q --cov=checkout --cov-branch | tail -3
for t in unit integration; do .venv/bin/pytest -q --collect-only tests/$t | tail -1; done
rm -rf mutants && .venv/bin/python scripts/mutate.py run 2>&1 | tail -c 100ALL CHECKS PASSED after about 5 seconds (real 5.3 on my machine), with 24 passed, 1 deselected for the suite. Coverage TOTAL ... 80%. Then 10 tests collected and 6 tests collected. The mutation run ends 68/68 🎉 28 ... 🙁 40: 28 of 68 mutants killed in pricing.py, 41%. Eighty per cent coverage and 41% killed is the picture to beat. The starter suite already meets the two-minute budget. The budget matters because of what you are about to add.2. Register the tiers. Edit pyproject.toml so the options read as below (the [tool.coverage.run], [tool.mutmut] and [tool.ruff] blocks stay). --strict-markers makes a misspelt marker an error.
[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "-ra --strict-markers -m 'not flaky' -p no:schemathesis"
markers = [
"unit: pure code, no I/O (tests/unit)",
"integration: a real sqlite file or a real local process (tests/integration)",
"contract: the provider's answers against fake_provider/contract.json, and what the client reads (tests/contract)",
"flaky: deliberately flaky (sleep-based); quarantined from the default run, run with -m flaky",
"e2e: browser test; skipped unless Playwright's Chromium is installed",
]Append this to tests/conftest.py, which gives each test the marker of the folder it sits in:
TIERS = ("unit", "integration", "contract", "e2e")
def pytest_collection_modifyitems(items):
"""Give every test the marker of the tests/ folder it lives in."""
for item in items:
parts = Path(str(item.path)).parts
for tier in TIERS:
if tier in parts:
item.add_marker(getattr(pytest.mark, tier))This is the hook from The shape of a suite with one more tier, contract. Folders that are not a tier, such as tests/extras/, stay unmarked. If you built tests/api/ in API and contract tests, it is gone: you start from a clean lab, and the API tests here live in tests/integration/.
.venv/bin/pytest -q -m unit --collect-only | tail -110/25 tests collected (15 deselected). The marker follows the folder. Remember that a -m on the command line replaces the -m 'not flaky' in addopts, so anything you type with -m has to say and not flaky itself.3. The unit tier. Create tests/unit/test_money_edges.py. It pins the stated rounding rule at the half kobo, which the starter never tests:
import pytest
from checkout.money import VAT_RATE_BP, format_naira, percent_of, vat_on
@pytest.mark.parametrize(
"net, vat",
[
(0, 0),
(1, 0), # 0.075 kobo rounds down
(6, 0), # 0.45 kobo rounds down
(7, 1), # 0.525 kobo rounds up
(20, 2), # 1.5 kobo: exactly half rounds UP (the stated rule)
(60, 5), # 4.5 kobo: half up again
(1_000_000, 75_000),
],
)
def test_vat_rounds_half_up(net, vat):
assert vat_on(net) == vat
def test_vat_rate_is_seven_and_a_half_percent():
assert VAT_RATE_BP == 750
@pytest.mark.parametrize(
"amount, bp, expected",
[(1_000_000, 500, 50_000), (999, 500, 49), (1, 9999, 0), (0, 1000, 0), (10_000, 10_000, 10_000)],
)
def test_percent_of_rounds_down(amount, bp, expected):
assert percent_of(amount, bp) == expected
@pytest.mark.parametrize(
"kobo, text",
[(0, "N0.00"), (5, "N0.05"), (100, "N1.00"), (1_234_550, "N12,345.50"), (100_000_000, "N1,000,000.00")],
)
def test_format_naira(kobo, text):
assert format_naira(kobo) == textCreate tests/unit/test_pricing_edges.py. Every tier boundary, every delivery band edge, and the promo window on both sides of a Lagos midnight (UTC+1, so 23:00 UTC is midnight in Lagos):
from datetime import datetime, timezone
import pytest
from checkout.pricing import (
DELIVERY_FAR_FEE,
PROMOS,
Line,
delivery_fee,
discount_bp,
line_total,
price_cart,
promo_applies,
)
UTC = timezone.utc
NOW = datetime(2026, 11, 23, 9, 0, tzinfo=UTC) # outside the promo
IN_PROMO = datetime(2026, 12, 15, 12, 0, tzinfo=UTC)
HARMATTAN = PROMOS["HARMATTAN"]
def test_line_total_multiplies():
assert line_total(Line(250_000, 3)) == 750_000
@pytest.mark.parametrize("qty", [0, -1])
def test_line_total_rejects_a_quantity_below_one(qty):
with pytest.raises(ValueError, match="at least 1"):
line_total(Line(100, qty))
@pytest.mark.parametrize(
"subtotal, bp",
[
(0, 0),
(999_999, 0), # one kobo under N10,000
(1_000_000, 500), # exactly N10,000: 5%
(1_000_001, 500),
(4_999_999, 500),
(5_000_000, 1000), # exactly N50,000: 10%
(8_000_000, 1000),
],
)
def test_discount_tier_boundaries(subtotal, bp):
assert discount_bp(subtotal) == bp
@pytest.mark.parametrize(
"km, fee",
[
(0, 150_000), (5, 150_000), (6, 300_000), (15, 300_000),
(16, 500_000), (40, 500_000), (41, DELIVERY_FAR_FEE),
],
)
def test_delivery_band_edges(km, fee):
assert delivery_fee(km) == fee
def test_negative_distance_is_rejected():
with pytest.raises(ValueError, match="negative"):
delivery_fee(-1)
@pytest.mark.parametrize(
"moment, live",
[
(datetime(2026, 11, 30, 22, 59, 59, tzinfo=UTC), False), # 23:59:59 on 30 Nov in Lagos
(datetime(2026, 11, 30, 23, 0, 0, tzinfo=UTC), True), # 00:00 on 1 Dec in Lagos
(datetime(2026, 12, 31, 22, 59, 59, tzinfo=UTC), True), # 23:59:59 on 31 Dec in Lagos
(datetime(2026, 12, 31, 23, 0, 0, tzinfo=UTC), False), # 00:00 on 1 Jan in Lagos
(IN_PROMO, True),
],
)
def test_promo_window_follows_the_lagos_day(moment, live):
assert promo_applies(HARMATTAN, moment) is live
def test_price_cart_adds_up_every_part():
quote = price_cart([Line(300_000, 2)], distance_km=3, now=NOW)
assert quote.as_dict() == {
"subtotal": 600_000, "tier_discount": 0, "promo_discount": 0,
"net": 600_000, "vat": 45_000, "delivery_fee": 150_000, "total": 795_000,
}
def test_tier_discount_at_the_boundary_flows_into_vat_and_total():
quote = price_cart([Line(1_000_000, 1)], distance_km=0, now=NOW)
assert quote.tier_discount == 50_000
assert quote.net == 950_000
assert quote.vat == 71_250
assert quote.total == 950_000 + 71_250 + 150_000
def test_promo_applies_after_the_tier_discount():
quote = price_cart([Line(1_000_000, 1)], distance_km=0, now=IN_PROMO, promo_code="HARMATTAN")
assert quote.tier_discount == 50_000
assert quote.promo_discount == 95_000 # 10% of 950,000, not of 1,000,000
assert quote.net == 855_000
def test_promo_is_ignored_outside_its_dates_and_for_unknown_codes():
assert price_cart([Line(1_000_000, 1)], 0, NOW, "HARMATTAN").promo_discount == 0
assert price_cart([Line(1_000_000, 1)], 0, IN_PROMO, "NOSUCH").promo_discount == 0
assert price_cart([Line(1_000_000, 1)], 0, IN_PROMO).promo_discount == 0
def test_vat_is_charged_on_goods_not_on_delivery():
quote = price_cart([Line(100_000, 1)], distance_km=100, now=NOW)
assert quote.vat == 7_500
assert quote.total == 100_000 + 7_500 + DELIVERY_FAR_FEE
def test_an_empty_cart_prices_to_delivery_only():
quote = price_cart([], distance_km=0, now=NOW)
assert quote.total == 150_000.venv/bin/pytest tests/unit -q57 passed. They pass on clean code, as they should: they pin what the code does at its edges. They only earn their place if they fail when the code is wrong, which step 4 tests.4. Measure the unit tier by mutation, on both money files. In pyproject.toml, under [tool.mutmut], add "checkout/money.py" to paths_to_mutate and remove it from also_copy (a file cannot be both):
paths_to_mutate = ["checkout/pricing.py", "checkout/money.py"]
also_copy = ["checkout/__init__.py", "checkout/clock.py", "checkout/db.py", "checkout/payments_client.py", "checkout/search_index.py"]rm -rf mutants
.venv/bin/python scripts/mutate.py run 2>&1 | tail -c 100
.venv/bin/python scripts/mutate.py resultsThe run ends 82/82 🎉 77 ... 🙁 5: 77 of 82 killed, 94%, in about 2 seconds. Before your tests it was 39 of 82, 48%. The survivors:
checkout.pricing.x_line_total__mutmut_4: survived
checkout.pricing.x_delivery_fee__mutmut_4: survived
checkout.pricing.x_promo_applies__mutmut_2: survived
checkout.pricing.x_price_cart__mutmut_15: survived
checkout.money.x_vat_on__mutmut_4: survivedLook at each with .venv/bin/python scripts/mutate.py show <name>. Four of the five are worth reasoning about:
line_total_4anddelivery_fee_4change the text of an error message, to"XXqty must be at least 1XX". Yourpytest.raises(..., match=...)used a pattern that still matches inside the longer text. Anchor both patterns:match="^qty must be at least 1$"andmatch="^distance cannot be negative$".promo_applies_2replacesnow.astimezone(LAGOS)withnow.astimezone(None), which reads the machine’s own time zone. If your laptop is set to Lagos, as the one this was written on is, the mutant behaves the same and survives. Kill it by making the test machine’s zone something else:
def test_the_promo_day_is_read_in_lagos_whatever_the_machine_zone(monkeypatch):
# A mutant that reads the machine's own zone survives on a laptop set to Lagos.
monkeypatch.setenv("TZ", "America/New_York")
time.tzset()
try:
assert promo_applies(HARMATTAN, datetime(2026, 11, 30, 23, 0, 0, tzinfo=UTC)) is True
assert promo_applies(HARMATTAN, datetime(2026, 12, 31, 23, 0, 0, tzinfo=UTC)) is False
finally:
monkeypatch.undo()
time.tzset()Add import time to the imports at the top of the file and put this test above test_price_cart_adds_up_every_part. The finally block puts the zone back for the tests that follow.
price_cart_15changespromo_code or ""topromo_code or "XXXX". Looking up""and looking up"XXXX"both find nothing, so no input can tell them apart. That is an equivalent mutant.vat_on_4changes+ 5000to+ 5001. The productnet_kobo * 750is always a multiple of 250, so adding 5000 or 5001 never crosses a multiple of 10,000 differently. Also equivalent.
rm -rf mutants
.venv/bin/python scripts/mutate.py run 2>&1 | tail -c 10082/82 🎉 80 ... 🙁 2: 80 of 82, 97.6%. The two survivors are the two equivalent mutants. Your ceiling is 97.6%, not 100%. Write a mutation floor in your notes and the reason for it. I use 95%: it allows the two equivalents and two real survivors, and it fails the day a rule gains a branch with no test.5. The integration tier. Every test here uses the db fixture, a fresh sqlite file in tmp_path. Create tests/integration/test_inventory.py:
"""Stock rules against a real sqlite file (the `db` fixture makes a fresh one per test)."""
import pytest
from checkout.inventory import OutOfStock, release_all, reserve, reserve_all
def test_reserve_takes_stock_and_release_puts_it_back(db):
assert reserve(db, 3, 2) is True
assert db.stock_of(3) == 3
release_all(db, [{"product_id": 3, "qty": 2}])
assert db.stock_of(3) == 5
def test_reserving_exactly_what_is_left_works_and_one_more_does_not(db):
assert reserve(db, 3, 5) is True
assert db.stock_of(3) == 0
assert reserve(db, 3, 1) is False
assert db.stock_of(3) == 0 # a refused reservation leaves the count alone
def test_a_shortfall_on_the_second_line_puts_the_first_line_back(db):
lines = [{"product_id": 2, "qty": 10}, {"product_id": 3, "qty": 6}] # product 3 has 5
with pytest.raises(OutOfStock) as caught:
reserve_all(db, lines)
assert caught.value.product_id == 3
assert db.stock_of(2) == 100
assert db.stock_of(3) == 5Create tests/integration/test_order_flow.py. It checks what a mock cannot: after a retry with the same key there is one order, one charge and one decrement of stock; after a failed charge the stock is back.
"""place_order against a real sqlite file and a stub provider."""
import pytest
from checkout.inventory import OutOfStock
from checkout.orders import PaymentDeclined, UnknownProduct, place_order
from checkout.payments_client import ChargeResult, PaymentUnavailable
from tests.conftest import StubPayments
ONE_SHEA = [{"product_id": 2, "qty": 1}]
def test_a_retry_with_the_same_key_returns_the_first_order_and_charges_once(db, payments, clock):
first, created_first = place_order(db, payments, clock, ONE_SHEA, "retry-1")
second, created_second = place_order(db, payments, clock, ONE_SHEA, "retry-1")
assert (created_first, created_second) == (True, False)
assert second["id"] == first["id"]
assert len(payments.calls) == 1
assert db.count_orders() == 1
assert db.stock_of(2) == 99
def test_different_keys_make_different_orders(db, payments, clock):
a, _ = place_order(db, payments, clock, ONE_SHEA, "key-a")
b, _ = place_order(db, payments, clock, ONE_SHEA, "key-b")
assert a["id"] != b["id"]
assert db.stock_of(2) == 98
def test_the_order_records_the_quoted_total_and_its_lines(db, payments, clock):
order, _ = place_order(db, payments, clock, [{"product_id": 2, "qty": 2}], "k", distance_km=3)
assert order["total_kobo"] == 902_500
assert payments.calls == [("k", 902_500, "k")]
assert order["lines"] == [{"product_id": 2, "qty": 2, "unit_price_kobo": 350_000}]
assert order["charge_id"] == "ch_stub"
def test_a_provider_outage_leaves_no_order_and_all_the_stock(db, clock):
class Down:
def charge(self, reference, amount_kobo, idempotency_key):
raise PaymentUnavailable("down")
with pytest.raises(PaymentUnavailable):
place_order(db, Down(), clock, ONE_SHEA, "k")
assert db.count_orders() == 0
assert db.stock_of(2) == 100
def test_a_declined_card_leaves_no_order(db, clock):
declining = StubPayments(ChargeResult("", "declined", "insufficient_funds"))
with pytest.raises(PaymentDeclined) as caught:
place_order(db, declining, clock, ONE_SHEA, "k")
assert caught.value.code == "insufficient_funds"
assert db.count_orders() == 0
def test_a_draft_product_cannot_be_bought_and_nothing_is_charged(db, payments, clock):
with pytest.raises(UnknownProduct):
place_order(db, payments, clock, [{"product_id": 4, "qty": 1}], "k")
assert payments.calls == []
def test_buying_more_than_is_in_stock_charges_nothing(db, payments, clock):
with pytest.raises(OutOfStock):
place_order(db, payments, clock, [{"product_id": 3, "qty": 6}], "k")
assert payments.calls == []
assert db.stock_of(3) == 5Create tests/integration/test_orders_api.py, the API through FastAPI’s TestClient:
"""POST /orders and GET /orders/{id} through FastAPI's TestClient, a real sqlite file, a stub provider."""
import pytest
from fastapi.testclient import TestClient
from checkout.api import create_app
from checkout.search_index import SearchIndex
@pytest.fixture
def client(db, payments, clock):
return TestClient(create_app(db, payments, clock, SearchIndex()))
def post_order(client, key="api-1", qty=2, **extra):
body = {"lines": [{"product_id": 2, "qty": qty}], "distance_km": 3, **extra}
return client.post("/orders", json=body, headers={"Idempotency-Key": key})
def test_post_orders_creates_then_replays(client):
first = post_order(client)
replay = post_order(client)
assert first.status_code == 201
assert replay.status_code == 200
assert replay.json() == first.json()
assert first.json()["total_kobo"] == 902_500
assert first.json()["id"].startswith("ord_")
def test_get_order_returns_what_was_placed(client):
placed = post_order(client).json()
got = client.get(f"/orders/{placed['id']}")
assert got.status_code == 200
assert got.json() == placed
def test_get_unknown_order_is_a_404_with_the_error_shape(client):
resp = client.get("/orders/ord_nope")
assert resp.status_code == 404
assert resp.json() == {"error": "not_found", "detail": "ord_nope"}
@pytest.mark.parametrize(
"product_id, qty, status, code",
[(99, 1, 404, "unknown_product"), (4, 1, 404, "unknown_product"), (3, 6, 409, "out_of_stock")],
)
def test_order_errors_map_to_status_and_code(client, product_id, qty, status, code):
body = {"lines": [{"product_id": product_id, "qty": qty}]}
resp = client.post("/orders", json=body, headers={"Idempotency-Key": "e"})
assert resp.status_code == status
assert resp.json()["error"] == code
def test_a_missing_idempotency_key_is_rejected(client):
resp = client.post("/orders", json={"lines": [{"product_id": 2, "qty": 1}]})
assert resp.status_code == 422
def test_zero_quantity_is_rejected_before_any_stock_moves(client, db):
resp = post_order(client, qty=0)
assert resp.status_code == 422
assert db.stock_of(2) == 100.venv/bin/pytest tests/integration -q24 passed (your six starter tests and eighteen new ones), in about 0.7 seconds. Each test builds its own database file, so none depends on another and pytest-randomly can shuffle them freely.6. The contract tier. Create tests/contract/__init__.py (empty) and tests/contract/conftest.py. The provider keeps its charges in module-level dictionaries, so the fixture resets them around every test. conforms checks a response body against the contract’s schema for its status code:
import json
from pathlib import Path
import pytest
from fastapi.testclient import TestClient
from jsonschema import Draft7Validator
from fake_provider.app import app as provider_app
from fake_provider.app import reset
CONTRACT = json.loads((Path(__file__).resolve().parents[2] / "fake_provider" / "contract.json").read_text())
@pytest.fixture
def provider():
"""The fake provider in-process. Its state is module-level, so every test starts from a reset."""
reset()
yield TestClient(provider_app)
reset()
@pytest.fixture
def conforms():
"""conforms(response, 'POST /v1/charges') checks the body against the contract for its status."""
def check(response, endpoint):
schema = CONTRACT["endpoints"][endpoint]["responses"][str(response.status_code)]
schema = {**schema, "definitions": CONTRACT["definitions"]}
errors = sorted(Draft7Validator(schema).iter_errors(response.json()), key=lambda e: list(e.path))
assert not errors, f"{endpoint} {response.status_code} breaks the contract: {errors[0].message}"
return checkCreate tests/contract/test_provider_contract.py. It asks whether the provider still answers as the contract says; slow mode shortens its wait to 0.05 seconds so the test costs nothing:
"""Does the provider still answer the way fake_provider/contract.json says it does?"""
CHARGE = {"reference": "ord-1", "amount_kobo": 500_000, "currency": "NGN"}
POST = "POST /v1/charges"
def test_a_new_charge_is_201_and_matches(provider, conforms):
resp = provider.post("/v1/charges", json=CHARGE, headers={"Idempotency-Key": "c1"})
assert resp.status_code == 201
conforms(resp, POST)
def test_the_same_key_is_200_with_the_same_charge(provider, conforms):
first = provider.post("/v1/charges", json=CHARGE, headers={"Idempotency-Key": "c2"})
again = provider.post("/v1/charges", json=CHARGE, headers={"Idempotency-Key": "c2"})
assert again.status_code == 200
assert again.json() == first.json()
conforms(again, POST)
assert provider.get("/_admin/stats").json() == {"charges": 1}
def test_a_decline_is_402_and_matches(provider, conforms):
resp = provider.post("/v1/charges", json=CHARGE, headers={"X-Fake-Mode": "decline"})
assert resp.status_code == 402
conforms(resp, POST)
def test_a_provider_error_is_500_and_matches(provider, conforms):
resp = provider.post("/v1/charges", json=CHARGE, headers={"X-Fake-Mode": "500"})
assert resp.status_code == 500
conforms(resp, POST)
def test_slow_mode_still_answers_in_contract(provider, conforms, monkeypatch):
monkeypatch.setenv("FAKE_PROVIDER_SLOW_S", "0.05") # 0.05 s, not the default 1.0 s
resp = provider.post("/v1/charges", json=CHARGE, headers={"X-Fake-Mode": "slow"})
assert resp.status_code == 201
conforms(resp, POST)
def test_get_charge_matches_for_found_and_not_found(provider, conforms):
made = provider.post("/v1/charges", json=CHARGE).json()
found = provider.get(f"/v1/charges/{made['id']}")
missing = provider.get("/v1/charges/ch_nope")
assert (found.status_code, missing.status_code) == (200, 404)
conforms(found, "GET /v1/charges/{id}")
conforms(missing, "GET /v1/charges/{id}")Create tests/contract/test_payments_client_consumer.py. It pins what checkout reads (id, status on success, code on a decline) and how it classifies failures, with httpx.MockTransport and no network:
"""The consumer side: checkout reads only `id`, `status` and `code`. Pin exactly that, nothing more."""
import httpx
import pytest
from checkout.payments_client import ChargeResult, PaymentsClient, PaymentUnavailable
def client_for(handler):
return PaymentsClient("http://provider.test", transport=httpx.MockTransport(handler))
def test_a_success_needs_only_id_and_status():
client = client_for(lambda req: httpx.Response(201, json={"id": "ch_1", "status": "succeeded"}))
assert client.charge("r", 1000, "k") == ChargeResult("ch_1", "succeeded")
def test_extra_fields_from_the_provider_are_ignored():
body = {"id": "ch_1", "status": "succeeded", "amount_kobo": 1000, "risk_score": 0.1}
client = client_for(lambda req: httpx.Response(201, json=body))
assert client.charge("r", 1000, "k").id == "ch_1"
def test_a_decline_needs_only_the_code():
client = client_for(lambda req: httpx.Response(402, json={"error": "card_declined", "code": "insufficient_funds"}))
assert client.charge("r", 1000, "k") == ChargeResult("", "declined", "insufficient_funds")
def test_the_request_carries_the_key_and_the_amount():
seen = {}
def handler(request):
seen["key"] = request.headers["Idempotency-Key"]
seen["body"] = request.read()
return httpx.Response(201, json={"id": "ch_1", "status": "succeeded"})
client_for(handler).charge("ord-9", 1234, "key-9")
assert seen["key"] == "key-9"
assert b'"amount_kobo":1234' in seen["body"].replace(b" ", b"")
@pytest.mark.parametrize("status", [500, 502, 503])
def test_any_5xx_is_unavailable(status):
with pytest.raises(PaymentUnavailable):
client_for(lambda req: httpx.Response(status, json={"error": "x"})).charge("r", 1, "k")
def test_a_timeout_is_unavailable_and_does_not_wait():
def handler(request):
raise httpx.ReadTimeout("simulated", request=request)
with pytest.raises(PaymentUnavailable, match="timed out"):
client_for(handler).charge("r", 1, "k")
def test_a_refused_connection_is_unavailable():
def handler(request):
raise httpx.ConnectError("refused", request=request)
with pytest.raises(PaymentUnavailable, match="unreachable"):
client_for(handler).charge("r", 1, "k").venv/bin/pytest tests/contract -q15 passed in 0.15s.Now make the contract earn its place. In fake_provider/app.py, change "reference": body.reference, to "ref": body.reference, and run both tiers:
.venv/bin/pytest tests/contract tests/integration -q -p no:randomly | tail -6'reference' is a required property, and 4 failed, 35 passed. Every integration and consumer test stays green, because checkout never reads reference. The contract is the provider’s promise to all its consumers; the consumer test pins what this one needs. Revert the edit.7. The real wire, and where the time goes. A timeout cannot be tested in process, since it needs a client that really waits. Create tests/integration/test_provider_over_http.py. The fixture starts the provider on a free port, never a fixed one, so it cannot collide with the browser test, and it kills the process on teardown because timeout mode sleeps 30 seconds. The constants at the top are the provider’s and the client’s defaults:
"""checkout's real HTTP client against the real fake provider process: timeouts need a real wire."""
import os
import socket
import subprocess
import sys
import time
import urllib.request
from pathlib import Path
import pytest
from checkout.payments_client import PaymentsClient, PaymentUnavailable
LAB = Path(__file__).resolve().parents[2]
CLIENT_TIMEOUT_S = 2.0 # what the client waits before giving up (its default)
PROVIDER_SLOW_S = 1.0 # how long the provider's `slow` mode waits (its default)
def free_port():
with socket.socket() as s:
s.bind(("127.0.0.1", 0))
return s.getsockname()[1]
@pytest.fixture(scope="module")
def provider_url():
port = free_port()
cmd = [sys.executable, "-m", "uvicorn", "--log-level", "warning", "--port", str(port), "fake_provider.app:app"]
proc = subprocess.Popen(cmd, cwd=LAB, env=dict(os.environ, CHECKOUT_AUTOSTART="0", FAKE_PROVIDER_SLOW_S=str(PROVIDER_SLOW_S)))
url = f"http://127.0.0.1:{port}"
try:
for _ in range(100):
try:
urllib.request.urlopen(url + "/openapi.json", timeout=1)
break
except OSError:
time.sleep(0.1)
else:
raise RuntimeError("provider did not start")
yield url
finally:
proc.kill() # the provider's `timeout` mode sleeps 30 s; do not wait for it
proc.wait(timeout=10)
def charge(url, mode, timeout_s):
client = PaymentsClient(url, timeout_s=timeout_s, headers={"X-Fake-Mode": mode})
return client.charge("ord-1", 500_000, "wire-" + mode)
def test_the_client_gives_up_on_a_hung_provider_after_its_timeout(provider_url):
started = time.perf_counter()
with pytest.raises(PaymentUnavailable, match="timed out"):
charge(provider_url, "timeout", timeout_s=CLIENT_TIMEOUT_S)
assert CLIENT_TIMEOUT_S <= time.perf_counter() - started < CLIENT_TIMEOUT_S + 1.0
def test_a_provider_that_is_slow_but_inside_the_timeout_still_succeeds(provider_url):
result = charge(provider_url, "slow", timeout_s=PROVIDER_SLOW_S * 3)
assert result.status == "succeeded"
def test_a_500_over_the_wire_is_unavailable(provider_url):
with pytest.raises(PaymentUnavailable, match="500"):
charge(provider_url, "500", timeout_s=2.0).venv/bin/pytest -q --durations=4 -p no:randomly108 passed, 1 deselected in 5.79s, and the slowest tests are 2.04s call ...test_the_client_gives_up_on_a_hung_provider_after_its_timeout, 1.01s call ...test_a_provider_that_is_slow_but_inside_the_timeout_still_succeeds, then the browser test’s setup at about 0.44 s. Two waits cost three seconds of a 5.8-second run, and they test nothing a shorter wait would not. Nobody guessed they would be the slowest tests in the suite.Cut the waits without removing the tests. Change the two constants and run again:
CLIENT_TIMEOUT_S = 0.3 # long enough to be a real timeout, short enough not to be felt
PROVIDER_SLOW_S = 0.2 # the slow test gives the client 3 x this.venv/bin/pytest -q --durations=4 -p no:randomly108 passed, 1 deselected in 3.34s. The slowest items are now the browser test’s setup, teardown and call. The suite lost 2.4 seconds by shortening two numbers.8. Cure the flaky test. In the starter, the quarantined test sleeps 0.05 s and hopes the index is done. Replace the whole of tests/test_flaky_example.py:
"""The old sleep-based search test, cured: it waits for the index's queue, not for a guessed time."""
from checkout.search_index import SearchIndex
def test_new_product_is_searchable_after_a_flush():
index = SearchIndex(lag_s=0.05, jitter=True) # each update still waits 0 to 0.1 s
index.submit({"id": 7, "seller_id": "s", "name": "Shea butter", "status": "published"})
index.flush() # returns when the worker has applied it
assert [d["id"] for d in index.search("shea")] == [7]The flaky marker stays registered for the day another test needs quarantine. Now count the tiers:
for m in unit integration contract e2e; do .venv/bin/pytest -q -m "$m and not flaky" --collect-only | tail -1; done58/109, 27/109, 15/109 and 1/109 tests collected. Fifty-eight, 27, 15 and one are 101 of 109. The other eight are the seven add-on tests in tests/extras/ and the cured search test, which sit in no tier folder. Say where you want them, or leave them out on purpose.9. Decide whether to parallelise. Run the suite serially and with workers, three times each:
for opt in "-p no:xdist" "-n 2" "-n 4" "-n auto"; do echo "== $opt"; for i in 1 2 3; do /usr/bin/time -p .venv/bin/pytest -q $opt 2>&1 | grep -E "passed|failed|^real" | tr '\n' ' '; echo; done; donereal 3.5 to 3.8. -n 2: real 3.6 to 5.0. -n 4: 3.7 to 4.2. -n auto (12 CPUs here): 4.0 to 4.4. Parallel is no faster and sometimes slower. The suite has no long list of independent tests to share out, so the workers’ start-up eats the gain. Keep the gate serial and write down the number at which you would turn -n on.10. Build the gate. Create scripts/gate.py. Its three constants are the numbers you defend:
"""The whole gate in one command, with a clock on every stage. From labs/testing:
.venv/bin/python scripts/gate.py
Stages: lint, tests with branch coverage (all four tiers), the smoke test, mutation testing.
Exits 1 if a stage fails, any test is skipped, coverage or the mutation score is under its floor, or the total
is over the budget. Edit the three numbers below; each one is yours to defend.
"""
import glob
import json
import re
import shutil
import subprocess
import sys
import time
BUDGET_S = 120 # the whole gate
COVERAGE_MIN = 85 # percent, line and branch together, over checkout/
MUTATION_MIN = 0.95 # killed / all mutants, over pricing.py and money.py
PY = sys.executable
STAGES = [
("lint", [PY, "-m", "ruff", "check", "checkout", "fake_provider", "tests", "scripts"]),
("tests + coverage", [PY, "-m", "pytest", "-q", "--cov=checkout", "--cov-branch",
f"--cov-fail-under={COVERAGE_MIN}", "--cov-report=term:skip-covered"]),
("smoke test", [PY, "scripts/smoke_test.py"]),
]
def run(cmd):
started = time.perf_counter()
proc = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)
took = time.perf_counter() - started
if proc.returncode != 0:
print(proc.stdout[-3000:])
return proc.returncode == 0, took, proc.stdout
def mutation_score():
killed = total = 0
for meta in glob.glob("mutants/**/*.meta", recursive=True):
for code in json.load(open(meta))["exit_code_by_key"].values():
total += 1
killed += code in (1, 3)
return killed, total
def main():
results = []
for name, cmd in STAGES:
ok, took, out = run(cmd)
note = ""
if name.startswith("tests"):
cover = next((ln.split()[-1] for ln in out.splitlines() if ln.startswith("TOTAL")), "?")
counts = re.search(r"(\d+ passed)(, \d+ skipped)?", out)
note = f"{counts.group(0) if counts else 'no tests ran'}, coverage {cover}"
if counts and counts.group(2): # a skipped tier is a hole, not a pass
ok, note = False, note + " (a skip fails the gate: install Chromium)"
results.append((name, ok, took, note))
shutil.rmtree("mutants", ignore_errors=True) # a stale cache can hide survivors
ok, took, _ = run([PY, "scripts/mutate.py", "run"])
killed, total = mutation_score()
score = killed / total if total else 0.0
ok = ok and score >= MUTATION_MIN
results.append(("mutation testing", ok, took, f"{killed}/{total} killed = {score:.1%}, floor {MUTATION_MIN:.0%}"))
total_s = sum(r[2] for r in results)
print(f"{'stage':<20}{'':<6}{'seconds':>8} detail")
for name, ok, took, note in results:
print(f"{name:<20}{'ok' if ok else 'FAIL':<6}{took:>8.1f} {note}")
in_budget = total_s <= BUDGET_S
print(f"{'total':<20}{'ok' if in_budget else 'FAIL':<6}{total_s:>8.1f} budget {BUDGET_S} s")
sys.exit(0 if all(r[1] for r in results) and in_budget else 1)
if __name__ == "__main__":
main().venv/bin/python scripts/gate.py
echo "exit $?"stage seconds detail
lint ok 0.0
tests + coverage ok 4.2 109 passed, coverage 89%
smoke test ok 0.8
mutation testing ok 1.9 80/82 killed = 97.6%, floor 95%
total ok 7.0 budget 120 sand exit 0. About 7 seconds against a budget of 120. Coverage is 89%: 100% for pricing.py, money.py, orders.py and payments_client.py, 83% for api.py (the browser test’s server runs in another process, so its lines are not counted) and 0% for legacy.py, which belongs to another project. I set the coverage floor at 85, four points under the measured number, so a new file with no tests trips it. Without Chromium the tests line reads 108 passed, 1 skipped and the gate fails on the skip.
Now defend the budget. 7 seconds is far under 120, and a CI runner is a different machine; this lab did not measure one, so assume yours is several times slower and keep a margin you can state. Write three sentences: what number you would alert on, what you would cut first if the suite doubled, and why a budget that is 17 times the measured time is still worth having. Hint for the last one: a budget is a trip wire for the day someone adds a test that waits.
11. Prove 0 flaky in 20 runs. Run the whole suite twenty times; pytest-randomly picks a new order each time, so this also checks that no test depends on another.
time (fails=0; for i in $(seq 1 20); do .venv/bin/pytest -q >/dev/null 2>&1 || fails=$((fails+1)); done; echo "failed runs: $fails of 20")failed runs: 0 of 20, in about 1 minute 14 seconds (real 1:13). Twenty clean runs of a fault that fails half the time would happen one time in a million, so this is real evidence and not luck.Undo the cure and see whether your loop notices. In tests/test_flaky_example.py add import time at the top and replace the line index.flush() with time.sleep(0.05). Then run only that file twenty times:
fails=0; for i in $(seq 1 20); do .venv/bin/pytest -q tests/test_flaky_example.py >/dev/null 2>&1 || fails=$((fails+1)); done; echo "failed runs: $fails of 20"It printed failed runs: 8 of 20 the first time and failed runs: 14 of 20 the second. A gate that ran the suite once would have passed it about one run in two. Put flush() back, then change MUTATION_MIN to 1.0 and run the gate: it fails on the two equivalent mutants. Say in a sentence why that failure is the gate being wrong, not your tests.
- DOC pytest-xdist documentation
Read the overview and the distribution page to see what `-n auto` does and what the plugin warns about, and check its known limitations before you turn it on. Skip remote execution over SSH.
- DOC pytest, Good Integration Practices
Test layout and import modes, the layout questions behind your `tests/` folders. Read the layout and import-mode sections; skip tox and setuptools.
- POST Vocke, The Practical Test Pyramid (martinfowler.com, 2018) Ham Vocke, 2018
The tiers of this suite, with unit, integration, contract, UI and end-to-end tests set out one by one. Read the contract tests and avoid-duplication sections against what you built; skip the Spring sample application.
All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.