The shape of a suite: pyramid, trophy and what fits your system
How many tests at which level is a cost decision: measure what each tier costs and what it touches, then choose the shape for this system
Each of the team's forty browser tests fails for no reason of its own, such as a slow render or a timing slip, one run in 200. Nothing in the code is wrong. About how often is the whole suite red?
A suite is a set of tests, and every test has a price: time to write, time to run, time to read when it fails, and a chance of failing for the wrong reason. Each test also buys something: it can fail when a specific kind of bug is present. The shape of a suite is the answer to one question, which is where those purchases are cheapest. The diagrams people draw (a pyramid, a trophy, a honeycomb) are answers other teams reached for their systems. Your job is to reach yours.
The pyramid, and why it is drawn that way
Martin Fowler’s note “TestPyramid” (1 May 2012) credits Mike Cohn, whose 2009 book Succeeding with Agile named the “Test Automation Pyramid”. The claim is that you should have many more low-level unit tests than high-level tests driven through the user interface. Fowler finds UI-driven tests “brittle, expensive to write, and time consuming to run”, and calls the high-level tests “a second line of test defense”. When one of them fails, you reproduce the bug in a unit test first.
Three levels give the usual picture.
| Level | What it exercises | Speed | If it fails |
|---|---|---|---|
| Unit | one function or class, usually with no I/O | microseconds to milliseconds | the line is nearby |
| Service or integration | a service with its real collaborators, such as a database or its API | tens of milliseconds to seconds | the bug is somewhere in this service |
| End to end | the whole stack, through the user interface | seconds to minutes | the bug is somewhere |
The shape follows the cost. A test that exercises more code is slower, depends on more things that can be flaky, and when it fails it narrows the search less. So you want the checks that can run low down to run low down. Ham Vocke’s “The Practical Test Pyramid” (martinfowler.com, February 2018) puts it as a rule: push tests as far down the pyramid as you can, and if a high-level test finds an error and no lower-level test fails, write the lower-level test too. He adds the other half: every test costs time to write, read, maintain and run, so a higher-level test should cover only what lower ones cannot, and a high-level test that duplicates lower coverage should be deleted. He warns against the sunk-cost fallacy here.
The inverted shape has a name, the ice-cream cone: many slow tests on top and a few unit tests underneath. Fowler describes how record-and-playback UI testing slides into it, and Vocke calls it hard to maintain and too slow to run. Lamine’s team is a cone.
What a unit test is allowed to touch
The pyramid is only useful if “unit” and “integration” mean something you can check. Software Engineering at Google (chapter 11, by Adam Bender) defines test size by resources, not by lines of code or scope. A small test runs in a single process and may not sleep, do I/O or make blocking calls. A medium test runs on one machine, so a real database file and local network calls are allowed. A large test may span machines. The same chapter says Google aims for roughly 80% narrow unit tests, 15% medium and 5% end to end, by count, and that each team’s mix will vary.
Size by resources is a better definition than size by scope, because you can enforce it. It gives you a rule you can put in a pyproject.toml: a test in the unit tier does no disk, no network and no threads. The lab does this with markers, in the next section’s lab. It also means the argument about whether a test is “really” a unit test (does it use two classes?) stops mattering. What matters is what it costs and what it needs.
The trophy and the honeycomb: the middle is where bugs live
Two newer shapes argue with the pyramid.
Kent C. Dodds’s “The Testing Trophy and Testing Classifications” (June 2021) has four layers: static checks at the base (types and a linter), then unit, then integration, then end to end. The slogan, which he credits to a tweet by Guillermo Rauch, is “Write tests. Not too many. Mostly integration.” His reasoning is a return on investment: confidence is the return, and time is the investment. Integration tests give more confidence per hour in a typical application, because most bugs are in how units fit together rather than inside one unit.
The Spotify post “Testing of Microservices” (André Schaffer, January 2018) draws a honeycomb, for services made of many small services. Its argument is that in microservices the complexity lies in the interactions between services, not inside each one. Many unit tests tie the suite to the internal structure, so a harmless refactor breaks tests. The post therefore puts most tests at what it calls integration tests: start a database, fill it, start the service and query its real API. It keeps implementation-detail tests for code with real internal complexity, and wants as few integrated tests as possible (tests that pass or fail depending on another system being correct). It admits the cost: tests that took milliseconds now take a few seconds, and failures point less precisely. It judges the trade worth it.
Notice the two words doing the work. For Dodds and for Schaffer, “integration” means real parts of your own service together, with the outside world replaced. Those are cheap enough to be the main course. The “end to end” and “integrated” tests they warn about are the ones that need other people’s systems, a real browser or a shared environment.
So the three diagrams are not three opinions about the same thing. They are the same cost model applied to systems where the price list is different. If your middle tier costs 20 milliseconds, the pyramid’s argument against it is weak. If it costs 40 seconds because it needs a database server and three other services, the pyramid’s argument is strong. You cannot choose well without the price list, and the lab builds it.
Reading the price list off the lab
labs/testing has four test folders. tests/unit/ holds 10 tests of pricing.py, money.py and nothing else. tests/integration/ holds 6: the API in-process with a stubbed provider, place_order on a real SQLite file, and the search index. tests/e2e/ holds one Playwright test of the checkout page. tests/extras/ holds 7 checks for the course add-ons (flags, migrations, the model). The other test, the flaky one, sits at the top of tests/.
Count them and time them. On the machine this chapter was written on, run per tier with the browser installed:
| Tier | Tests | Time per test | What it reaches |
|---|---|---|---|
| unit | 10 | under 1 ms | pricing.py 91% of its statements, money.py 100%, the rest almost nothing |
| integration | 6 | about 18 ms | api.py 72%, orders.py 88%, db.py 90%, inventory.py 79% |
| e2e | 1 | 1.1 to 1.8 s | the HTML page, through a real Chromium, with both servers started |
Three things in that table matter more than the numbers.
First, the cost ratios. An integration test here costs roughly twenty to a hundred times a unit test. A browser test costs roughly a hundred times an integration test. Those are the steps the pyramid is built on, and they are real in this lab, even though everything is small and local.
Second, the unit tier alone covers 24% of the checkout package. The integration tier alone covers 65%. That is not a quality score: Why we test showed how little a coverage number proves. It is a map. It says which tier touches which code. orders.py and api.py have 0% from unit tests, because they are glue: they call the database, the payment client and the clock. You cannot unit-test glue without replacing everything it glues, and Fakes, stubs and mocks is the chapter about what happens when you do.
Third, the checkout package is 770 lines, and the two pure modules, money.py and pricing.py, are 118 of them. About 15% of the code is pure rules. About 445 lines are api.py, orders.py, db.py, inventory.py and payments_client.py: glue. The rules are where boundaries live, and Choosing cases spent a chapter on them, so the pure part deserves a dense bottom: many cases per function, at the edges. The glue is where an idempotency key, a rollback and a stock count meet, and it deserves tests that run the real parts.
So for checkout the honest shape is neither diagram. It has a thick unit base on pricing.py and money.py, a thick middle on orders.py, api.py and db.py, and a very thin top: one browser test for the one flow worth the cost, add to cart, pay and see the confirmation. That is a trophy with a heavier base, or a pyramid with a fat middle. The name matters less than the reasons behind each tier.
Where the shape goes wrong
The cone. It grows because browser tests are the easiest to write when you do not know the code: you click what a user clicks. They pass on the first try, and the team feels covered. The costs arrive later. They are slow (so people batch pushes, as Running tests on every change described), they fail for reasons that are not the code (the arithmetic in the Predict above), and when one fails nobody knows which layer is at fault. Mike Wacker’s post on the Google Testing Blog, in the reading list, sets out the same three costs. The fix is not to delete them. It is to move each behaviour down to the lowest tier that can check it, and keep at the top only what needs a browser.
The hourglass. Many unit tests, many end-to-end tests, nothing in the middle. It happens when the code is hard to test without a full stack and easy to test as small pure functions. The glue is untested in isolation, so every glue bug is found by the slowest, vaguest test.
Counting by name. A team renames its tiers and calls a database-backed test a “unit test” because it sits in tests/unit. The labels stop describing cost. The fix is the Google rule: classify by what the test is allowed to touch, and make the rule something the runner enforces.
Counting tests, not behaviours. A shape is about where behaviours are checked, not how many functions have a test. One browser test that checks the whole checkout flow is cheap if it is the only place that flow is checked. Forty browser tests that each check a price rule are expensive and say little.
Treating the shape as a target. Google’s 80/15/5 is a mix they observe and aim for, and the chapter says teams’ mixes vary. A number copied to another system is a diagram, not an engineering decision.
Measuring your own shape
The pyramid is easy to draw and hard to check, so check it. Three measurements per tier are enough: number of tests, seconds per test, and the code that only this tier reaches. Add one more question for every test you write: could a lower tier check this? If a unit test can check that 1,000,000 kobo gets the 5% discount, a browser test of the same thing is waste.
To get the measurements, tests have to carry a label the runner understands. pytest calls it a marker. Register three markers, unit, integration and e2e, in pyproject.toml, and add --strict-markers to addopts so a typo such as @pytest.mark.unnit is an error at collection and not a test that silently belongs to no tier. Apply them from the folder a test lives in, with one hook in tests/conftest.py, so nobody has to remember a decorator. Then pytest -m unit is the fast loop, pytest -m "not e2e and not flaky" is the run for a machine with no browser, and a small script can print the shape.
Selecting by tier is a blunt form of test selection. Test selection shows the finer form: run the tests that depend on the change. It works best when the tiers are labelled, since selection can then trade tiers against changes, and the CI at scale chapter later in this course takes it further.
The QA track covers the same decision from the role’s side: the QA track chapter Testing philosophies (careers, QA) compares the pyramid, the trophy, exploratory and risk-based testing and who owns the choice. This chapter owns the craft, the measurement and the tiers in a real repository.
You will count and time the tests in each tier, register three markers so the runner knows the tiers, draw the shape, find out which tier reaches which code, and decide a shape for checkout/. Work from labs/testing with the venv from the README. The browser test starts both servers on ports 8094 and 8095; if something else holds them, set E2E_API_PORT and E2E_PROVIDER_PORT to other free ports.
1. Count the tests in each tier. Read the last line of each run.
cd labs/testing
.venv/bin/pytest --collect-only -q tests/unit | tail -1
.venv/bin/pytest --collect-only -q tests/integration | tail -1
.venv/bin/pytest --collect-only -q tests/e2e | tail -1
.venv/bin/pytest --collect-only -q tests/extras | tail -1
.venv/bin/pytest --collect-only -q | tail -110 tests collected, 6 tests collected, 1 test collected, 7 tests collected, then 24/25 tests collected (1 deselected) for the whole suite. Ten, six and one are your first picture: a pyramid by count. The deselected one is the quarantined flaky test (addopts = -m 'not flaky'). Seven tests are in tests/extras/, which check the course add-ons, and they belong to no tier yet. The times in each line differ on your machine.2. Time each tier. Run each folder with its slowest tests listed.
.venv/bin/pytest tests/unit -q --durations=3
.venv/bin/pytest tests/integration -q --durations=3
.venv/bin/pytest tests/e2e -q --durations=310 passed in 0.10s, and the durations are hidden because all are under 0.005 s. Integration: 6 passed in 0.36s, slowest 0.03s setup for an API test. Without Chromium the browser tier prints 1 skipped and SKIPPED ... Playwright Chromium not installed. With the browser installed and PLAYWRIGHT_BROWSERS_PATH set as in the README: 1 passed in 1.77s, with 0.55s setup, 0.48s call and 0.36s teardown. The one browser test costs more than the sixteen tests below it put together. Pytest’s own start-up is in the whole-run figures, which is why they overstate the unit tier; step 4 measures the tests alone.3. Register the tiers. Edit pyproject.toml. Add --strict-markers to addopts and two markers (e2e is already there):
[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "-ra --strict-markers -m 'not flaky' -p no:schemathesis"
markers = [
"flaky: deliberately flaky (sleep-based); quarantined from the default run, run with -m flaky",
"e2e: browser test; skipped unless Playwright's Chromium is installed",
"unit: pure code, no I/O, no threads",
"integration: real sqlite file, in-process API, threads; no browser",
]Then add this to the end of tests/conftest.py, which gives every test the marker of the folder it lives in:
TIERS = ("unit", "integration", "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)).venv/bin/pytest --markers | grep -E "unit|integration"
for m in unit integration e2e; do .venv/bin/pytest -m $m --collect-only -q | tail -1; done@pytest.mark.unit: pure code, no I/O, no threads and the integration line, then 10/25 tests collected (15 deselected), 6/25 tests collected (19 deselected) and 1/25 tests collected (24 deselected). They match the folder counts, so the markers agree with the folders. Ten plus six plus one is 17 of 25; the other eight are the seven extras and the flaky test. A marker scheme with unlabelled tests has a hole in its picture. Decide where those eight belong, or leave them out on purpose and say so.4. Run without the browser, and meet a gotcha. The obvious run for a machine with no browser is pytest -m "not e2e". Try it, and look at what it collects.
.venv/bin/pytest -m "not e2e" -q | tail -1
.venv/bin/pytest -m "not e2e" --collect-only -q | grep flaky24 passed, 1 deselected on a lucky run (the deselected test is the browser one; on an unlucky run it reads 1 failed, 23 passed, 1 deselected), and the second command prints tests/test_flaky_example.py::test_new_product_is_searchable_after_a_short_wait. A -m on the command line replaces the -m 'not flaky' in addopts, it does not add to it, so the quarantined flaky test now runs in the fast loop, and fails about one run in three. The expression you want is the whole condition:
.venv/bin/pytest -m "not e2e and not flaky" -q | tail -123 passed, 2 deselected in 0.6s (give or take): the 10 unit, 6 integration and 7 extras tests. A quarantine you can undo with a flag you typed for another reason is a leaky quarantine. Keep that expression: it is the run for any machine without a browser.
5. Draw the shape. Create scripts/shape.py, which runs each tier and prints its count and its test time, taken from pytest’s JUnit report so that start-up and collection are not counted:
"""Print the shape of the suite: tests and seconds per tier. Run from labs/testing."""
import subprocess
import sys
import tempfile
import xml.etree.ElementTree as ET
from pathlib import Path
def run(expr):
report = Path(tempfile.mkdtemp()) / "report.xml"
subprocess.run(
[sys.executable, "-m", "pytest", "-m", expr, "-q", "-p", "no:randomly", f"--junitxml={report}"],
capture_output=True,
)
cases = [c for c in ET.parse(report).iter("testcase") if c.find("skipped") is None]
# each testcase's time covers setup, call and teardown, not pytest's start-up
return len(cases), sum(float(c.get("time")) for c in cases)
rows = [
("unit", "unit"),
("integration", "integration"),
("e2e", "e2e"),
("untiered", "not unit and not integration and not e2e and not flaky"),
]
print(f"{'tier':<12}{'tests':>6}{'seconds':>9}{'ms/test':>9} shape")
for name, expr in rows:
n, secs = run(expr)
each = f"{1000 * secs / n:>9.1f}" if n else f"{'-':>9}"
print(f"{name:<12}{n:>6}{secs:>9.3f}{each} {'#' * n}").venv/bin/python scripts/shape.py10 tests with 0.000 seconds (each is under a millisecond, so the sum rounds to zero), integration 6 tests, about 0.11 to 0.13 seconds and 18 to 21 ms each, e2e 0 tests (skipped), and untiered 7. With the browser installed (and the ports free), the e2e row reads 1 test at about 1.1 to 1.8 seconds, 1125 to 1783 ms. A row of ten, six and one hash marks is a pyramid by count. Weigh each row by its time instead and it is the reverse: the one browser test costs more time than all the others. The count says the suite is a pyramid. The clock says where the time goes.6. See which tier reaches which code. Run coverage on each tier alone.
rm -f .coverage
.venv/bin/pytest tests/unit -q -p no:randomly --cov=checkout --cov-branch --cov-report=term | grep -E "orders|api|pricing|money|TOTAL"
rm -f .coverage
.venv/bin/pytest tests/integration -q -p no:randomly --cov=checkout --cov-branch --cov-report=term | grep -E "orders|api|pricing|money|TOTAL"checkout/api.py 0%, checkout/orders.py 0%, checkout/pricing.py 91%, checkout/money.py 100%, TOTAL 24%. Integration alone: api.py 72%, orders.py 88%, pricing.py 85%, money.py 75%, TOTAL 65%. Two things to read from this. The glue is reached only from the middle. And the middle tier also reaches 85% of pricing.py by running it as part of an order, but only for the few carts those six tests send, which is why the pricing rules still need their own dense unit tests. Reach is not strength.7. Argue a shape. Write six lines in a file of your own, shape-notes.md. Name what in checkout/ is pure (money.py, pricing.py) and what is glue (orders.py, api.py, db.py, inventory.py, payments_client.py). Say which tier should hold most new tests for each. Say what the single browser test is for, and what you would delete if there were forty. State whether a pyramid, a trophy or neither fits, and the cost number from step 5 that settles it.
pricing.py and money.py get many unit tests at their edges, because each costs under a millisecond and the boundaries are where bugs sit. Glue gets integration tests on a real SQLite file and the in-process API, at about 20 ms each, because a mock of the database cannot enforce a unique key or a transaction. The browser tier holds one test, the flow only a browser can check. Neither diagram fits as drawn: it is a trophy whose base is the pricing rules.@pytest.mark.unit on test_price_endpoint in tests/integration/test_api.py (it uses the API and a database file, so it is not a unit test) and run pytest -m unit --collect-only -q | tail -1, then scripts/shape.py. You see 11/25 tests collected and an eleventh test in the unit row, which now costs a few milliseconds instead of none. The tier labelled fast is no longer fast, and nothing failed. Markers are only as honest as whoever applies them. Remove the decorator, and think about what check you would add to catch it: a test that fails when any unit-marked test opens a file or a socket.Put the lab back. Later chapters start from the clean lab, so remove what you added: git checkout pyproject.toml tests/conftest.py, then rm -f scripts/shape.py shape-notes.md .coverage. pytest -q should again print 23 passed, 1 skipped, 1 deselected. The chapters after this one that want tier markers (the project) register them again, and say so.
Lamine's team at Ojaline has forty browser tests and six unit tests, a 31-minute build and red about one run in five with no code change. The team has one quarter, and cannot stop shipping. Where do they start?
- POST Just Say No to More End-to-End Tests Mike Wacker, 2015
Google Testing Blog, 22 April 2015. The argument that end-to-end tests are slow, flaky and expensive to debug, and that a team should keep the pyramid and limit browser tests to a few broad flows. Read it with the cone in mind: it is the case against the shape the cone grows into.
- POST TestPyramid Martin Fowler, 2012
The short original: the pyramid, the ice-cream cone it warns against and why UI tests are the expensive layer. Read it all; it takes two minutes.
- POST The Practical Test Pyramid Ham Vocke, 2018
A worked version with code: sociable against solitary unit tests, pushing tests down, and deleting duplicated tests. Read the sections on the pyramid and on what to test at each level; the code samples are Java and Spring, so skip those.
- POST The Testing Trophy and Testing Classifications Kent C. Dodds, 2021
The case for putting most tests in the middle, argued as return on investment, with the remark that the exact classification matters little. It scopes the trophy to monolithic front-end applications written in JavaScript, so take the reasoning and test it against `checkout/` yourself.
- POST Testing of Microservices Andre Schaffer, 2018
The honeycomb: integration tests of one service as the main course, with the cost admitted. Read the definitions of integrated, integration and implementation-detail tests; they are the clearest in the field.
- BOOK Software Engineering at Google, chapter 11: Testing Overview Adam Bender, 2020
Test size by resources, not scope, and the 80/15/5 mix as a measured aim. Read those two sections; the rest repeats ideas from earlier chapters here. Read: the sections on test size and on the test mix.
All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.