Lesson 11 of 28Working in real codebases
Testing on a Team
The team habits that keep a test suite trusted: tests in every PR, failing tests first for bugs, a flaky-test policy, honest coverage and mutation testing.
CI goes red on your PR. The failure is in a checkout test you did not touch, so you click "re-run". It goes green and you merge. Two other people did the same thing that week. A month later a customer is charged twice, and the root cause is the same race condition that test had been catching all along, a few percent of the time. Nobody broke the suite on purpose. The team just slowly stopped believing it. A test suite is only worth what the team trusts it to say, and that trust is built by habits, not by tools.
Norms that make a suite trustworthy
Testing Strategy covers what to test and at which level. On a team, the harder question is behaviour: what everybody agrees to do every day. Strong teams converge on a short list.
Tests ship in the same PR as the code. Not "a follow-up PR for tests". That follow-up loses to the next deadline nearly every time, and the reviewer has to approve code with nothing proving it works. If a change is hard to test, that is design feedback worth hearing now.
A bug fix starts with a failing test. Before you fix anything, write a test that reproduces the bug and watch it fail. This proves you understood the bug, proves the fix fixes it, and stops it coming back. A fix with a test that never failed may test nothing at all.
Reviewers read the tests first. Test names are the fastest summary of what a change is meant to do. If the tests do not tell you, the code probably will not either. Ask: "If I broke this code, would one of these tests fail?" A quick way to check is to break it on purpose locally.
Main is always green, and red main is everybody's problem. When main breaks, the first move is to revert the change that broke it, not to debug in place while ten people pull a broken branch. Fix it forward on a branch, calmly.
Nobody merges on red. Not "it is just the flaky one". The moment red becomes acceptable, real failures hide among the noise.
What a good test looks like in review
You will review far more tests than you write. These are the qualities to look for, and the comments to leave when they are missing.
Named after behaviour, not methods. test_calculate says nothing. test_refund_rejected_after_30_days is a sentence from the spec, and when it fails in CI, the name alone tells you what broke.
Arrange, act, assert. Set up the world, do one thing, check the result. When a test has several acts and asserts interleaved, it is really several tests, and the first failure hides the rest.
One reason to fail. A test that asserts on 14 fields of a response breaks whenever any of them changes, including ones it does not care about. Assert on what this test is about.
Deterministic. Same code, same result, every run, on every machine. No real clock, no unseeded randomness, no dependence on the order tests run in.
Independent. Each test sets up what it needs. It never relies on another test having run first, and it leaves nothing behind.
Fast. A unit test that takes 2 seconds is a bug. Slow suites get run less, and then they catch less.
Checks outcomes, not implementation. Asserting that a private helper was called three times locks the code's structure in place, so every refactor breaks tests that were not wrong. Assert on the result the caller sees.
# Hard to review: vague name, several behaviours, real clock, checks internals
def test_refund(mocker):
spy = mocker.spy(refunds, "_days_between")
r = refunds.request_refund(order_id=1)
assert r.ok
r2 = refunds.request_refund(order_id=2)
assert not r2.ok
assert spy.call_count == 2
# Easy to review: one behaviour each, fixed time, checks what the user sees
def test_refund_allowed_within_30_days(make_order):
order = make_order(delivered_at=date(2026, 3, 1))
result = request_refund(order, today=date(2026, 3, 31))
assert result.ok
def test_refund_rejected_after_30_days(make_order):
order = make_order(delivered_at=date(2026, 3, 1))
result = request_refund(order, today=date(2026, 4, 1))
assert result.reason == "outside_refund_window"The second version tests the boundary on both sides, which is where date bugs live, and it will still pass after someone rewrites _days_between entirely.
Flaky tests: how trust dies
A flaky test passes and fails on the same code. It is the single biggest threat to a suite, because it teaches people that red means nothing. Once that lesson is learned, a real failure gets the same "re-run" click as the fake ones.
The causes are a short, well-known list:
- Time. Tests that read the real clock break at midnight, at month-end, on the day the clocks change, or when CI runs in a different time zone from your laptop.
- Order and shared state. A test passes only because another test ran first and left data behind, or fails because one did.
- Async waits.
sleep(1)and then check. On a busy CI runner, one second is sometimes not enough. - Network and real services. A third-party sandbox that is slow or down for five minutes.
- Randomness. Random test data without a fixed seed that occasionally produces an edge case.
- Concurrency. Two tests sharing a port, a temp file or a database row, run in parallel.
- Real bugs. Sometimes the test is right and the code has a race. This is the case that "retry until green" hides.
Order dependence is the hardest to spot by eye. Each test below looks fine. Run the suite in file order and in a few shuffled orders, the way a plugin like pytest-randomly does.
Press Run (⌘ Enter) to see what happens.In file order everything passes, because test_total_qty happens to clean up between the other two. Shuffle the order and different tests fail on different runs. Neither failing test is wrong on its own; they share state. The fix is for every test to start from a clean cart, for example with a fixture.
The last three lines are the real lesson. Flakiness compounds. One test that fails 2% of the time is a nuisance. Twenty of them, and a third of all CI runs are red for no reason, which is exactly the point where people stop reading failures.
What does this print?
# 100 tests, each independently flaky 1% of the time print(round(0.99 ** 100, 2))
Match each symptom to its most likely cause.
Quarantine, then fix
Every team gets flaky tests. What separates healthy teams is a written policy, so nobody has to decide what to do at 6 p.m. on a Friday.
Detect
Make flakiness visible
CI records tests that failed and then passed on a retry as **flaky**, not as passed. Playwright's reporter does this out of the box; for pytest, track rerun results in your CI's test analytics.
Quarantine
Take it out of the merge path
Mark the test so it still runs but cannot block merges. Open a ticket with the failure logs and an owner, usually the team that owns the code under test.
Fix
Find the cause, with a deadline
Reproduce it by running it many times or in random order. Fix the test or the race in the code. A quarantine with no deadline is a slow delete.
Return or delete
Close the loop
Put the fixed test back in the gate. If nobody can fix it within the agreed time, delete it and accept the coverage gap honestly instead of keeping a test nobody believes.
Reproducing a flake is the hard part, so use the tools that make rare things common. pytest-repeat runs a test many times (--count=200). pytest-randomly shuffles test order and prints the seed, so you can replay the exact order that failed. Jest and Vitest both have options to shuffle tests too. Check each tool's docs for the current flags.
Why "retry until green" is a trap. Automatic retries (pytest-rerunfailures, Playwright's retries) are fine as a detection tool: the test failed, passed on retry, and got flagged. They are harmful as a policy, where retries silently turn red into green and nobody looks. Some of those flakes are real race conditions that customers hit too. Retries hide them, and the suite gets slower and less trusted at the same time.
A checkout test fails about 1 run in 30. Put your response in order.
- Tap the steps below in the right order.
Coverage is a signal, not a target
Goodhart's law: when a measure becomes a target, it stops being a good measure. Mandate 90% coverage and people will write tests that execute code without checking anything. A test that calls every function and asserts nothing gets full marks.
Used as a signal, coverage is useful:
- Uncovered lines are a reading list. An untested
exceptblock orelsebranch is a question for the author: is this path reachable, and what should happen? pytest in Depth shows how to turn on branch coverage, which catches theifwhose other side never ran. - Diff coverage beats total coverage. A rule like "90% total" punishes whoever touches the old untested module. A rule like "the lines this PR changed must be covered" is fair to everyone and ratchets the codebase upward over time. Codecov calls this patch coverage, and
diff-coverdoes it for any coverage report. - A sudden drop is a review prompt, not an automatic failure. Deleting well-tested dead code also lowers the percentage.
What coverage can never tell you is whether a test would notice a bug. For that you need a different tool.
Mutation testing: tests for your tests
Mutation testing makes small changes to your code (a mutant): >= becomes >, and becomes or, a constant shifts by one. Then it runs your tests against each mutant. If a test fails, the mutant is killed, which is good. If every test still passes, the mutant survived: you have found behaviour your suite does not actually check.
Here is a tiny mutation tester. Both suites below cover every line of shipping_fee. Run it.
Press Run (⌘ Enter) to see what happens.The weak suite has perfect line coverage and still lets two boundary bugs through. A customer spending exactly 50.00 would pay shipping, and no test would notice. Two extra asserts, one each side of the boundary, kill every mutant.
Real tools do this across a codebase: mutmut for Python, Stryker for JavaScript and TypeScript (and C#), PIT for Java. They are slow, because they run the suite once per mutant. Teams run them on the files a PR changed, or nightly on critical modules like billing and permissions, and read the survivors as a list of missing tests. Do not chase a 100% mutation score; some mutants are equivalent to the original and can never be killed.
Test data that does not rot
Test data is where suites quietly become unmaintainable.
Shared fixtures (one big sample_customer used by 80 tests) look efficient. Then someone changes the customer's country for a new test, and 12 unrelated tests break. Each test was silently depending on details it never mentioned.
Factories fix this. A factory builds a valid object with sensible defaults, and each test overrides only the fields it cares about: make_order(delivered_at=date(2026, 3, 1)). The test now states exactly what matters to it, and the rest can change freely. In Python, factory_boy or a plain function both work.
For anything touching a database, prefer the real database over a mock, started in a container for the test run. Testing with Real Databases covers that setup in depth; the team-level point is that "works against the mock" has caused enough outages that most backend teams now default to real dependencies in integration tests.
Beyond one service
Some failures only exist between systems, or only in production.
- Contract tests check that two services agree on an API without running both together. Contract Tests and Architecture Tests covers consumer-driven contracts with Pact.
- End-to-end smoke tests cover the few journeys that must never break: sign up, log in, pay. Keep them few. Run them with Playwright against every deploy, and treat a failure as a reason to roll back.
- Testing in production is not a joke when done deliberately. Synthetic checks run a scripted journey against production every few minutes and alert when it fails. Canary releases send a small slice of traffic to a new version and compare its error rate with the old one. Feature flags let you turn on code for internal users first. These catch what no pre-production environment can: real data, real load, real third parties.
TDD on a real team
Test-driven development means writing a failing test, writing just enough code to pass it, then refactoring, in short cycles. Interviewers ask about it, and the honest answer is more useful than a slogan.
TDD shines when the behaviour is clear and the logic is dense: pricing rules, parsers, permission checks, date calculations, state machines. It is close to mandatory for bug fixes, where the failing test is the reproduction. It also pushes you toward small, injectable functions, which are easier to test anyway.
Teams usually skip strict TDD when they do not yet know what they are building: a spike, an exploratory UI, glue code that mostly calls a framework. There, writing tests after the shape settles is reasonable. What matters is not the order you wrote them in, but that the PR arrives with tests that would fail if the code were wrong.
>= to > in a discount check survives. What does that tell you?- regression test
- A test written to reproduce a bug before it is fixed, so the bug cannot quietly return.
- flaky test
- A test that passes and fails on the same code, usually because of time, shared state, waits, networks or races.
- quarantine
- Taking a flaky test out of the merge gate while it still runs and has an owner and a deadline to fix it.
- diff coverage
- Coverage measured only on the lines a pull request changed, also called patch coverage.
- mutation testing
- Changing the code in small ways and checking that the tests fail. A surviving mutant marks behaviour no test checks.
- factory
- A helper that builds valid test objects with defaults, so each test overrides only the fields it cares about.
- synthetic check
- A scripted user journey run against production on a schedule, alerting when it fails.