Download tools/measure_coverage.py from tailot/codex-python: direct link, hf CLI and curl.
- Browser
- Download file 5.84 kB
-
https://huggingface.co/datasets/tailot/codex-python/resolve/main/tools/measure_coverage.py
- Command line
-
hf download hf://datasets/tailot/codex-python/tools/measure_coverage.py
-
curl -L -o measure_coverage.py https://huggingface.co/datasets/tailot/codex-python/resolve/main/tools/measure_coverage.py
5.84 kB
| """Count which functions of the package the test suite actually enters. | |
| The tool starts the suite once in a traced child process and records every | |
| function of lingologos_python that any test called. Functions no test enters | |
| stay dark, so a test can promise a floor for the lit share instead of a | |
| feeling. Only the standard library is used: the profile hook is the counter, | |
| and the syntax tree of the package is the denominator. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import ast | |
| import json | |
| import os | |
| import subprocess | |
| import sys | |
| import tempfile | |
| from pathlib import Path | |
| from typing import List, Set, Tuple | |
| ROOT = Path(__file__).resolve().parents[1] | |
| if str(ROOT) not in sys.path: | |
| sys.path.insert(0, str(ROOT)) | |
| sys.dont_write_bytecode = True | |
| PACKAGE_DIR = ROOT / "lingologos_python" | |
| DEFAULT_FLOOR = 90.0 | |
| def module_name(rel: Path) -> str: | |
| """Dotted module name a file inside the package answers to.""" | |
| parts = list(rel.with_suffix("").parts) | |
| if parts and parts[-1] == "__init__": | |
| parts = parts[:-1] | |
| return ".".join(["lingologos_python", *parts]) | |
| def definitions(path: Path) -> List[str]: | |
| """Qualnames of every function the file defines, in the form co_qualname uses.""" | |
| tree = ast.parse(path.read_text(encoding="utf-8", newline="")) | |
| found: List[str] = [] | |
| def walk(node: ast.AST, prefix: str) -> None: | |
| for child in ast.iter_child_nodes(node): | |
| if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef)): | |
| qual = child.name if not prefix else prefix + "." + child.name | |
| found.append(qual) | |
| walk(child, qual) | |
| elif isinstance(child, ast.ClassDef): | |
| walk(child, child.name) | |
| walk(tree, "") | |
| return found | |
| def package_files() -> List[Path]: | |
| return sorted(PACKAGE_DIR.rglob("*.py")) | |
| def run_child(report: Path) -> int: | |
| """Run the suite in this process while a profile hook records entered functions.""" | |
| # The suite carries a test that starts this tool; that test stands down | |
| # when it runs inside the traced child, so the measurement never nests. | |
| os.environ["LINGOLOGOS_COVERAGE_CHILD"] = "1" | |
| seen: Set[Tuple[str, str]] = set() | |
| package = str(PACKAGE_DIR) + os.sep | |
| def probe(frame, event, _argument): | |
| if event == "call": | |
| code = frame.f_code | |
| if code.co_filename.startswith(package): | |
| rel = Path(code.co_filename).relative_to(PACKAGE_DIR) | |
| seen.add((module_name(rel), code.co_qualname)) | |
| sys.setprofile(probe) | |
| import pytest | |
| status = int(pytest.main(["-q", "-p", "no:cacheprovider", "tests"])) | |
| sys.setprofile(None) | |
| report.write_text( | |
| json.dumps({"executed": sorted(seen)}, sort_keys=True) + "\n", | |
| encoding="utf-8", | |
| newline="\n", | |
| ) | |
| return status | |
| def summarize(child_report: Path) -> Tuple[float, int, int, List[str]]: | |
| """Percent of package functions the child entered, plus the dark list.""" | |
| payload = json.loads(child_report.read_text(encoding="utf-8")) | |
| executed = {(str(module), str(qual)) for module, qual in payload["executed"]} | |
| total = 0 | |
| lit = 0 | |
| dark: List[str] = [] | |
| for path in package_files(): | |
| module = module_name(path.relative_to(PACKAGE_DIR)) | |
| for qual in definitions(path): | |
| total += 1 | |
| if (module, qual) in executed: | |
| lit += 1 | |
| else: | |
| dark.append("%s::%s" % (module, qual)) | |
| percent = (100.0 * lit / total) if total else 0.0 | |
| return percent, lit, total, dark | |
| def main(argv: List[str] | None = None) -> int: | |
| parser = argparse.ArgumentParser( | |
| description="Measure how much of lingologos_python the test suite enters." | |
| ) | |
| parser.add_argument("--floor", type=float, default=DEFAULT_FLOOR, help="minimum percent to pass") | |
| parser.add_argument("--report", default=None, help="write the JSON summary here") | |
| parser.add_argument("--child", action="store_true", help=argparse.SUPPRESS) | |
| parser.add_argument("--child-report", default=None, help=argparse.SUPPRESS) | |
| args = parser.parse_args(argv) | |
| if args.child: | |
| child_report = Path(args.child_report or (Path(tempfile.mkdtemp()) / "child.json")) | |
| return run_child(child_report) | |
| env = dict(os.environ, LINGOLOGOS_COVERAGE_CHILD="1") | |
| with tempfile.TemporaryDirectory(prefix="lingologos_coverage_") as tmp_dir: | |
| child_report = Path(tmp_dir) / "child.json" | |
| status = subprocess.run( | |
| [sys.executable, "-B", str(Path(__file__).resolve()), "--child", | |
| "--child-report", str(child_report)], | |
| cwd=str(ROOT), | |
| env=env, | |
| stdout=subprocess.DEVNULL, | |
| stderr=subprocess.DEVNULL, | |
| ).returncode | |
| if not child_report.is_file(): | |
| print("coverage: the traced suite wrote no record (exit %d)" % status) | |
| return 1 | |
| percent, lit, total, dark = summarize(child_report) | |
| report = { | |
| "percent": round(percent, 2), | |
| "lit": lit, | |
| "total": total, | |
| "floor": args.floor, | |
| "dark": sorted(dark), | |
| } | |
| if args.report: | |
| target = Path(args.report) | |
| target.parent.mkdir(parents=True, exist_ok=True) | |
| target.write_text(json.dumps(report, sort_keys=True, indent=2) + "\n", encoding="utf-8", newline="\n") | |
| print("coverage: %d of %d functions entered (%.1f%%), floor %.1f%%" % (lit, total, percent, args.floor)) | |
| if status != 0: | |
| print("coverage: the traced suite exited %d, so the number describes a failing run" % status) | |
| return 1 | |
| if percent < args.floor: | |
| print("coverage: below the floor; %d functions never entered" % len(dark)) | |
| return 1 | |
| return 0 | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |