Quality metrics that mean something
A metric is a question with a definition, a source, a decision it informs and a list of uses it must never get. Compute coverage, mutation score, flake rate, escape rate and time to green on the lab, then watch each one break when someone sets it as a target
Ojaline sets a target of zero flaky tests, counted as the number of tests carrying a flaky label in the tracker. A team lead has two weeks and 14 flaky tests. Which outcome is most likely?
Earlier chapters gave you the instruments. You can measure coverage and mutation score and the flake rate, and you know what running tests on every change costs in minutes. This chapter is about what to do with the numbers once you have them: which ones to put in front of whom, how each is defined so two people compute the same value, and how each goes wrong. You work on the lab’s own data and on a CSV of 60 synthetic CI runs that you generate with a short script.
A metric is a question with a definition
Before a number goes on a dashboard, write down five things about it.
The question. “Are customers meeting bugs we could have caught?” is a question. “Escape rate” is a label for its answer. If you cannot write the question, you cannot tell whether the number answers it.
The definition. Numerator, denominator, period, and what is included and excluded, in words a sceptic could recompute. Two teams that both report an “escape rate” with different definitions produce numbers that look comparable and are not.
The source. The system and field the data comes from. A number whose source is a spreadsheet one person keeps dies when that person goes on leave.
The decision. What someone does differently when the number moves. If the answer is “nothing”, the number is decoration.
What it must never be used for. This is the part most dashboards omit. Every metric has a use that destroys it, and it is cheaper to write that down before the number has a target on it.
The QA career track’s chapter, Quality metrics that are not lies, develops the same model for a quality lead and adds the DORA metrics and the data hygiene a dashboard needs. This chapter is the craft underneath it: you compute the numbers yourself, so you know what each one can and cannot show.
Metrics fall into three kinds, and the kind decides who should see them:
| Kind | Examples in this chapter | Answers | Dangerous as |
|---|---|---|---|
| Outcome | Escape rate | Are customers better off? | A target tied to individuals or pay |
| Signal health | Flake rate, time to green | Can we trust and afford our evidence? | A comparison between teams with different suites |
| Activity | Line and branch coverage, test count, mutation score | Where are the gaps? | Almost anything other than a map for the people doing the work |
Outcome metrics go to the people who ask whether quality is improving. Signal-health metrics go to the engineers who run the pipeline. Activity metrics go to the people writing tests, as a map. Pavel’s two targets are an activity metric and a signal-health metric, and he has made both an outcome. That mismatch is the root of the problem.
Coverage and mutation score: what they are for
You measured both in the earlier chapter: checkout/pricing.py has 92% combined line and branch coverage and a mutation score of 28 of 68, which is 41%. Take the two as metrics.
Coverage. Question: which code has no test that runs it? Definition: statements executed under the test run divided by statements in the file, and, with branch coverage on, the share of decision exits taken. Source: coverage.py through pytest-cov. Decision: where to look for missing tests, and whether a change arrived with none. It must never be used as a target, because the tool does not see assertions, or as evidence that code is safe.
Mutation score. Question: where do the tests that ran say nothing? Definition: mutants killed divided by mutants made, for named files. Source: scripts/mutate.py run. Decision: which rules need stronger assertions this sprint. It must never be a merge gate before the team has seen a month of its noise (equivalent mutants, machine-dependent ones), and it cannot be compared across files with different amounts of dead code.
Neither number is wrong. Google’s engineers, in the paper on code coverage at Google, describe using coverage on the changeset in code review, where it shows a reviewer which changed lines no test ran, and their testing blog gives 60%, 75% and 90% as guidelines, not mandates. That is the useful job. Fowler puts it in one line: coverage is a useful tool for finding untested parts of a codebase, and a poor measure of how good the tests are. Inozemtseva and Holmes (2014) looked at this directly: once the size of a suite is accounted for, coverage on its own had only a low to moderate correlation with how many faults the suite found.
// Every line runs, so coverage says 100%. Nothing checks the answer.
test('shippingFee runs', () => {
expect(shippingFee(1000, false)).toBeGreaterThanOrEqual(0);
expect(shippingFee(1000, true)).toBeGreaterThanOrEqual(0);
expect(shippingFee(9000, false)).toBeGreaterThanOrEqual(0);
});// Assert the value, and the edge either side of the threshold.
test('shippingFee', () => {
expect(shippingFee(1000, false)).toBe(499);
expect(shippingFee(1000, true)).toBe(249);
expect(shippingFee(4999, false)).toBe(499);
expect(shippingFee(5000, false)).toBe(0);
}); Run the sim’s weak suite and watch two numbers: coverage reaches 100% and the bug is still there. That is the result you reproduce on the lab below, with the real tools.
Flake rate: can you trust a red build
The flake rate is a signal-health metric. Its job is to tell you whether a red build carries information. Question: how often does a failure mean nothing? Definition: the share of gating runs whose first attempt failed and then passed on a re-run with no change to the code, over a fixed window, with a flake budget the team agreed in advance. Source: the CI run log, a field recording whether an attempt was a re-run. Decision: whether new end-to-end tests wait while flakes are fixed. It must never be used to compare teams with different suites, or to judge the engineer who inherited the tests.
You measure it the way the flaky-tests chapter did: run the same test on the same code many times and count red. “Fails about half the time” is an opinion. “Failed 29 of 50 runs on an unchanged commit” is a measurement, and it comes with a spread: another 50 runs gives a different count. On this lab the quarantined test fails about 35% to 60% of runs, varying from run to run.
Escape rate: did the defects reach customers
The escape rate is the outcome metric for testing. Question: of the defects that existed, how many did customers find first? Definition: defects found after release, divided by all defects found (those caught before release plus those found after), by release cohort and with a fixed window, such as 30 days. Source: the defect tracker, with a required “found by” field that triage cannot leave blank, joined to the CI log. Decision: whether to hold a review of what the tests missed, and where to add tests. It must never be used to rank engineers or teams, or as a target with a reward, because the cheapest way to lower it is to relabel. In the lab data below, relabelling three defects as feature requests moves the rate from 50% to 36% and no customer is better off.
The denominator matters. Escaped defects alone rise when you ship more, and they fall when you ship less, which tells you about volume. Escaped over escaped plus caught gives the share that got through, and the share is what testing is accountable for. The measure is still partial: a defect that nobody finds is in neither count.
Time to green: what a failure costs
Time to green is the second signal-health metric. Question: how long does a change wait for trustworthy evidence? Definition: minutes from the first push to the first green run, per change, reported as a median and a 90th percentile with the count beside them. Source: the CI run log. Decision: where CI engineering time goes: runners, sharding or flakes. It must never be used to judge how hard an engineer works.
Report a median and a percentile because the distribution has a long tail. A few runs wait on an outage or a long fix, and a single average hides both the typical change and the bad day. You see the effect in the lab data, where the mean is 30.1 minutes, the median 12.4 and the 90th percentile 63.6. Splitting the time by the cause of the first failure shows where the minutes go, which a single number never does. Štěpán Davidovič’s Monte Carlo analysis of incident durations, in “Incident Metrics in SRE” (Google), reaches a related conclusion for mean time to recovery and mitigation: they suit decisions and trends poorly.
Count the tests, and mean it
The raw count of tests and the suite’s duration belong on the diagnostic page, with a warning. Test count rises when someone splits one test into five, and it falls when someone parametrises five into one. Duration is useful, because the cost of running tests on every change is time, but it is a trend to watch on one suite, not a score. The lab prints both, and you see in the first step that 23 tests run in 0.9 seconds. That figure is a reference point for later, not a result.
Goodhart’s law, with numbers
When a measure becomes a target, it stops measuring. The line is attached to Charles Goodhart and, in this wording, to Marilyn Strathern. DORA’s guide applies it directly: mandating values for its metrics, such as deploying several times a day, invites teams to game the numbers. Its other warnings are the ones to take over for testing: do not rely on a single metric, do not compare different applications, and do not make it a competition.
You do not need to argue the point. You can run it. In the lab below you raise pricing coverage from 92% to 100% with three tests that check nothing, and the mutation score stays at 28 of 68. You relabel three escapes and the escape rate falls from 50% to 36%. Each is the cheap route to a target, and each leaves the product exactly where it was.
Choosing five metrics for Ojaline
Pavel is not wrong to want numbers. He needs a small set that he can read, that cannot be improved without improving something, and that has a different owner for each. Nanami’s list, which you build in the lab:
| Metric | Kind | Reader |
|---|---|---|
| Escape rate, with the count of severity 1 and 2 escapes beside it | Outcome | Pavel, quarterly |
| Flake rate against a budget | Signal health | Team leads, weekly |
| Time to green: median and p90 | Signal health | CI platform, weekly |
Mutation score on pricing.py and money.py |
Activity | Authors of those files, each sprint |
| Coverage of changed lines | Activity | Reviewers, on each change |
Coverage of the whole codebase is missing on purpose. It is a map, and the useful version of the map is the changed-lines one that shows a reviewer what a change left untested. Pavel gets one outcome number and two signal numbers, none of which can be reached by writing a test with no assertion.
Two cautions about the data you compute them from. First, small numbers: the lab’s 60 runs split by team into 18 to 21 runs each, and one defect more or less changes a team’s escape rate by tens of points. Compare a team with its own past, never with another team. Second, the synthetic CSV is built so that coverage on a change has nothing to do with whether it escapes. The generator makes it so. That shows you the method for checking, not a finding about real code, and the real evidence on the question is the research in the reading list.
You will measure the lab’s tests, generate a CSV of 60 synthetic CI runs from a seeded script, compute the flake rate, escape rate and time to green, raise coverage to 100% without moving the mutation score, relabel defects to see the escape rate fall, and write down five metrics with their definitions. Work from labs/testing. Your numbers for the lab’s own tools match the ones below. The flake rate varies from run to run.
Start from the shipped state. If an earlier chapter’s lab left test files behind, remove them and run git checkout tests pyproject.toml.
cd labs/testing
export CHECKOUT_DB=/tmp/metrics-lab.sqlite
export TZ=UTC
mkdir -p data
rm -rf mutantsTZ=UTC fixes the machine’s time zone, because one mutant in pricing.py reads it, as the mutation chapter explained.
1. Measure the suite: coverage per module, test count and duration. Create scripts/quality_snapshot.py:
"""Print one line per module: line coverage, branch coverage, and the whole suite's size.
Run from labs/testing after:
.venv/bin/pytest -p no:randomly -q --cov=checkout --cov-branch \
--cov-report=json:data/cov.json --junitxml=data/junit.xml
"""
import json
import xml.etree.ElementTree as ET
cov = json.load(open("data/cov.json"))
print("%-24s %6s %9s %11s" % ("module", "lines", "branches", "statements"))
for path, data in sorted(cov["files"].items()):
s = data["summary"]
if s["num_statements"] == 0:
continue
lines = 100 * s["covered_lines"] / s["num_statements"]
if s["num_branches"]:
branches = "%7.0f%%" % (100 * s["covered_branches"] / s["num_branches"])
else:
branches = "%8s" % "none"
print("%-24s %5.0f%% %s %11d" % (path.replace("checkout/", ""), lines, branches, s["num_statements"]))
suite = ET.parse("data/junit.xml").getroot()
if suite.tag == "testsuites":
suite = suite[0]
print()
print("tests: %s run, %s skipped, %s failed, %.2f s" % (
int(suite.get("tests")) - int(suite.get("skipped")),
suite.get("skipped"), suite.get("failures"), float(suite.get("time"))))Run the suite with coverage and read the snapshot:
.venv/bin/pytest -p no:randomly -q --cov=checkout --cov-branch --cov-report=json:data/cov.json --junitxml=data/junit.xml | tail -1
.venv/bin/python scripts/quality_snapshot.py23 passed, 1 skipped, 1 deselected, 1 warning in 0.91s
module lines branches statements
ai_summary.py 97% 83% 35
api.py 73% 50% 83
...
legacy.py 0% 0% 20
money.py 100% none 8
orders.py 90% 80% 40
payments_client.py 46% 0% 26
pricing.py 95% 79% 61
search_index.py 100% 50% 33
tests: 23 run, 1 skipped, 0 failed, 0.91 sSame suite, very different modules. money.py is fully covered. legacy.py has no test at all, and payments_client.py runs less than half its code. pricing.py shows 95% of lines and 79% of branches, which is why the earlier chapter’s combined figure was 92%. Line and branch coverage are two numbers, and this is the second. The timing on your machine will differ by a little.
2. Measure the tests, and the flake rate over 50 runs. First the mutation score of the money rules:
.venv/bin/python scripts/mutate.py run 2>&1 | tr '\r' '\n' | grep -o '[0-9]*/[0-9]* .*🔇 [0-9]*' | tail -1Then 50 runs of the quarantined flaky test, counting the red ones:
fail=0; for i in $(seq 50); do .venv/bin/pytest -m flaky -p no:randomly -q >/dev/null 2>&1 || fail=$((fail+1)); done; echo "$fail of 50 runs failed"68/68 🎉 28 🫥 0 ⏰ 0 🤔 0 🙁 40 🔇 0
29 of 50 runs failedMutation score 28 of 68, 41%, from two seconds of work. The flake loop takes about a minute. Your count differs: a second run of 50 gave 21 (these are single runs). Both are the same test on the same code, so the spread is itself the finding. One run proves nothing, 50 give a range, and you report the range (about 20 to 30 of 50) not a single figure. Across all the runs of this test taken while writing the course, it failed about 35% to 60% of the time, varying from run to run: far above anything a budget would allow. The 29 and 21 above are two single runs.
3. Generate the CI-runs CSV. The chapter’s data is synthetic: every figure is invented, and the same seed always writes the same file. Create scripts/make_ci_runs.py:
"""Write data/ci_runs.csv: 60 synthetic CI runs for Ojaline's checkout service.
Every number is invented. The same seed always writes the same file.
Run from labs/testing: .venv/bin/python scripts/make_ci_runs.py
"""
import csv
import random
from datetime import date, timedelta
SEED = 2026
RUNS = 60
TEAMS = (("orders", 0.40), ("pricing", 0.30), ("payments-client", 0.30))
# Chance that a change which passed CI still has a defect found in production
# within 30 days. It depends on the team and on nothing else.
ESCAPE_CHANCE = {"orders": 0.14, "pricing": 0.06, "payments-client": 0.10}
rng = random.Random(SEED)
def pick_team():
x = rng.random()
total = 0.0
for name, weight in TEAMS:
total += weight
if x < total:
return name
return TEAMS[-1][0]
rows = []
day = date(2026, 9, 1)
for n in range(1, RUNS + 1):
day += timedelta(days=1 if rng.random() < 0.6 else 2)
while day.weekday() >= 5: # skip Saturday and Sunday
day += timedelta(days=1)
team = pick_team()
attempt_min = 8 + rng.random() * 6 # one CI attempt: 8 to 14 minutes
first_result, cause, attempts, minutes = "pass", "", 1, attempt_min
if rng.random() < 0.35:
first_result = "fail"
x = rng.random()
if x < 0.40:
cause, attempts = "real_bug", 2
wait = 20 + rng.expovariate(1 / 45) # time to find and fix the bug
elif x < 0.80:
cause, attempts = "flaky", 2
wait = 3 + rng.random() * 12 # someone presses re-run
else:
cause, attempts = "infra", 2
wait = 30 + rng.expovariate(1 / 120) # runner or registry trouble
minutes = attempt_min * attempts + wait
escaped = 0
if rng.random() < ESCAPE_CHANCE[team]:
escaped = 1 + (rng.random() < 0.2)
coverage = min(100.0, max(45.0, rng.gauss(78, 9))) # independent of everything else
rows.append({
"run_id": "r%03d" % n,
"merged_on": day.isoformat(),
"team": team,
"first_result": first_result,
"cause": cause,
"attempts": attempts,
"minutes_to_green": round(minutes, 1),
"defects_caught_by_ci": 1 if cause == "real_bug" else 0,
"defects_escaped": escaped,
"changed_line_coverage_pct": round(coverage, 1),
})
with open("data/ci_runs.csv", "w", newline="") as f:
writer = csv.DictWriter(f, fieldnames=list(rows[0]))
writer.writeheader()
writer.writerows(rows)
print("wrote data/ci_runs.csv: %d runs" % len(rows)).venv/bin/python scripts/make_ci_runs.py
head -4 data/ci_runs.csv
shasum -a 256 data/ci_runs.csv | cut -c1-16wrote data/ci_runs.csv: 60 runs
run_id,merged_on,team,first_result,cause,attempts,minutes_to_green,defects_caught_by_ci,defects_escaped,changed_line_coverage_pct
r001,2026-09-02,pricing,pass,,1,11.1,0,0,80.0
r002,2026-09-03,payments-client,pass,,1,11.3,0,0,90.0
r003,2026-09-07,pricing,pass,,1,9.4,0,0,82.0
0841d2c41c4d589dRead the code before you trust the file. Each row is a change that merged. cause says why the first attempt failed: real_bug (CI caught a defect), flaky (a re-run went green), infra (a runner or registry problem). defects_escaped is what production found within 30 days. The checksum matches on any machine, because the generator is seeded, so you and a colleague analyse the same 60 runs. The generator makes the team the only thing that affects escapes, and coverage affects nothing. You will see in step 4 what that looks like in the numbers.
4. Compute the metrics. Create scripts/analyse_ci_runs.py:
"""Read data/ci_runs.csv and print the metrics, each with its definition.
Run from labs/testing: .venv/bin/python scripts/analyse_ci_runs.py [csv-file]
"""
import csv
import statistics
import sys
from collections import defaultdict
path = sys.argv[1] if len(sys.argv) > 1 else "data/ci_runs.csv"
with open(path, newline="") as f:
runs = list(csv.DictReader(f))
for r in runs:
r["minutes_to_green"] = float(r["minutes_to_green"])
r["defects_caught_by_ci"] = int(r["defects_caught_by_ci"])
r["defects_escaped"] = int(r["defects_escaped"])
r["changed_line_coverage_pct"] = float(r["changed_line_coverage_pct"])
def percentile(values, p):
"""Nearest-rank percentile, so the answer is always a value in the data."""
ordered = sorted(values)
rank = max(1, -(-len(ordered) * p // 100)) # ceiling without importing math
return ordered[int(rank) - 1]
def escape_rate(rows):
caught = sum(r["defects_caught_by_ci"] for r in rows)
escaped = sum(r["defects_escaped"] for r in rows)
return escaped, caught + escaped
print("runs: %d" % len(runs))
# Flake rate: the share of runs whose first attempt failed and then passed
# with no code change.
flaky = sum(1 for r in runs if r["cause"] == "flaky")
print("flake rate: %d of %d runs (%.1f%%)" % (flaky, len(runs), 100 * flaky / len(runs)))
# Escape rate: of all defects found, the share found after release.
escaped, found = escape_rate(runs)
print("escape rate: %d of %d defects (%.1f%%)" % (escaped, found, 100 * escaped / found))
print(" by team (small numbers, read with care):")
by_team = defaultdict(list)
for r in runs:
by_team[r["team"]].append(r)
for team in sorted(by_team):
e, n = escape_rate(by_team[team])
print(" %-16s %d runs, %d of %d defects escaped" % (team, len(by_team[team]), e, n))
# Time to green: minutes from the first push to the first green run.
times = [r["minutes_to_green"] for r in runs]
print("time to green (minutes):")
print(" mean %.1f" % statistics.mean(times))
print(" median %.1f" % statistics.median(times))
print(" p90 %.1f" % percentile(times, 90))
print(" max %.1f" % max(times))
print(" by cause of the first failure (median, count):")
by_cause = defaultdict(list)
for r in runs:
by_cause[r["cause"] or "none"].append(r["minutes_to_green"])
for cause in ("none", "flaky", "real_bug", "infra"):
if cause in by_cause:
print(" %-9s %6.1f n=%d" % (cause, statistics.median(by_cause[cause]), len(by_cause[cause])))
# The vice president's two targets, and what coverage says about escapes.
bad = [r["changed_line_coverage_pct"] for r in runs if r["defects_escaped"] > 0]
good = [r["changed_line_coverage_pct"] for r in runs if r["defects_escaped"] == 0]
print("changed-line coverage, mean: %.1f%% on changes with an escape (n=%d), %.1f%% on the rest (n=%d)"
% (statistics.mean(bad), len(bad), statistics.mean(good), len(good)))
print("changes at or above 90%% changed-line coverage: %d of %d" % (sum(1 for r in runs if r["changed_line_coverage_pct"] >= 90), len(runs))).venv/bin/python scripts/analyse_ci_runs.pyruns: 60
flake rate: 10 of 60 runs (16.7%)
escape rate: 7 of 14 defects (50.0%)
by team (small numbers, read with care):
orders 21 runs, 5 of 6 defects escaped
payments-client 21 runs, 2 of 3 defects escaped
pricing 18 runs, 0 of 5 defects escaped
time to green (minutes):
mean 30.1
median 12.4
p90 63.6
max 247.4
by cause of the first failure (median, count):
none 11.3 n=41
flaky 33.1 n=10
real_bug 78.8 n=7
infra 208.7 n=2
changed-line coverage, mean: 79.6% on changes with an escape (n=7), 77.6% on the rest (n=53)
changes at or above 90% changed-line coverage: 6 of 60Read it line by line. One run in six needed a re-run for no reason, and each flake cost about 22 minutes more than a clean run (33.1 against 11.3 at the median): ten flakes are about 220 engineer-minutes in this window, which is the real price of the label Pavel wants gone. The escape rate is 50%, but the by-team lines are 3 to 6 defects each: do not conclude that pricing is better than orders from a count of five. The mean time to green is 30.1 minutes and the median 12.4, because two infrastructure runs took 170 and 247 minutes. Coverage for changes that escaped (79.6%) is no different from the rest (77.6%): in this data, as the generator built it, the number tells you nothing about escapes. Only 6 of 60 changes reach 90%, so Pavel’s target would be failed by almost every change, and gamed by the rest.
5. Game the coverage number. Create tests/unit/test_pricing_padding.py:
from contextlib import suppress
from datetime import datetime, timezone
from checkout.pricing import Line, delivery_fee, line_total, price_cart
def test_zero_quantity_runs():
with suppress(Exception):
line_total(Line(250_000, 0))
def test_negative_distance_runs():
with suppress(Exception):
delivery_fee(-5)
def test_promo_cart_runs():
with suppress(Exception):
now = datetime(2026, 12, 15, 12, 0, tzinfo=timezone.utc)
price_cart([Line(300_000, 2)], distance_km=3, now=now, promo_code="HARMATTAN").venv/bin/pytest -p no:randomly --cov=checkout.pricing --cov-branch --cov-report=term-missing -q | grep -E 'pricing.py |passed'
rm -rf mutants
.venv/bin/python scripts/mutate.py run 2>&1 | tr '\r' '\n' | grep -o '[0-9]*/[0-9]* .*🔇 [0-9]*' | tail -1checkout/pricing.py 61 0 14 0 100%
26 passed, 1 skipped, 1 deselected in 0.77s
68/68 🎉 28 🫥 0 ⏰ 0 🤔 0 🙁 40 🔇 0Coverage went from 92% to 100%, with no missed line and no partial branch, and the target is met. The mutation score is exactly where it was, 28 of 68. The three tests run the quantity guard, the distance guard and the promo discount, and check nothing: suppress(Exception) swallows any failure, so even a mutant that crashes the call is not noticed. If you had left the exceptions uncaught, some crash-mutants would die and the score would rise a little (it reached 37 of 68 in a trial where the calls were not wrapped). The point is that coverage reached its goal for the price of three tests that protect nothing.
Delete the file before you go on: rm tests/unit/test_pricing_padding.py.
6. Choose five metrics. Create data/metrics.csv with a header row metric,definition,source,decision,never_use_for and five rows of your own. Use this row as a guide, and quote any field that contains a comma:
Escape rate,Defects found after release as a share of all defects found in the quarter,"Tracker field found_by, joined to the CI log","Whether to hold a release review and where to add tests","Ranking engineers or teams, or a target with a bonus"Choose from the metrics in this chapter, or add one of your own (change fail rate from the DORA list, say), and fill in all five columns for each. Then check that nothing is blank:
.venv/bin/python - <<'EOF'
import csv
rows = list(csv.DictReader(open("data/metrics.csv", newline="")))
print(len(rows), "metrics")
for r in rows:
missing = [k for k, v in r.items() if not v.strip()]
print("%-32s %s" % (r["metric"], "complete" if not missing else "missing: " + ", ".join(missing)))
EOF5 metrics
Escape rate complete
Flake rate complete
Time to green (median and p90) complete
Mutation score on money files complete
Changed-line coverage completeWith Nanami’s five, the check prints this. Compare your never_use_for column with hers: for flake rate it reads “comparing teams with different suites”, for the mutation score “a merge gate before a month of noise is understood”, for changed-line coverage “a target for all code, or evidence a change is safe”. A blank in that column means you have not yet thought about how the number breaks, and that is the column that matters.
Relabel the data, as a team under pressure would. Create scripts/relabel.py, which zeroes the first three escapes and writes a second file:
import csv
rows = list(csv.DictReader(open("data/ci_runs.csv", newline="")))
n = 0
for r in rows:
if r["defects_escaped"] != "0" and n < 3:
r["defects_escaped"] = "0"
n += 1
with open("data/ci_runs_relabelled.csv", "w", newline="") as f:
writer = csv.DictWriter(f, fieldnames=list(rows[0]))
writer.writeheader()
writer.writerows(rows)Run it, then .venv/bin/python scripts/analyse_ci_runs.py data/ci_runs_relabelled.csv | sed -n 3p. The escape rate falls from 7 of 14 (50.0%) to 4 of 11 (36.4%). Three defects were relabelled and no customer is better off. Now look for the defence: which field in a real tracker would show the relabelling (a changed found-by value, a reopened ticket), and could the dashboard show that count beside the rate? Delete scripts/relabel.py and data/ci_runs_relabelled.csv when you are done.
7. Put the lab back. Remove everything you created, including the files under data/, and unset the variables:
rm -f scripts/quality_snapshot.py scripts/make_ci_runs.py scripts/analyse_ci_runs.py scripts/relabel.py
rm -f data/cov.json data/junit.xml data/ci_runs.csv data/ci_runs_relabelled.csv data/metrics.csv
rm -f tests/unit/test_pricing_padding.py /tmp/metrics-lab.sqlite
rm -rf mutants
unset CHECKOUT_DB TZ
git status --short .
.venv/bin/pytest -q 2>&1 | tail -1git status --short . prints nothing and the suite ends 23 passed, 1 skipped, 1 deselected. Keep data/metrics.csv somewhere outside the lab first if you want your five metrics.Pavel has asked for 90% coverage and zero flaky tests by quarter end, and he will read one slide. Nanami has the lab numbers: pricing coverage is already above 90% with a weak suite, 10 of 60 runs needed a re-run and each cost about 22 extra minutes, and half the defects in the window reached customers. Both of his targets would be met by cheap routes. What does she propose in the meeting?
- PAPER Software Engineering Metrics: What Do They Measure and How Do We Know? Cem Kaner and Walter P. Bond, 2004
The argument behind this whole chapter: a metric has to be shown to measure the attribute you care about, and bug counts capture only a small part of it. Read it before you add a number to a dashboard. Read: Sections 1 and 2 for construct validity and the cost of measurement dysfunction; skip the formal measurement theory.
- DOC DORA: the software delivery metrics DORA, Google Cloud
The five delivery metrics with their definitions, and four plain warnings: do not set them as targets, do not rely on one, do not compare different applications, do not make it a competition. Read the warnings twice.
- DOC DORA research programme DORA, Google Cloud
The research behind the metrics, with each year's report from 2014. Use it to see how the programme studies delivery, and skip the summaries if you only need the definitions.
- PAPER Coverage Is Not Strongly Correlated with Test Suite Effectiveness Laura Inozemtseva and Reid Holmes, 2014
The evidence for the activity-metric point: coverage on its own says little about how many faults a suite finds once suite size is accounted for. Read the threats section to see how far it generalises. Read: Abstract, then the results and threats to validity.
- PAPER Code Coverage at Google Marko Ivankovic and others, 2019
Shows coverage used well: on the changeset, in review, as information for the reviewer and not as a gate. Skip the infrastructure detail. Read: The sections on the survey of developers and on coverage in code review.
- POST Fowler: Test Coverage Martin Fowler, 2012
A short note that says what coverage is for (finding untested code) and what it is not (a measure of test quality), and warns about making it a target. Ten minutes.
All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.