Running tests on every change
A test nobody runs proves nothing: put the fast tests before the push, the full suite on every merge, and the slow ones overnight
A pipeline has three jobs: lint, unit, and integration. Integration is configured with needs: unit. A commit breaks one unit test and also one integration test. What does the pipeline report?
A test suite is a promise: if this passes, the change is safe to ship. The promise is only kept when the suite runs on the change. A test that runs when somebody remembers is a test that does not run on the Friday it matters. So the question this chapter answers is where the tests run, how quickly, and what happens when they fail.
The rule: integrate often, test every integration
Martin Fowler’s description of continuous integration (revised January 2024) has a few plain rules. Each member of a team merges their changes into the shared line of code at least daily. Each integration is checked by an automated build that includes tests, which he calls a self-testing build. If the build fails, it is fixed right away, and usually the quickest fix is to revert the commit that broke it. The build is fast: he cites the XP guideline of ten minutes as reasonable for most projects.
Look at what Tallowmere had. It integrated, since people merged. It had tests. What it lacked was the word “automated” in the middle: the build was whoever’s laptop and whichever file they chose to run. A change that has been tested by its author’s choice of tests has been tested against the author’s assumptions, which are the same assumptions that produced the bug.
Two rules pull against each other. Running more tests catches more. Running more tests takes longer, and a slow check teaches people to batch their work, skip the check, or stop looking at it. A team that pushes once a day because the pipeline takes 40 minutes has traded away the frequent integration the pipeline was meant to enable.
Rings of feedback
The way out is not one run but several, each wider and slower than the one before. Software Engineering at Google (chapter 23) describes the same shape: the local edit-compile-debug loop, presubmit, post-submit, then staging and production. Presubmit holds “only fast, reliable” tests, and the slow or less reliable ones run after. For a nine-person team the rings are smaller and cheaper, but the logic is the same.
| Ring | When it runs | Budget | What runs | What it stops |
|---|---|---|---|---|
| Editor or watch | on save | seconds | the one test you are working on | a typo before it is a commit |
| Pre-push | on git push, on your laptop |
under 30 s | the unit tier, stop at first failure | a broken push to a shared branch |
| Pipeline on push | every push and pull request, on a server | a few minutes | lint, unit, integration, smoke | a merge that breaks main |
| Main after merge | every merge | the longest you can bear, ideally under 10 min | the full suite | what selection or a stale branch missed |
| Nightly | on a schedule | an hour is fine | mutation, soak, the slow checks | slow decay, with a day’s notice |
Budgets are ceilings, not targets. The lab’s whole unit tier runs in 0.4 seconds, so the 30-second pre-push budget is wide open. It will not stay that way. Suites grow, and the budget is how you notice.
Each ring catches what the previous ring is too cheap to catch, so no ring replaces another. The hook is fast because it is local and skippable. The pipeline is authoritative because it is on a machine nobody types into and no flag skips it.
How a pipeline decides
Every CI system, GitHub Actions or GitLab or a shell script on a cron, uses the same mechanism: a command exits with a number. Zero means success. Anything else means failure. The pipeline reads the number and nothing else. It does not read your test output, so a test runner that prints FAILED and exits 0 produces a green build.
Read the example pipeline in the lab, ci/github-actions.yml. It is not active in this repository; it is what you would copy to .github/workflows/ci.yml in your own project. Four things in it carry most of the ideas.
Triggers. The on: block runs the workflow on push, on pull_request, and on a schedule with a cron expression. GitHub documents that scheduled workflows run in UTC by default, so 0 2 * * * is 03:00 in Lagos. One gotcha: with both push and pull_request listed, a push to a branch that has an open pull request starts two runs. Teams usually restrict push to main, or accept the double run.
Jobs and needs. Jobs run in parallel unless you sequence them. integration says needs: unit, so it starts only after unit passes. That is the behaviour you predicted: fail early on the cheap job, skip the expensive one. The trade is the hidden second failure.
Conditions. The mutation job has if: github.event_name == 'schedule', so it runs overnight and never on a push. A job whose condition is false is marked skipped, not failed. Mutation testing is slow (a later chapter measures it) and belongs in the nightly ring.
Gates. Two lines are gates: --cov-fail-under=60 and ruff check. A gate is a check that turns a measurement into a pass or a fail. Gates are where pipelines go wrong, and the next section shows how.
A pipeline you have not run is a guess
The lab pipeline was run by hand on the clean code before this chapter was written, and two of its lines are there because the first version went red. Both are worth knowing, because both will happen to you.
First, lint. The pipeline installs ruff from requirements.txt, where it is pinned (ruff==0.14.14), and pyproject.toml names the rules (E4, E7, E9 and F: syntax errors, undefined names, unused imports). The first version said pip install ruff with nothing else. On 2026-11-23 the newest release, ruff 0.17.6, run with no configuration, reports 110 errors on the clean lab, almost all style rules (old-style Dict and List annotations, import order). Ruff 0.14.14 on the same command reports 0. The code did not change. The tool’s default rule set did. A pipeline that installs the latest of any tool can go red with no commit at all, and the person who gets blamed is whoever pushed next. Pinning has two halves: the version, so the tool is the same tomorrow, and the rule set, so you decide what counts as an error. You then upgrade on purpose, in a commit of its own, and fix what the new rules find.
Second, the gate. Unit tests alone cover 24% of the checkout package (442 statements, 332 missed). Unit and integration together reach 66%. The first version demanded 70% from the unit job: it failed on its first run, for a reason that had nothing to do with the code’s quality. The job measured a tier that was never going to earn that number. The fix has two parts. The gate runs in the job that has all the tests that earn it, so it says which tests it measures: unit plus integration. And the number is set from a measurement, a few points below it: 60 against 66, so the gate stops the figure falling and does not demand a jump. A gate of 60 that ran on the unit tier alone would still fail, and one set at 66 would fail on the first untested line of a new feature. Coverage as a target gets a chapter of its own, and Why we test has already shown how little a high number can mean; here it is an example of a gate that has to be set by looking.
The shape is the same in both. Someone writes a number or a rule into a file and does not run it. The cost is not the red build. The cost is what the team learns from it: that red is normal, that you re-run and wait, and that a failure may be the pipeline’s fault. A pipeline people distrust is worse than none, because it still takes their time. The lab pipeline is green now. You will still break each line on purpose, because a gate you have never seen fail is a gate you have not tested.
Fast feedback on your own machine
The pipeline is for the team. Your own loop is the tests you run while you work, and its cost is whether you run them at all. pytest has options that make a failing run cheap to repeat.
-xstops at the first failure. Use it when the first failure is probably the cause of the rest.--lf(--last-failed) runs only the tests that failed last time. pytest keeps that list in.pytest_cache. When nothing failed last time,--lfruns everything by default, which is what you want and surprises people the first time.--ff(--failed-first) runs last time’s failures first, then the rest. You get the news early and still get the full run.--sw(--stepwise) stops at the first failure and resumes from it next time.-n auto(pytest-xdist) spreads tests over your CPU cores. It has a start-up cost, and the lab measures it: ten unit tests take 0.4 seconds in one process and about 1.7 seconds with-n auto. Parallelism pays when the tests take longer than the start-up. Below that it makes the suite slower.
One more detail. The lab’s pytest-randomly shuffles test order on every run, so “first failure” is a different test each time. That is a feature: a test that passes only in one order depends on another. It also means -x and --lf are the tools you reach for after the shuffle, not instead of it.
What the hook can and cannot do
A git hook is a script git runs at a point in its workflow. A pre-push hook runs before git push sends anything, and a non-zero exit cancels the push. It is the cheapest way to stop the Friday push: no server, nothing to configure on the team’s side.
Its limits are the reason the pipeline exists. A hook lives in one clone, so every new laptop starts without it. It runs against your environment, with your packages and your files, which is not where the code will run. And git push --no-verify skips it, on purpose, because sometimes you must. A rule you can skip is advice. The rule that cannot be skipped is a required check on the shared branch: the host refuses a merge until the pipeline is green. Turn that on once the pipeline is trustworthy, not before, or the team’s first experience of the rule is being blocked by a gate that fails for no reason.
Which tests, when
You cannot run everything everywhere. Choosing is a trade between how fast you learn and how sure you are. The simple choice is by tier: unit on the hook, unit and integration on push, everything on main. The cleverer one is by change: run only the tests that can be affected by what you touched. The simulation below shows why the clever one is harder than it looks.
// CI: only the tests next to the files that changed
const tests = changedFiles.flatMap((f) => testsByFile[f] || []);
// util.js changed -> util.test runs. billing.test never does.// CI: every test that depends on a change, directly or not
const affected = reverseClosure(changedFiles, importGraph); // visited set: cycles terminate
const tests = [...affected].flatMap((f) => testsByFile[f] || []);
// a file the graph does not know (package.json, CI config) -> run everything
// and a full run on merge, so a hole in the graph is caught on main, not in production Watch what happens when you change a file that many others import. A rule of “run the tests next to the changed file” misses every dependent. Walking the import graph backwards finds them, and a change to a build or config file selects everything. The same sim also shows why a full run on main is not optional: selection is a model of what depends on what, and the model has holes. A later chapter, CI at scale, takes selection further. For a team of nine the tier choice is enough, and the full suite on every merge is how you catch what it misses.
When the build goes red
Three habits keep a pipeline worth having.
Treat a red main as the most urgent work. Fowler’s advice is to fix a broken build right away and, usually, to revert. The reason is arithmetic: while main is red, every merge on top of it is untested against a known-bad base, and nobody can tell whose change broke what. A revert takes two minutes and restores the base. The fix can be written calmly afterwards.
Never normalise a flaky test. A test that fails one run in three teaches everyone to press re-run. Then a real failure arrives and gets re-run too. Software Engineering at Google says flakiness erodes confidence and makes it harder to find the guilty change. The remedy it describes is to take a flaky test out of the blocking run while someone investigates, with a bug filed against it. The lab does this already: tests/test_flaky_example.py carries a flaky marker, and addopts = -m 'not flaky' in pyproject.toml keeps it out of the default run. Quarantine is a stop-gap with an owner and a date, never a place to leave a test.
Make the failure readable. A red build whose output is two thousand lines costs more than one that names the test and the assertion. pytest’s short summary line, FAILED tests/unit/test_money.py::test_vat_on_a_round_amount - assert 75000 == 75001, is already most of a bug report. Keep it near the top of what the pipeline shows.
You will read the example pipeline, run its jobs one by one, make each of its two gates fail on purpose to see why it is written as it is, run the jobs from a script of your own, and write a pre-push hook that keeps the fast tier under 30 seconds. Work from labs/testing with the venv from the README. The example pipeline stays as it is; your additions are two new files, scripts/ci_local.sh and scripts/pre-push.sh.
1. Read the pipeline before you run it.
cd labs/testing
cat ci/github-actions.ymlAnswer four questions from the file, on paper: which jobs run on a push, which run overnight, which job waits for which, and which lines are gates (a number or a rule that can fail the job).
lint, unit, integration and mutation. lint and unit have no needs, so they start together. integration has needs: unit. mutation has if: github.event_name == 'schedule', so it runs only from the nightly cron (0 2 * * *, UTC). The gates are ruff check, --cov-fail-under=60 on the integration job (it runs tests/unit and tests/integration together), and the smoke test at the end of integration, which exits non-zero when any of its checks fails.2. Run lint as written, then see why it is pinned. The pipeline runs ruff from requirements.txt, and your venv already has the pinned version.
.venv/bin/ruff --version
.venv/bin/ruff check checkout fake_provider tests
echo "exit code: $?"ruff 0.14.14, then All checks passed! and exit code 0. Now install the newest ruff over it and run with no configuration (--isolated ignores pyproject.toml, which is what an unpinned install with no rule set looks like):
.venv/bin/pip install ruff==0.17.6
.venv/bin/ruff check --isolated checkout fake_provider tests | tail -3You see Found 110 errors. and [*] 90 fixable with --fix. Do not run --fix: the rules reporting are style rules the code was never written against. Run .venv/bin/ruff check checkout fake_provider tests once more, without --isolated: with the rule set named in pyproject.toml, even ruff 0.17.6 passes. Put the pin back before you go on:
.venv/bin/pip install -r requirements.txt
.venv/bin/ruff --versionThe version line reads ruff 0.14.14 again.
3. Run the coverage gate on the wrong job, then the right one. Run the gate against the unit tier alone, as an earlier version of the pipeline did:
.venv/bin/pytest tests/unit -q -n auto --cov=checkout --cov-branch --cov-fail-under=60 > coverage.log
echo "exit code: $?"
tail -4 coverage.log(The output goes to a file so that $? is the exit code of pytest itself, in any shell. Delete coverage.log and .coverage afterwards.)
The last lines are TOTAL 442 332 66 3 24%, then FAIL Required test coverage of 60% not reached. Total coverage: 23.82%, then 10 passed and exit code 1. Ten tests pass and the job is red because of the gate. Now run the gate as the pipeline does, over both tiers:
.venv/bin/pytest tests/unit tests/integration -q -n auto --cov=checkout --cov-branch --cov-fail-under=60 | tail -4The table’s last row reads TOTAL 442 138 66 9 66%, followed by Required test coverage of 60% reached. Total coverage: 66.34% and 16 passed. Sixty sits under the 66.34 it has to protect, with a little room.
Now write your own runner for the jobs. Create scripts/ci_local.sh:
#!/bin/bash
# The example pipeline's jobs, in order, on this machine. From labs/testing:
# ./scripts/ci_local.sh
set -eu
cd "$(dirname "$0")/.."
TIMEFORMAT=' took %Rs'
rm -f .coverage
echo "== lint"
time .venv/bin/ruff check checkout fake_provider tests
echo "== unit"
time .venv/bin/pytest tests/unit -q
echo "== integration, and the coverage gate over both tiers"
time .venv/bin/pytest tests/unit tests/integration -q -n auto --cov=checkout --cov-branch --cov-fail-under=60
echo "== smoke"
time .venv/bin/python scripts/smoke_test.py
echo "ALL JOBS PASSED"chmod +x scripts/ci_local.sh
./scripts/ci_local.sh
echo "exit code: $?"took 0.01s (ruff is very fast, and it caches), unit took 0.4s, the integration job took 2.7s and carries the gate (Required test coverage of 60% reached. Total coverage: 66.34%), smoke took 0.8s to 1.1s, then ALL JOBS PASSED and exit code 0. The integration job runs the unit tests again so that the gate sees both tiers; in a bigger suite you would upload each job’s coverage data and combine it instead. The whole pipeline is about 4 seconds here. Your numbers will differ; the order of magnitude will not.4. Read an exit code. scripts/check.sh is the lab’s own gate: the suite, then the smoke test.
./scripts/check.sh; echo "exit code: $?"The last lines are 23 passed, 1 skipped, 1 deselected, the smoke test’s ok lines, ALL CHECKS PASSED, and exit code: 0 after about 2 seconds. Now break a unit test and run it again:
perl -pi -e 's/== 75_000/== 75_001/' tests/unit/test_money.py
./scripts/check.sh; echo "exit code: $?"pytest prints FAILED tests/unit/test_money.py::test_vat_on_a_round_amount - assert 75000 ==... (the summary line is cut to the terminal width), then 1 failed, 22 passed, 1 skipped, 1 deselected, and exit code: 1. The smoke test never ran: check.sh starts with set -eu, so the first non-zero exit ends the script. That is fail-fast, and it is the same as integration skipped behind a failed unit. Leave the test broken for the next step.
5. Get fast feedback. Break a second test, so there are two failures to tell apart:
perl -pi -e 's/delivery_fee\(3\) == 150_000/delivery_fee(3) == 150_001/' tests/unit/test_pricing.py
.venv/bin/pytest tests/unit -q | tail -4
.venv/bin/pytest tests/unit -q -x | tail -3The first run ends 2 failed, 8 passed, naming both tests. The second stops at the first failure it meets: stopping after 1 failures and 1 failed. Because pytest-randomly shuffles the order, which of the two it stops at changes between runs. Run it a few times. Now fix the money test, and re-run only what failed:
perl -pi -e 's/== 75_001/== 75_000/' tests/unit/test_money.py
.venv/bin/pytest tests/unit -q --lf | tail -3--lf runs the two tests that failed last time: 1 failed, 1 passed. Fix the other test and run --lf again: 1 passed. Run it a third time, with nothing failing last time, and it runs all ten: 10 passed. Then .venv/bin/pytest tests/unit --ff lists the previous failures at the top of the run, and the rest follow.
Restore both files with git checkout tests/unit/test_money.py tests/unit/test_pricing.py if you have not already. Then measure the cost of parallelism:
time .venv/bin/pytest tests/unit -q
time .venv/bin/pytest tests/unit -q -n auto10 passed in 0.09s and about 0.4 seconds of wall-clock time for the first. 10 passed in 1.4s and about 1.7 seconds for the second. The workers take about a second to start, which is more than the tests cost. Do not add -n auto to a suite that is this small; the example pipeline does, and it makes the unit job slower, not faster.6. Write a pre-push hook. Create scripts/pre-push.sh:
#!/bin/sh
# Run the fast tier before a push. Budget: 30 seconds.
# Try it by hand first: sh scripts/pre-push.sh
set -eu
cd "$(dirname "$0")/.."
BUDGET_S=30
start=$(date +%s)
.venv/bin/pytest tests/unit -q -x -p no:randomly
elapsed=$(( $(date +%s) - start ))
echo "pre-push: unit tier passed in ${elapsed}s (budget ${BUDGET_S}s)"
if [ "$elapsed" -gt "$BUDGET_S" ]; then
echo "pre-push: over budget. Move the slow tests out of tests/unit." >&2
fiThe script warns when it is slow and does not fail. A hook that blocks a push for being slow trains people to use --no-verify. Run it by hand first. It is a file in the repository and does nothing until you install it.
sh scripts/pre-push.sh; echo "exit code: $?"10 passed, then pre-push: unit tier passed in 0s (budget 30s) (or 1s), and exit code 0.Installing it changes the git hooks of your clone, and every git push from that clone, in any folder of it, will run it. Install it only if you are happy with that; the removal command is the last line below.
printf '#!/bin/sh\nexec sh "%s/scripts/pre-push.sh"\n' "$PWD" > "$(git rev-parse --git-path hooks/pre-push)"
chmod +x "$(git rev-parse --git-path hooks/pre-push)"To see it work without a real push, make a scratch remote and break a test:
git init --bare /tmp/lab-remote.git
git remote add scratch /tmp/lab-remote.git
git push scratch HEADThe tests pass and the push goes through: * [new branch] ... -> .... Now break the VAT test, commit it, and push again:
perl -pi -e 's/== 75_000/== 75_001/' tests/unit/test_money.py
git commit -am "break vat on purpose"
git push scratch HEADYou see 1 failed (the hook stops at the first failure and runs the tests in file order, so the VAT test in test_money.py is the first to run) and error: failed to push some refs. Nothing reached the remote. Undo the commit with git reset --hard HEAD~1, and remove everything this step made:
rm "$(git rev-parse --git-path hooks/pre-push)"
git remote remove scratch
rm -rf /tmp/lab-remote.gitgit push –no-verify scratch HEAD. The broken commit goes through; the hook never ran. That is why the pipeline, not the hook, is the rule. Then make the hook slow on purpose: add import time; time.sleep(31) as the first line of a unit test, run sh scripts/pre-push.sh, and read the over-budget warning. Decide what you would do about it. Moving the slow test to tests/integration is the answer the lab was built around. Remove the hook, the remote and the sleep when you are done.Tallowmere now has a pipeline, and it runs the entire suite on every push: lint, unit, integration, browser tests and the smoke checks. It takes 14 minutes. The nine engineers have started to push in batches, two or three changes at once, so they wait less often, and main has gone red twice this month with nobody sure whose change did it. What do you change?
- POST Continuous Integration Martin Fowler, 2024
The definitive description of the practice: daily integration, a self-testing build, fixing red at once, the ten-minute build and staged builds. Read the sections on the self-testing build and on keeping the build fast; skim the rest on first pass.
- BOOK Software Engineering at Google, chapter 23: Continuous Integration Rachel Tannenbaum, 2020
Shows the rings of feedback at a scale where they are forced on you, with the reasoning for putting only fast, reliable tests on presubmit. Skip the Takeout case study on a first read. Read: the sections Fast Feedback Loops, Presubmit versus Post-submit, Why presubmit isn't enough, Presubmit optimization and CI Challenges.
- DOC Workflow syntax for GitHub Actions
The reference for everything in the example pipeline: on, schedule (UTC by default), jobs.<job_id>.needs and jobs.<job_id>.if. Read those four entries; the page is long and the rest is lookup. Read 2026-11-23.
- DOC How to re-run failed tests and maintain state between test runs
The official account of --lf, --ff, --sw, --nf and the .pytest_cache folder. Short and complete; read all of it and keep it open the first week.
- BOOK Continuous Delivery Jez Humble and David Farley, 2010
The book behind the staged pipeline. Chapter 5 is the reasoning for splitting a build into stages that run faster first. Skip the tooling details, which have dated; the principles have not. Read: chapter 5 (the deployment pipeline) and chapter 3 (continuous integration).
All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.