Finds the test coverage gaps that matter in a Cobertura XML or LCOV report: files with the most missed lines, uncovered blocks, weak branch coverage, untested files and diff coverage of the lines changed in a pull request, then suggests the few tests worth writing first. Stdlib Python.
---
name: code-coverage-gap-finder
description: Finds the test coverage gaps that matter in a Cobertura XML or LCOV report: files with the most missed lines, uncovered blocks, weak branch coverage, untested files and diff coverage of the lines changed in a pull request, then suggests the few tests worth writing first. Stdlib Python.
---
# Code Coverage Gap Finder
You help developers and reviewers turn a coverage report into a short, useful list of tests to write. A single "coverage 51%" number tells a team almost nothing; what helps is knowing which files and which changed lines are not exercised by any test, where whole blocks or error paths are never run, and which gaps are risky enough to fix now. You read the report (and the diff of the change under review, if there is one), explain the numbers plainly, and propose a small, ranked set of concrete tests.
Coverage is a map of what tests execute, not proof that the code is correct. A line can be covered by a test that asserts nothing. Always say this when someone treats a high number as a quality guarantee, and never suggest tests that only exist to raise the number.
## Files in this skill
- `scripts/coverage_gaps.py` - reads Cobertura XML (coverage.py `coverage xml`, Jest/Vitest/istanbul `cobertura` reporter, gcovr, PHPUnit, coverlet, JaCoCo converted to Cobertura) or LCOV (`lcov.info`), and optionally a unified diff (`git diff`); prints totals, the files with the most missed lines with uncovered line ranges, diff coverage of changed lines and flags C01-C09; `--format text|md|json|csv`, thresholds, `--exclude`, `--strip-prefix`, `--fail-on`, `--self-test` runs 22 checks (Python 3.8+ standard library only)
- `references/coverage-metrics.md` - line, branch and diff coverage, how tools count them differently, and sensible targets
- `references/what-to-test-first.md` - how to rank gaps by risk and what a good test for each kind of gap looks like
- `templates/coverage-review.md` - a pull request or team review comment with numbers, the top gaps and the proposed tests
- `examples/coverage.xml` - a real coverage.py report (with `--branch`) of a small shop project: well-tested pricing, a partly tested discounts module, untested refunds and a new untested gift card module
- `examples/changes.diff` - the `git diff -U0` of the change under review (new discount helpers, new gift card file, one new test)
- `examples/lcov.info` - a small LCOV report from a JavaScript project
## Workflow
### 1. Get the report and the diff
Ask which language and test runner they use and produce a report in one of the two formats:
```
# Python (coverage.py)
coverage run --branch -m pytest && coverage xml -o coverage.xml
# JavaScript / TypeScript (Jest or Vitest with istanbul)
npx jest --coverage --coverageReporters=cobertura # or lcov -> coverage/lcov.info
npx vitest run --coverage --coverage.reporter=cobertura
# C / C++
gcovr --xml-pretty -o coverage.xml
# The change under review
git diff --no-color -U0 origin/main...HEAD > changes.diff
```
Branch data only appears when branch measurement is on (`--branch` for coverage.py). Paths in the diff must match the paths in the report; if the report stores `src/app/x.py` and the diff says `app/x.py`, use `--strip-prefix src`.
### 2. Run the analysis
```
python3 scripts/coverage_gaps.py coverage.xml
python3 scripts/coverage_gaps.py coverage.xml --diff changes.diff --min-diff 80 --format md > coverage-review.md
python3 scripts/coverage_gaps.py coverage/lcov.info --exclude "src/generated/*" --min-total 70
python3 scripts/coverage_gaps.py coverage.xml --format csv > coverage-by-file.csv
python3 scripts/coverage_gaps.py coverage.xml --diff changes.diff --fail-on high # CI gate
python3 scripts/coverage_gaps.py --self-test
```
Exit code 0 = fine (or `--fail-on none`, the default), 1 = flags at or above `--fail-on`, 2 = unreadable report or diff.
| Code | Severity | Gap |
|---|---|---|
| C01 | medium | total line coverage below `--min-total` (default 80%) |
| C02 | low | a file with at least `--min-lines` lines is below `--min-file` (default 60%) |
| C03 | medium / high | diff coverage of changed executable lines below `--min-diff` (high when below half of it) |
| C04 | medium | a changed source file is not in the report at all (new file never imported, or excluded) |
| C05 | low | an uncovered block of `--block` (default 15) or more consecutive lines in a partly tested file |
| C06 | low | branch coverage 25+ points below line coverage: lines run, but some if/else paths never do |
| C07 | medium | a file with at least `--min-lines` lines has no covered line at all |
| C08 | high | the report has no measured lines (tests did not run, or wrong paths) |
| C09 | info | the diff has no changed executable lines in the report (docs/config change, or path mismatch) |
### 3. Rank the gaps
Use `references/what-to-test-first.md`. Changed lines come first (C03/C04): they are the cheapest to test now and the most likely to hide new bugs. Then untested files that handle money, permissions, data deletion or external input (C07), then uncovered error paths and branches (C05/C06). Generated code, simple getters, logging and `if __name__ == "__main__"` blocks are low priority; suggest `--exclude` or a coverage config exclusion with a reason instead of tests.
### 4. Propose tests
For the top 3-5 gaps, open the uncovered line ranges and write concrete test ideas: the function, the input, the expected result or exception, and which uncovered lines or branch it will run. Prefer one meaningful assertion per behavior over many lines that only execute code. If the code is hard to test (hidden I/O, globals, time), say so and suggest a small refactor.
### 5. Report
Fill `templates/coverage-review.md` for a PR comment or a team review. Include the numbers, the top gaps, the proposed tests and an honest note on what coverage cannot tell.
## Rules
- Coverage numbers differ between tools (lines vs statements, with or without branches); compare runs only from the same tool and settings. coverage.py's own "Cover" column combines lines and branches, so it can differ from this script's line coverage.
- Never recommend tests without assertions, or excluding code from measurement just to hit a target.
- Do not shame a team for a low number; show the cheapest, highest-value next steps.
- Treat thresholds as team agreements, not universal truths; a 100% target is rarely worth its cost.
- Do not paste proprietary source code outside the conversation; line numbers and file names are enough for the report.
FILE:references/coverage-metrics.md
# Coverage metrics in plain words
## Line coverage
The share of executable lines that ran at least once during the tests. Blank lines, comments and most declarations do not count. Tools disagree on details: coverage.py counts statements, istanbul counts statements and lines separately, gcov counts lines. Always compare numbers from the same tool and settings.
## Branch coverage
The share of possible paths through decisions (`if`/`else`, loops entered or skipped, `&&`/`||` short circuits, `switch` cases, ternaries) that ran. A line with `if x:` is "covered" as soon as it runs once, but its branch is only fully covered when the tests make it both true and false. Branch coverage is usually lower than line coverage. A gap of 25 points or more (flag C06) often means error paths, edge cases or `else` cases are never tested.
In Cobertura XML a branch line looks like `<line number="12" hits="3" branch="true" condition-coverage="50% (1/2)"/>`; in LCOV each branch is a `BRDA:<line>,<block>,<branch>,<taken>` record where `-` means never evaluated.
## Diff coverage (patch coverage)
The share of changed executable lines in a pull request that the tests run. It answers "did this change come with tests?" and is fairer than a total number, because old untested code does not punish a new, well-tested change. Many teams gate PRs on diff coverage (for example 80%) and only watch the total.
Only added or modified lines count. Deleted lines, blank lines, comments and test files are ignored. A new source file that does not appear in the report at all (flag C04) usually means no test imports it, or it is excluded in the coverage configuration.
## Function coverage
The share of functions called at least once (LCOV `FN`/`FNDA`). A quick way to spot dead or untested functions; this script reports lines and branches only.
## Sensible targets
- New and changed code: 80-90% diff coverage with meaningful assertions.
- Whole project: a trend that goes up slowly matters more than a fixed number; 70-85% is common for application code.
- Critical modules (payments, permissions, data deletion, parsing external input): aim higher and test branches, not just lines.
- 100% is rarely worth the cost; the last few percent are often defensive code, generated code or platform-specific paths.
## What coverage cannot tell you
- Whether the assertions are right, or whether there are any assertions at all.
- Whether important combinations of inputs are tested (100% branch coverage can still miss a bug that needs two conditions at once).
- Whether integration with real databases, networks or browsers works.
- Mutation testing (for example mutmut, Stryker, PIT) is the next step when a team wants to know if tests would catch real bugs.
FILE:references/what-to-test-first.md
# What to test first
Rank each gap by **risk x likelihood of change / cost to test**. In practice this order works for most teams:
1. **Changed lines without tests (C03, C04).** The author has the context right now and the change is the most likely place for a new bug. Ask for tests in the same pull request.
2. **Untested code that moves money, controls access or deletes data (C07 in such files).** Refunds, payments, prices, discounts, permissions, account deletion, data export, migrations.
3. **Code that parses external input.** File uploads, CSV and JSON imports, webhooks, URL and form parameters, dates and time zones.
4. **Error paths and branches (C05, C06).** `except`/`catch` blocks, early returns, "not found" and "too small" cases, retries and timeouts. Bugs hide where tests never go.
5. **Large uncovered blocks in otherwise tested files (C05).** Often a forgotten feature flag path or a whole function nobody calls; sometimes dead code to delete instead of test.
6. **Everything else**, only when it is cheap.
## Usually not worth a test
- Generated code (protobuf, ORM migrations, API clients), vendored libraries.
- Trivial getters and setters, `__repr__`, simple data classes.
- `if __name__ == "__main__":` blocks and CLI wiring that is covered by an end-to-end test.
- Logging-only lines and debug helpers.
Exclude them with a reason (`# pragma: no cover` with a comment, `/* istanbul ignore next */`, or `omit`/`exclude` in the coverage config) rather than writing empty tests.
## What a good test for a gap looks like
- Names the behavior, not the line: `test_refund_is_zero_after_30_days`, not `test_line_12`.
- Sets up the smallest realistic input, calls the public function, and asserts the result or the exception.
- Covers both sides of the uncovered branch when the logic is important (`opened=True` and `opened=False`).
- Uses boundaries: 0, 1, the limit, limit + 1, empty, None, negative, very large.
- Avoids sleeping, real network calls and current time; inject a clock or a fake.
## Example from `examples/`
- `shop/gift_cards.py` is new in the change and has 0 covered lines: write tests for `redeem` (partial use, more than the balance, zero or negative amount) and `masked`, and for the invalid card number check in `__init__`.
- `shop/discounts.py` lines 29 and 36-41: `best_code` never sees an invalid code (line 29, the `continue`), and `code_expired` is never called. Two small tests cover both.
- `shop/refunds.py` has no tests at all and handles money: add tests for the 30-day limit, opened items (85%), damaged items and a return date before the order date.
FILE:templates/coverage-review.md
# Test coverage review: {{repository or PR title}}
**Report:** {{coverage tool, date, branch measurement on/off}}
**Change under review:** {{PR link or "whole project"}}
## Numbers
| Metric | Value | Target |
|---|---|---|
| Diff coverage (changed lines) | {{e.g. 30.0% (9/30)}} | {{80%}} |
| Line coverage (project) | {{e.g. 51.0%}} | {{80%}} |
| Branch coverage (project) | {{e.g. 40.9%}} | {{-}} |
## Gaps that matter most
1. **{{file}}** lines {{ranges}} - {{why it matters: new code / money / external input / error path}}
2. **{{file}}** lines {{ranges}} - {{why}}
3. **{{file}}** - {{why}}
## Tests I suggest
| # | Test | Covers | Effort |
|---|---|---|---|
| 1 | {{test name: input -> expected result}} | {{file:lines / branch}} | {{S/M/L}} |
| 2 | {{...}} | {{...}} | {{...}} |
| 3 | {{...}} | {{...}} | {{...}} |
## Not worth testing (exclude with a reason)
- {{file or block}} - {{generated / CLI wiring / logging}}
## Notes
- Coverage shows which code runs during tests, not whether the assertions are right.
- {{anything about flaky tests, missing branch data or path mismatches}}
FILE:examples/coverage.xml
<?xml version="1.0" ?>
<coverage version="7.18.0" timestamp="1796368012084" lines-valid="100" lines-covered="51" line-rate="0.51" branches-valid="44" branches-covered="18" branch-rate="0.4091" complexity="0">
<!-- Generated by coverage.py: https://coverage.readthedocs.io/en/7.18.0 -->
<!-- Based on https://raw.githubusercontent.com/cobertura/web/master/htdocs/xml/coverage-04.dtd -->
<sources>
<source>/home/dev/shop-api</source>
</sources>
<packages>
<package name="shop" line-rate="0.51" branch-rate="0.4091" complexity="0">
<classes>
<class name="__init__.py" filename="shop/__init__.py" complexity="0" line-rate="1" branch-rate="1">
<methods/>
<lines/>
</class>
<class name="cart.py" filename="shop/cart.py" complexity="0" line-rate="0.8333" branch-rate="0.625">
<methods/>
<lines>
<line number="2" hits="1"/>
<line number="3" hits="1"/>
<line number="6" hits="1"/>
<line number="7" hits="1"/>
<line number="8" hits="1"/>
<line number="9" hits="1"/>
<line number="11" hits="1"/>
<line number="12" hits="1" branch="true" condition-coverage="100% (2/2)"/>
<line number="13" hits="1" branch="true" condition-coverage="50% (1/2)" missing-branches="12"/>
<line number="14" hits="1"/>
<line number="15" hits="1"/>
<line number="16" hits="1"/>
<line number="18" hits="1"/>
<line number="19" hits="0"/>
<line number="20" hits="0"/>
<line number="21" hits="0" branch="true" condition-coverage="0% (0/2)" missing-branches="exit,22"/>
<line number="22" hits="0"/>
<line number="24" hits="1"/>
<line number="25" hits="1"/>
<line number="27" hits="1"/>
<line number="28" hits="1"/>
<line number="29" hits="1" branch="true" condition-coverage="100% (2/2)"/>
<line number="30" hits="1"/>
<line number="31" hits="1"/>
</lines>
</class>
<class name="discounts.py" filename="shop/discounts.py" complexity="0" line-rate="0.6667" branch-rate="0.5625">
<methods/>
<lines>
<line number="3" hits="1"/>
<line number="10" hits="1"/>
<line number="11" hits="1"/>
<line number="12" hits="1" branch="true" condition-coverage="50% (1/2)" missing-branches="13"/>
<line number="13" hits="0"/>
<line number="14" hits="1" branch="true" condition-coverage="50% (1/2)" missing-branches="15"/>
<line number="15" hits="0"/>
<line number="16" hits="1" branch="true" condition-coverage="100% (2/2)"/>
<line number="17" hits="1"/>
<line number="19" hits="1"/>
<line number="20" hits="1"/>
<line number="23" hits="1"/>
<line number="25" hits="1"/>
<line number="26" hits="1" branch="true" condition-coverage="100% (2/2)"/>
<line number="27" hits="1"/>
<line number="28" hits="1" branch="true" condition-coverage="50% (1/2)" missing-branches="29"/>
<line number="29" hits="0"/>
<line number="30" hits="1" branch="true" condition-coverage="100% (2/2)"/>
<line number="31" hits="1"/>
<line number="32" hits="1"/>
<line number="35" hits="1"/>
<line number="36" hits="0"/>
<line number="37" hits="0" branch="true" condition-coverage="0% (0/2)" missing-branches="38,39"/>
<line number="38" hits="0"/>
<line number="39" hits="0" branch="true" condition-coverage="0% (0/2)" missing-branches="40,41"/>
<line number="40" hits="0"/>
<line number="41" hits="0"/>
</lines>
</class>
<class name="gift_cards.py" filename="shop/gift_cards.py" complexity="0" line-rate="0" branch-rate="0">
<methods/>
<lines>
<line number="4" hits="0"/>
<line number="5" hits="0"/>
<line number="6" hits="0" branch="true" condition-coverage="0% (0/2)" missing-branches="7,8"/>
<line number="7" hits="0"/>
<line number="8" hits="0"/>
<line number="9" hits="0"/>
<line number="11" hits="0"/>
<line number="12" hits="0" branch="true" condition-coverage="0% (0/2)" missing-branches="13,14"/>
<line number="13" hits="0"/>
<line number="14" hits="0"/>
<line number="15" hits="0"/>
<line number="16" hits="0"/>
<line number="18" hits="0"/>
<line number="19" hits="0"/>
</lines>
</class>
<class name="pricing.py" filename="shop/pricing.py" complexity="0" line-rate="0.8667" branch-rate="0.6667">
<methods/>
<lines>
<line number="3" hits="1"/>
<line number="6" hits="1"/>
<line number="7" hits="1" branch="true" condition-coverage="100% (2/2)"/>
<line number="8" hits="1"/>
<line number="9" hits="1" branch="true" condition-coverage="50% (1/2)" missing-branches="10"/>
<line number="10" hits="0"/>
<line number="11" hits="1"/>
<line number="14" hits="1"/>
<line number="15" hits="1" branch="true" condition-coverage="50% (1/2)" missing-branches="16"/>
<line number="16" hits="0"/>
<line number="17" hits="1"/>
<line number="20" hits="1"/>
<line number="21" hits="1"/>
<line number="22" hits="1"/>
<line number="23" hits="1"/>
</lines>
</class>
<class name="refunds.py" filename="shop/refunds.py" complexity="0" line-rate="0" branch-rate="0">
<methods/>
<lines>
<line number="2" hits="0"/>
<line number="5" hits="0"/>
<line number="6" hits="0"/>
<line number="7" hits="0" branch="true" condition-coverage="0% (0/2)" missing-branches="8,9"/>
<line number="8" hits="0"/>
<line number="9" hits="0" branch="true" condition-coverage="0% (0/2)" missing-branches="10,11"/>
<line number="10" hits="0"/>
<line number="11" hits="0" branch="true" condition-coverage="0% (0/2)" missing-branches="12,13"/>
<line number="12" hits="0"/>
<line number="13" hits="0" branch="true" condition-coverage="0% (0/2)" missing-branches="14,15"/>
<line number="14" hits="0"/>
<line number="15" hits="0"/>
<line number="18" hits="0"/>
<line number="19" hits="0"/>
<line number="25" hits="0" branch="true" condition-coverage="0% (0/2)" missing-branches="26,27"/>
<line number="26" hits="0"/>
<line number="27" hits="0"/>
<line number="30" hits="0"/>
<line number="31" hits="0"/>
<line number="32" hits="0"/>
</lines>
</class>
</classes>
</package>
</packages>
</coverage>
FILE:examples/changes.diff
diff --git a/shop/discounts.py b/shop/discounts.py
index 7a2f304..81655b4 100644
--- a/shop/discounts.py
+++ b/shop/discounts.py
@@ -20,0 +21,21 @@ def apply_code(total_cents, code):
+
+
+def best_code(total_cents, codes):
+ """Pick the code that gives the lowest total; ties keep the first code."""
+ best, best_total = None, total_cents
+ for code in codes:
+ new_total, error = apply_code(total_cents, code)
+ if error:
+ continue
+ if new_total < best_total:
+ best, best_total = code, new_total
+ return best, best_total
+
+
+def code_expired(code, today, expiry):
+ end = expiry.get(code.strip().upper())
+ if end is None:
+ return False
+ if today > end:
+ return True
+ return False
diff --git a/shop/gift_cards.py b/shop/gift_cards.py
new file mode 100644
index 0000000..a6a7e76
--- /dev/null
+++ b/shop/gift_cards.py
@@ -0,0 +1,19 @@
+"""Gift card balances (new in this change)."""
+
+
+class GiftCard:
+ def __init__(self, number, balance_cents):
+ if len(number) != 16 or not number.isdigit():
+ raise ValueError("gift card number must be 16 digits")
+ self.number = number
+ self.balance = balance_cents
+
+ def redeem(self, amount_cents):
+ if amount_cents <= 0:
+ raise ValueError("amount must be positive")
+ used = min(amount_cents, self.balance)
+ self.balance -= used
+ return amount_cents - used
+
+ def masked(self):
+ return "**** **** **** " + self.number[-4:]
diff --git a/tests/__init__.py b/tests/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/tests/test_discounts.py b/tests/test_discounts.py
new file mode 100644
index 0000000..b62587b
--- /dev/null
+++ b/tests/test_discounts.py
@@ -0,0 +1,7 @@
+import unittest
+from shop.discounts import best_code
+
+
+class DiscountTest(unittest.TestCase):
+ def test_best_code(self):
+ self.assertEqual(best_code(5000, ["WELCOME10", "SAVE5"]), ("WELCOME10", 4500))
FILE:examples/lcov.info
TN:
SF:src/utils/slugify.js
FN:1,slugify
FNDA:6,slugify
DA:2,6
DA:3,6
DA:4,1
DA:5,5
DA:6,5
BRDA:3,0,0,1
BRDA:3,0,1,5
LF:5
LH:5
end_of_record
TN:
SF:src/utils/dates.js
FN:1,formatDate
FN:9,daysBetween
FNDA:3,formatDate
FNDA:0,daysBetween
DA:2,3
DA:3,3
DA:4,0
DA:5,3
DA:10,0
DA:11,0
DA:12,0
BRDA:3,0,0,0
BRDA:3,0,1,3
BRDA:11,1,0,-
BRDA:11,1,1,-
LF:7
LH:3
end_of_record
FILE:scripts/coverage_gaps.py
#!/usr/bin/env python3
"""coverage_gaps.py - find the coverage gaps that matter in a Cobertura XML or LCOV report.
Reads a coverage report (Cobertura XML from coverage.py `coverage xml`, Jest/Vitest/istanbul
`cobertura` reporter, PHPUnit, .NET coverlet, gcovr ...; or LCOV `lcov.info`), and optionally a
unified diff of the change under review. Prints totals, the files with the most missed lines,
uncovered line ranges, diff coverage of changed lines, and flags C01-C09.
Usage:
coverage_gaps.py REPORT [--diff changes.diff] [--format text|md|json|csv]
[--min-total 80] [--min-file 60] [--min-diff 80] [--min-lines 10]
[--block 15] [--top 10] [--exclude GLOB ...] [--strip-prefix PREFIX]
[--fail-on none|info|low|medium|high]
coverage_gaps.py --self-test
Exit: 0 ok, 1 flags at or above --fail-on, 2 unreadable input. Python 3.8+, standard library only.
"""
import argparse, csv, fnmatch, io, json, os, re, sys
import xml.etree.ElementTree as ET
SEV = {"info": 0, "low": 1, "medium": 2, "high": 3}
class FileCov:
def __init__(self, path):
self.path = path
self.lines = {} # line number -> hit count
self.branches = {} # line number -> (covered, total)
def add_line(self, n, hits):
self.lines[n] = max(self.lines.get(n, 0), hits)
def add_branch(self, n, covered, total):
c, t = self.branches.get(n, (0, 0))
self.branches[n] = (max(c, covered), max(t, total))
@property
def total(self): return len(self.lines)
@property
def covered(self): return sum(1 for h in self.lines.values() if h > 0)
@property
def missed_lines(self): return sorted(n for n, h in self.lines.items() if h == 0)
@property
def branch_total(self): return sum(t for _, t in self.branches.values())
@property
def branch_covered(self): return sum(c for c, _ in self.branches.values())
def pct(self):
return 100.0 * self.covered / self.total if self.total else None
def branch_pct(self):
return 100.0 * self.branch_covered / self.branch_total if self.branch_total else None
def norm_path(p, strip=""):
p = p.replace("\\", "/")
while p.startswith("./"):
p = p[2:]
if strip and p.startswith(strip):
p = p[len(strip):].lstrip("/")
return p
def parse_cobertura(text, strip=""):
root = ET.fromstring(text)
if root.tag != "coverage":
raise ValueError("not a Cobertura report (root element is <%s>)" % root.tag)
sources = [s.text.strip() for s in root.iter("source") if s.text and s.text.strip()]
files = {}
for cls in root.iter("class"):
fn = cls.get("filename")
if not fn:
continue
path = norm_path(fn, strip)
fc = files.setdefault(path, FileCov(path))
for ln in cls.iter("line"):
try:
n = int(ln.get("number")); hits = int(float(ln.get("hits", "0")))
except (TypeError, ValueError):
continue
fc.add_line(n, hits)
cond = ln.get("condition-coverage") # e.g. "50% (1/2)"
if ln.get("branch") == "true" and cond:
m = re.search(r"\((\d+)/(\d+)\)", cond)
if m:
fc.add_branch(n, int(m.group(1)), int(m.group(2)))
return files, sources
def parse_lcov(text, strip=""):
files, cur = {}, None
for raw in text.splitlines():
line = raw.strip()
if line.startswith("SF:"):
path = norm_path(line[3:], strip)
cur = files.setdefault(path, FileCov(path))
elif line.startswith("DA:") and cur is not None:
parts = line[3:].split(",")
try:
cur.add_line(int(parts[0]), int(float(parts[1])))
except (IndexError, ValueError):
continue
elif line.startswith("BRDA:") and cur is not None:
parts = line[5:].split(",")
if len(parts) == 4:
try:
n = int(parts[0])
except ValueError:
continue
taken = parts[3] not in ("-", "0")
c, t = cur.branches.get(n, (0, 0))
cur.branches[n] = (c + (1 if taken else 0), t + 1)
elif line == "end_of_record":
cur = None
if not files:
raise ValueError("no SF: records found; not an LCOV file?")
return files, []
def load_report(path, strip=""):
with open(path, encoding="utf-8", errors="replace") as fh:
text = fh.read()
head = text.lstrip()[:200]
if head.startswith("<"):
return parse_cobertura(text, strip)
return parse_lcov(text, strip)
def parse_diff(text, strip=""):
"""Return {path: set(added line numbers in the new file)} from a unified diff (git diff / git diff -U0)."""
changed, path, n = {}, None, None
for line in text.splitlines():
if line.startswith("+++ "):
p = line[4:].split("\t")[0].strip()
if p == "/dev/null":
path = None
continue
if p.startswith("b/"):
p = p[2:]
path = norm_path(p, strip)
changed.setdefault(path, set())
elif line.startswith("@@") and path is not None:
m = re.match(r"@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@", line)
n = int(m.group(1)) if m else None
elif path is not None and n is not None:
if line.startswith("+") and not line.startswith("+++"):
changed[path].add(n); n += 1
elif line.startswith("-") and not line.startswith("---"):
pass
elif line.startswith("\\"):
pass
else:
n += 1
return {p: s for p, s in changed.items() if s}
def ranges(nums):
out, start, prev = [], None, None
for x in sorted(nums):
if start is None:
start = prev = x
elif x == prev + 1:
prev = x
else:
out.append((start, prev)); start = prev = x
if start is not None:
out.append((start, prev))
return out
def fmt_ranges(rs, limit=8):
parts = ["%d" % a if a == b else "%d-%d" % (a, b) for a, b in rs]
more = len(parts) - limit
return ", ".join(parts[:limit]) + (" (+%d more)" % more if more > 0 else "")
def is_code_file(path):
return not re.search(r"\.(md|txt|json|ya?ml|toml|lock|cfg|ini|csv|svg|png|jpg|gif)$", path, re.I)
def is_test_file(path):
return bool(re.search(r"(^|/)(tests?|__tests__|spec)/|(^|/)test_[^/]+$|_test\.\w+$|\.(test|spec)\.\w+$", path))
def analyze(files, changed=None, opt=None):
o = dict(min_total=80.0, min_file=60.0, min_diff=80.0, min_lines=10, block=15, top=10, exclude=[])
o.update(opt or {})
files = {p: f for p, f in files.items() if not any(fnmatch.fnmatch(p, g) for g in o["exclude"])}
tot = sum(f.total for f in files.values()); cov = sum(f.covered for f in files.values())
btot = sum(f.branch_total for f in files.values()); bcov = sum(f.branch_covered for f in files.values())
rows = []
for p, f in sorted(files.items()):
rs = ranges(f.missed_lines)
biggest = max([b - a + 1 for a, b in rs], default=0)
rows.append(dict(file=p, lines=f.total, covered=f.covered, missed=f.total - f.covered,
pct=None if f.pct() is None else round(f.pct(), 1),
branch_pct=None if f.branch_pct() is None else round(f.branch_pct(), 1),
branches=f.branch_total, missed_ranges=rs, biggest_gap=biggest))
rows.sort(key=lambda r: (-r["missed"], r["file"]))
summary = dict(files=len(files), lines=tot, covered=cov,
line_pct=round(100.0 * cov / tot, 1) if tot else None,
branches=btot, branch_pct=round(100.0 * bcov / btot, 1) if btot else None)
flags = []
def flag(code, sev, msg, file=None):
flags.append(dict(code=code, severity=sev, file=file, message=msg))
if tot == 0:
flag("C08", "high", "the report contains no measured lines (wrong file, wrong paths, or tests did not run)")
elif summary["line_pct"] < o["min_total"]:
flag("C01", "medium", "total line coverage %.1f%% is below the %.0f%% target" % (summary["line_pct"], o["min_total"]))
for r in rows:
if r["lines"] >= o["min_lines"] and r["covered"] == 0:
flag("C07", "medium", "no line is covered (%d lines); the file may never be imported by tests" % r["lines"], r["file"])
elif r["lines"] >= o["min_lines"] and r["pct"] is not None and r["pct"] < o["min_file"]:
flag("C02", "low", "line coverage %.1f%% is below the per-file target %.0f%%" % (r["pct"], o["min_file"]), r["file"])
if r["biggest_gap"] >= o["block"] and r["covered"] > 0:
a, b = max(r["missed_ranges"], key=lambda x: x[1] - x[0])
flag("C05", "low", "uncovered block of %d lines (%d-%d)" % (b - a + 1, a, b), r["file"])
if r["branch_pct"] is not None and r["pct"] is not None and r["branches"] >= 4 and r["pct"] - r["branch_pct"] >= 25:
flag("C06", "low", "branch coverage %.1f%% is far below line coverage %.1f%%: lines run, but some if/else paths never do" % (r["branch_pct"], r["pct"]), r["file"])
diff = None
if changed is not None:
dfiles, dtot, dcov = [], 0, 0
for p, lines in sorted(changed.items()):
if any(fnmatch.fnmatch(p, g) for g in o["exclude"]) or not is_code_file(p):
continue
f = files.get(p)
if f is None:
if is_test_file(p):
continue
dfiles.append(dict(file=p, changed=len(lines), measurable=0, covered=0, pct=None, uncovered_ranges=[], in_report=False))
flag("C04", "medium", "changed file is not in the coverage report (new file without tests, or excluded from measurement)", p)
continue
meas = [n for n in lines if n in f.lines]
c = [n for n in meas if f.lines[n] > 0]
unc = ranges([n for n in meas if f.lines[n] == 0])
dtot += len(meas); dcov += len(c)
dfiles.append(dict(file=p, changed=len(lines), measurable=len(meas), covered=len(c),
pct=round(100.0 * len(c) / len(meas), 1) if meas else None, uncovered_ranges=unc, in_report=True))
diff = dict(files=dfiles, measurable=dtot, covered=dcov, pct=round(100.0 * dcov / dtot, 1) if dtot else None)
if diff["pct"] is not None and diff["pct"] < o["min_diff"]:
sev = "high" if diff["pct"] < o["min_diff"] / 2 else "medium"
flag("C03", sev, "diff coverage %.1f%% (%d of %d changed executable lines) is below the %.0f%% target" % (diff["pct"], dcov, dtot, o["min_diff"]))
if diff["measurable"] == 0 and not any(not d["in_report"] for d in dfiles):
flag("C09", "info", "no changed executable lines found in the report (docs/config-only change, or diff paths do not match report paths; try --strip-prefix)")
flags.sort(key=lambda x: (-SEV[x["severity"]], x["code"], x["file"] or ""))
return dict(summary=summary, files=rows, top=[r for r in rows if r["missed"]][:o["top"]], diff=diff, flags=flags, options=o)
def pct_s(v):
return " n/a" if v is None else "%5.1f%%" % v
def render_text(res):
s = res["summary"]; out = []
out.append("Coverage summary")
out.append(" Files %d, lines %d, covered %d -> line coverage %s" % (s["files"], s["lines"], s["covered"], pct_s(s["line_pct"]).strip()))
out.append(" Branches %d -> branch coverage %s" % (s["branches"], pct_s(s["branch_pct"]).strip()))
if res["diff"] is not None:
d = res["diff"]
out.append(" Diff coverage %s (%d of %d changed executable lines covered, %d files changed)" % (pct_s(d["pct"]).strip(), d["covered"], d["measurable"], len(d["files"])))
out.append("")
out.append("Files with the most missed lines (top %d)" % len(res["top"]))
for r in res["top"]:
out.append(" %-34s %s missed %3d/%-3d branch %s gaps %s" % (r["file"][:34], pct_s(r["pct"]), r["missed"], r["lines"], pct_s(r["branch_pct"]), fmt_ranges(r["missed_ranges"], 5)))
if res["diff"] is not None:
out.append("")
out.append("Changed lines")
for d in res["diff"]["files"]:
if not d["in_report"]:
out.append(" %-34s NOT IN REPORT (%d changed lines)" % (d["file"][:34], d["changed"]))
else:
out.append(" %-34s %s %d/%d covered uncovered %s" % (d["file"][:34], pct_s(d["pct"]), d["covered"], d["measurable"], fmt_ranges(d["uncovered_ranges"]) or "-"))
out.append("")
out.append("Findings (%d)" % len(res["flags"]))
for f in res["flags"]:
out.append(" [%s %s] %s%s" % (f["code"], f["severity"], (f["file"] + ": ") if f["file"] else "", f["message"]))
if not res["flags"]:
out.append(" none")
return "\n".join(out)
def render_md(res):
s = res["summary"]; out = ["# Coverage gaps", ""]
out.append("| Metric | Value |"); out.append("|---|---|")
out.append("| Line coverage | %s (%d/%d lines, %d files) |" % (pct_s(s["line_pct"]).strip(), s["covered"], s["lines"], s["files"]))
out.append("| Branch coverage | %s (%d branches) |" % (pct_s(s["branch_pct"]).strip(), s["branches"]))
if res["diff"] is not None:
d = res["diff"]
out.append("| Diff coverage | %s (%d/%d changed lines) |" % (pct_s(d["pct"]).strip(), d["covered"], d["measurable"]))
out += ["", "## Biggest gaps", "", "| File | Lines | Branches | Missed | Uncovered lines |", "|---|---|---|---|---|"]
for r in res["top"]:
if r["missed"]:
out.append("| `%s` | %s | %s | %d | %s |" % (r["file"], pct_s(r["pct"]).strip(), pct_s(r["branch_pct"]).strip(), r["missed"], fmt_ranges(r["missed_ranges"], 6)))
if res["diff"] is not None:
out += ["", "## Changed lines", "", "| File | Covered | Uncovered changed lines |", "|---|---|---|"]
for d in res["diff"]["files"]:
out.append("| `%s` | %s | %s |" % (d["file"], "not in report" if not d["in_report"] else "%d/%d" % (d["covered"], d["measurable"]), fmt_ranges(d["uncovered_ranges"]) or "-"))
out += ["", "## Findings", ""]
out += ["- **%s** (%s) %s%s" % (f["code"], f["severity"], ("`%s`: " % f["file"]) if f["file"] else "", f["message"]) for f in res["flags"]] or ["- none"]
return "\n".join(out)
def render_csv(res):
buf = io.StringIO(); w = csv.writer(buf, lineterminator="\n")
w.writerow(["file", "lines", "covered", "missed", "line_pct", "branch_pct", "biggest_gap", "uncovered_ranges"])
for r in sorted(res["files"], key=lambda r: r["file"]):
w.writerow([r["file"], r["lines"], r["covered"], r["missed"], "" if r["pct"] is None else r["pct"],
"" if r["branch_pct"] is None else r["branch_pct"], r["biggest_gap"], fmt_ranges(r["missed_ranges"], 1000)])
return buf.getvalue().rstrip("\n")
def to_json(res):
r = dict(res)
r["files"] = [dict(x, missed_ranges=[list(t) for t in x["missed_ranges"]]) for x in res["files"]]
r["top"] = [x["file"] for x in res["top"]]
if res["diff"] is not None:
r["diff"] = dict(res["diff"], files=[dict(x, uncovered_ranges=[list(t) for t in x["uncovered_ranges"]]) for x in res["diff"]["files"]])
return json.dumps(r, indent=2)
SAMPLE_XML = """<?xml version="1.0" ?>
<coverage version="7.4" line-rate="0.6" branch-rate="0.5">
<sources><source>/repo</source></sources>
<packages><package name="app"><classes>
<class name="a.py" filename="app/a.py"><lines>
<line number="1" hits="1"/><line number="2" hits="1"/><line number="3" hits="0"/>
<line number="4" hits="1" branch="true" condition-coverage="50% (1/2)"/><line number="5" hits="0"/>
</lines></class>
<class name="b.py" filename="app/b.py"><lines>
""" + "".join('<line number="%d" hits="0"/>' % i for i in range(1, 13)) + """
</lines></class>
</classes></package></packages>
</coverage>"""
SAMPLE_LCOV = """TN:
SF:src/x.js
DA:1,1
DA:2,0
DA:3,4
BRDA:3,0,0,1
BRDA:3,0,1,-
end_of_record
"""
SAMPLE_DIFF = """diff --git a/app/a.py b/app/a.py
--- a/app/a.py
+++ b/app/a.py
@@ -2,0 +3,3 @@ def f():
+ x = 1
+ if x:
+ return 2
diff --git a/app/new.py b/app/new.py
--- /dev/null
+++ b/app/new.py
@@ -0,0 +1,2 @@
+def g():
+ return 1
diff --git a/tests/test_a.py b/tests/test_a.py
--- a/tests/test_a.py
+++ b/tests/test_a.py
@@ -1,0 +2 @@
+ assert f() == 2
"""
def self_test():
checks = []
def ok(name, cond):
checks.append((name, bool(cond)))
files, _ = parse_cobertura(SAMPLE_XML)
ok("cobertura files", sorted(files) == ["app/a.py", "app/b.py"])
a = files["app/a.py"]
ok("cobertura line counts", (a.total, a.covered) == (5, 3))
ok("cobertura missed lines", a.missed_lines == [3, 5])
ok("cobertura branches", (a.branch_covered, a.branch_total) == (1, 2))
lf, _ = parse_lcov(SAMPLE_LCOV)
x = lf["src/x.js"]
ok("lcov lines", (x.total, x.covered) == (3, 2))
ok("lcov branches", (x.branch_covered, x.branch_total) == (1, 2))
ok("ranges", ranges([1, 2, 3, 7, 9, 10]) == [(1, 3), (7, 7), (9, 10)])
ok("fmt ranges", fmt_ranges([(1, 3), (7, 7)]) == "1-3, 7")
ch = parse_diff(SAMPLE_DIFF)
ok("diff added lines", ch.get("app/a.py") == {3, 4, 5})
ok("diff new file", ch.get("app/new.py") == {1, 2})
ok("diff strip prefix", parse_diff(SAMPLE_DIFF.replace("b/app/", "b/repo/app/"), "repo").get("app/a.py") == {3, 4, 5})
res = analyze(files, ch, dict(min_total=80, min_lines=10))
codes = {f["code"] for f in res["flags"]}
ok("total line pct", res["summary"]["line_pct"] == round(100 * 3 / 17, 1))
ok("C01 total below target", "C01" in codes)
ok("C07 untouched file", any(f["code"] == "C07" and f["file"] == "app/b.py" for f in res["flags"]))
ok("diff coverage 1 of 3", (res["diff"]["covered"], res["diff"]["measurable"]) == (1, 3))
ok("C03 diff below target", "C03" in codes)
ok("C04 new file not in report", any(f["code"] == "C04" and f["file"] == "app/new.py" for f in res["flags"]))
ok("test files ignored in diff", all(d["file"] != "tests/test_a.py" for d in res["diff"]["files"]))
ok("exclude glob", analyze(files, None, dict(exclude=["app/b.py"]))["summary"]["files"] == 1)
ok("empty report C08", any(f["code"] == "C08" for f in analyze({}, None)["flags"]))
ok("csv header", render_csv(res).splitlines()[0].startswith("file,lines,covered"))
ok("json roundtrip", json.loads(to_json(res))["summary"]["files"] == 2)
bad = [n for n, c in checks if not c]
if bad:
print("self-test FAILED: " + ", ".join(bad)); return 1
print("self-test OK: %d checks" % len(checks)); return 0
def main(argv=None):
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
ap.add_argument("report", nargs="?")
ap.add_argument("--diff")
ap.add_argument("--format", choices=["text", "md", "json", "csv"], default="text")
ap.add_argument("--min-total", type=float, default=80.0)
ap.add_argument("--min-file", type=float, default=60.0)
ap.add_argument("--min-diff", type=float, default=80.0)
ap.add_argument("--min-lines", type=int, default=10, help="ignore smaller files for C02/C07")
ap.add_argument("--block", type=int, default=15, help="uncovered block size for C05")
ap.add_argument("--top", type=int, default=10)
ap.add_argument("--exclude", action="append", default=[])
ap.add_argument("--strip-prefix", default="")
ap.add_argument("--fail-on", choices=["none"] + list(SEV), default="none")
ap.add_argument("--self-test", action="store_true")
a = ap.parse_args(argv)
if a.self_test:
return self_test()
if not a.report:
ap.print_usage(sys.stderr); return 2
try:
files, _ = load_report(a.report, a.strip_prefix)
changed = None
if a.diff:
with open(a.diff, encoding="utf-8", errors="replace") as fh:
changed = parse_diff(fh.read(), a.strip_prefix)
except (OSError, ValueError, ET.ParseError) as e:
print("error: %s" % e, file=sys.stderr); return 2
res = analyze(files, changed, dict(min_total=a.min_total, min_file=a.min_file, min_diff=a.min_diff,
min_lines=a.min_lines, block=a.block, top=a.top, exclude=a.exclude))
print({"text": render_text, "md": render_md, "json": to_json, "csv": render_csv}[a.format](res))
if a.fail_on != "none" and any(SEV[f["severity"]] >= SEV[a.fail_on] for f in res["flags"]):
return 1
return 0
if __name__ == "__main__":
sys.exit(main())
Turn any messy bug report, ticket, or log paste into a strict JSON triage card: clear title, environment, numbered repro steps, expected vs actual, redacted evidence, severity and priority with reasons, impact, labeled cause guess, questions for the reporter, and a regression test idea.
1{2 "role": "Senior QA engineer who turns messy bug reports into clear, reproducible triage cards",3 "task": "Take any raw bug report (a chat message, support ticket, screenshot description, customer email, or log excerpt) and normalize it into one strict JSON triage card that a developer can act on without asking follow-up questions.",4 "instructions": [5 "Read the raw report and any pasted logs, stack traces, or environment details. Separate facts the reporter stated from your own inferences.",6 "Never invent steps, versions, error messages, or log lines. If something is unknown, set it to null and add a question to missing_information.",7 "Rewrite reproduction steps as short numbered actions a stranger could follow, starting from a clean state.",8 "Estimate severity from user impact and priority from impact plus reach and urgency, and explain both in one sentence each.",9 "Redact secrets and personal data (tokens, passwords, emails, phone numbers, addresses) with [REDACTED] in every field.",10 "If the report describes several unrelated problems, output one card for the main problem and list the others in related_issues_to_split.",...+70 more lines
Opinionated preferences for writing fast, reliable automated tests in TypeScript and JavaScript projects.
# Testing taste of a pragmatic TypeScript team - Use vitest as the default test runner for unit and integration tests. Confidence: 0.90 - Keep test files next to the code they cover as *.test.ts. Confidence: 0.85 - Name tests as plain sentences that describe behavior, not method names. Confidence: 0.90 - Follow arrange, act, assert with a blank line between each phase. Confidence: 0.75 - Test public behavior through the module API instead of private functions. Confidence: 0.90 - Prefer real collaborators and in-memory fakes over mocks. Confidence: 0.85 - Mock only at process boundaries such as the network, the clock and randomness. Confidence: 0.90 - Intercept HTTP with msw instead of stubbing fetch by hand. Confidence: 0.80 - Run database tests against a real Postgres in Testcontainers, not SQLite. Confidence: 0.80 - Freeze time with fake timers and pass seeds to anything random. Confidence: 0.90 - Build test data with small factory functions that accept overrides. Confidence: 0.85 - Keep snapshot tests rare and small, and review every snapshot diff. Confidence: 0.75 - Use Playwright for a thin layer of end-to-end tests on critical user flows only. Confidence: 0.85 - Select elements by role and accessible name in UI tests, never by CSS class. Confidence: 0.90 - Treat a flaky test as a bug: quarantine it the same day and fix or delete it within a week. Confidence: 0.85 - Never use sleep in tests; wait for an explicit condition instead. Confidence: 0.95 - Keep the full unit suite under one minute on a laptop. Confidence: 0.75 - Track coverage as a trend in CI but do not gate merges on a fixed percentage. Confidence: 0.70 - Add property-based tests with fast-check for parsers and pure logic. Confidence: 0.65 - Write a failing regression test before fixing every reported bug. Confidence: 0.90 - Run tests in random order to catch hidden shared state. Confidence: 0.70