atlas-iac/testing/quality_coverage.py
2026-08-17 07:58:44 -03:00

119 lines
4.2 KiB
Python

"""Per-file coverage threshold validation for quality-managed modules."""
from __future__ import annotations
import xml.etree.ElementTree as ET
from dataclasses import dataclass
from pathlib import Path
from typing import Any
@dataclass(frozen=True)
class CoverageRates:
"""Line and branch percentages reported for one source file."""
line: float
branch: float | None
def _load_percentages(xml_path: Path, root: Path) -> dict[str, CoverageRates]:
"""Load per-file line and branch percentages from a Cobertura report."""
tree = ET.parse(xml_path)
xml_root = tree.getroot()
source_roots = [
Path(node.text) for node in xml_root.findall("./sources/source") if node.text
]
percentages: dict[str, CoverageRates] = {}
for class_node in xml_root.findall(".//class"):
filename = class_node.attrib.get("filename")
line_rate = class_node.attrib.get("line-rate")
branch_rate = class_node.attrib.get("branch-rate")
if not filename or line_rate is None:
continue
normalized = filename.replace("\\", "/")
if normalized.startswith("/"):
key = Path(normalized).relative_to(root).as_posix()
else:
key = normalized
for source_root in source_roots:
candidate = source_root / filename
if candidate.exists():
key = candidate.relative_to(root).as_posix()
break
percentages[key] = CoverageRates(
line=float(line_rate) * 100.0,
branch=float(branch_rate) * 100.0 if branch_rate is not None else None,
)
return percentages
def run_check(contract: dict[str, Any], root: Path, xml_path: Path) -> list[str]:
"""Return human-readable issues for tracked files below the coverage floor.
The report is intentionally per-file so a single weak module cannot hide
behind aggregate suite coverage.
"""
if not xml_path.exists():
return [f"coverage xml missing: {xml_path.relative_to(root)}"]
percentages = _load_percentages(xml_path, root)
minimum = float(contract.get("coverage", {}).get("minimum_percent", 95.0))
coverage_contract = contract.get("coverage", {})
branch_minimum = coverage_contract.get("minimum_branch_percent")
if branch_minimum is not None:
branch_minimum = float(branch_minimum)
branch_tracked = {
path.replace("\\", "/")
for path in coverage_contract.get(
"branch_tracked_files",
coverage_contract.get("tracked_files", [])
if branch_minimum is not None
else [],
)
}
issues: list[str] = []
for relative_path in contract.get("coverage", {}).get("tracked_files", []):
normalized = relative_path.replace("\\", "/")
rates = percentages.get(normalized)
if rates is None:
issues.append(f"coverage missing for tracked file: {relative_path}")
continue
if rates.line + 1e-9 < minimum:
issues.append(
f"coverage below {minimum:.1f}%: {relative_path} ({rates.line:.1f}%)"
)
if branch_minimum is None or normalized not in branch_tracked:
continue
if rates.branch is None:
issues.append(f"branch coverage missing for tracked file: {relative_path}")
elif rates.branch + 1e-9 < branch_minimum:
issues.append(
"branch coverage below "
f"{branch_minimum:.1f}%: {relative_path} ({rates.branch:.1f}%)"
)
return issues
def compute_workspace_line_coverage(
contract: dict[str, Any],
root: Path,
xml_path: Path,
) -> float:
"""Compute mean line coverage across tracked files present in the XML."""
if not xml_path.exists():
return 0.0
percentages = _load_percentages(xml_path, root)
samples: list[float] = []
for relative_path in contract.get("coverage", {}).get("tracked_files", []):
normalized = relative_path.replace("\\", "/")
rates = percentages.get(normalized)
if rates is not None:
samples.append(rates.line)
if not samples:
return 0.0
return round(sum(samples) / len(samples), 3)