Coverage for scripts/test_badge.py: 100%

37 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-22 12:55 +0000

1"""The README's test badge, from CI's JUnit report (V6.6.6, #358). 

2 

3 python scripts/test_badge.py junit.xml # print the summary line 

4 python scripts/test_badge.py junit.xml --badge site/badges/tests.json 

5 

6pages.yml publishes the badge beside the coverage badge after each green CI on main, so the count can't lag the suite. The badge 

7file is a shields.io endpoint document, the same shape as scripts/coverage_badge.py writes. 

8""" 

9 

10from __future__ import annotations 

11 

12import argparse 

13import json 

14import sys 

15import xml.etree.ElementTree as ET # nosec B405: parses the JUnit file this repository's own CI run wrote 

16from pathlib import Path 

17 

18 

19def counts(path: Path) -> dict[str, int]: 

20 """Totals over every <testsuite> in a pytest JUnit file: tests, failed (failures + errors), skipped and passed.""" 

21 root = ET.parse(path).getroot() # nosec B314: see the import 

22 suites = [root] if root.tag == "testsuite" else root.findall("testsuite") 

23 if not suites: 

24 raise ValueError(f"no <testsuite> in {path}") 

25 tests = sum(int(suite.get("tests", 0)) for suite in suites) 

26 failed = sum(int(suite.get("failures", 0)) + int(suite.get("errors", 0)) for suite in suites) 

27 skipped = sum(int(suite.get("skipped", 0)) for suite in suites) 

28 return {"tests": tests, "failed": failed, "skipped": skipped, "passed": tests - failed - skipped} 

29 

30 

31def badge(figures: dict[str, int], label: str = "tests") -> dict[str, object]: 

32 ran = figures["passed"] + figures["failed"] 

33 color = "brightgreen" if figures["failed"] == 0 and ran > 0 else "red" 

34 return {"schemaVersion": 1, "label": label, "message": f"{figures['passed']}/{ran} passing", "color": color} 

35 

36 

37def main(argv: list[str] | None = None) -> int: 

38 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) 

39 parser.add_argument("junit_xml") 

40 parser.add_argument("--badge", default=None, metavar="FILE") 

41 args = parser.parse_args(argv) 

42 try: 

43 figures = counts(Path(args.junit_xml)) 

44 except (OSError, ET.ParseError, ValueError) as error: 

45 print(f"no test figures: {error}", file=sys.stderr) 

46 return 1 

47 print(f"## tests: {figures['passed']} passed, {figures['failed']} failed, {figures['skipped']} skipped") 

48 if args.badge: 

49 target = Path(args.badge) 

50 target.parent.mkdir(parents=True, exist_ok=True) 

51 target.write_text(json.dumps(badge(figures)) + "\n", encoding="utf-8") 

52 return 0 

53 

54 

55if __name__ == "__main__": 

56 raise SystemExit(main())