Coverage for scripts/coverage_badge.py: 100%
21 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-12 12:29 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-12 12:29 +0000
1"""Turn coverage.py's JSON report into a shields.io endpoint badge (ADR 0015).
3The docs workflow runs the tests on master, writes this next to the site and
4the HTML report, and the README badge reads it: the number on the badge is the
5number of the last run on master, never one typed in by hand.
6"""
8from __future__ import annotations
10import json
11import sys
12from pathlib import Path
14# Lowest total for each colour, highest first.
15COLOURS = ((100.0, "brightgreen"), (95.0, "green"), (90.0, "yellow"), (80.0, "orange"))
18def colour(percent: float) -> str:
19 return next((name for floor, name in COLOURS if percent >= floor), "red")
22def main(argv: list[str]) -> int:
23 if len(argv) != 2: # noqa: PLR2004
24 print("usage: coverage_badge.py <coverage.json> <badge.json>")
25 return 1
26 source, target = Path(argv[0]), Path(argv[1])
27 report = json.loads(source.read_text(encoding="utf-8"))
28 totals = report.get("totals") if isinstance(report, dict) else None
29 if not totals:
30 print(f"{source}: no totals; refusing to publish a badge without a measurement")
31 return 1
32 # coverage.py's own display rounding: it never shows 100 for 99.9.
33 badge = {
34 "schemaVersion": 1,
35 "label": "Code Coverage",
36 "message": f"{totals['percent_covered_display']}%",
37 "color": colour(totals["percent_covered"]),
38 # pytest's logo: the tests behind the number run under pytest, which
39 # drives coverage.py through pytest-cov; coverage.py has no logo of its
40 # own. A coverage service's logo would suggest one this project lacks.
41 "namedLogo": "pytest",
42 "logoColor": "white",
43 }
44 target.write_text(json.dumps(badge), encoding="utf-8")
45 print(f"{target}: coverage {badge['message']}")
46 return 0
49if __name__ == "__main__":
50 sys.exit(main(sys.argv[1:]))