Something went wrong. Try again.
Render line coverage from a Cobertura XML report
Something went wrong. Try again.
plugin-cobertura plugin.py
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172"""Render line coverage from a Cobertura XML report."""
from badger import ( entry, number, parse_xml, ratio, read_xml, threshold_color,)from badger import ( percentage as percentage_text,)
def _percentage(report: str) -> float | None: """Prefer exact counters; tolerate rounding in the optional reported rate.""" try: root = parse_xml(report) if isinstance(report, (str, bytes)) else report except ValueError as error: raise ValueError(f"invalid Cobertura XML: {error}") from error if root.tag.rsplit("}", 1)[-1].lower() != "coverage": raise ValueError("not a Cobertura report: missing <coverage> root element") reported = root.get("line-rate") if reported is not None: reported = number(float(reported) * 100, minimum=0, maximum=100) if "lines-covered" in root.attrib or "lines-valid" in root.attrib: try: actual = ratio( int(root.attrib["lines-covered"]), int(root.attrib["lines-valid"]) ) except (KeyError, ValueError) as error: raise ValueError("invalid Cobertura line counters") from error if actual is not None and reported is not None and abs(reported - actual) > 1: raise ValueError("Cobertura rate disagrees with line counters") return actual if reported is None: raise ValueError("Cobertura report has no line-rate or line counters") return reported
def _color(value): return threshold_color(value, ((90, "#2da44e"), (80, "#a4a61d"), (70, "#dfb317")))
def run(report: str = "coverage.xml") -> entry: """Render Cobertura line coverage with threshold-based color.
Args: report: path to the Cobertura XML report.
Examples: >>> cobertura(report="fixtures/high.xml") entry(label="coverage", status="95%", secondary_color="#2da44e") >>> cobertura(report="fixtures/middle.xml") entry(label="coverage", status="82%", secondary_color="#a4a61d") >>> cobertura(report="fixtures/low.xml") entry(label="coverage", status="42%", secondary_color="#d73a49") """ try: root = read_xml(report) except ValueError as error: raise ValueError(f"invalid Cobertura XML: {error}") from error percentage = _percentage(root) if percentage is None: return entry(label="coverage", status="no data", secondary_color="#6a737d") return entry( label="coverage", status=percentage_text(percentage), secondary_color=_color(percentage), )