Download tools/measure_test_coverage.py from tailot/lingologos-thinkingpython: direct link, hf CLI and curl.
- Browser
- Download file 4.5 kB
-
https://huggingface.co/datasets/tailot/lingologos-thinkingpython/resolve/main/tools/measure_test_coverage.py
- Command line
-
hf download hf://datasets/tailot/lingologos-thinkingpython/tools/measure_test_coverage.py
-
curl -L -o measure_test_coverage.py https://huggingface.co/datasets/tailot/lingologos-thinkingpython/resolve/main/tools/measure_test_coverage.py
4.5 kB
| """How much of the package the test suite actually enters (acceptance D6). | |
| The suite runs in-process under a tracer. A function counts as entered when its code object | |
| is called; the number is the share of defined functions the suite reaches, reported per | |
| module so an untested module cannot hide behind a tested neighbour. Node processes are | |
| covered through their `main` entry, which the suite drives in-process as well. A function | |
| is identified by its name and the line its code object starts on, so a nested helper or a | |
| lambda can never be counted twice or credited to a neighbour. | |
| """ | |
| import argparse | |
| import ast | |
| import json | |
| import os | |
| import sys | |
| from typing import Dict, Set | |
| ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | |
| sys.path.insert(0, ROOT) | |
| RESULTS_DIR = os.path.join(ROOT, "results") | |
| TRACED_PACKAGES = ("lingologos_thinkingpython", "nodes") | |
| def defined_functions(directory: str) -> Dict[str, Set[str]]: | |
| """File -> the names of the functions defined in it, package files only.""" | |
| out: Dict[str, Set[str]] = {} | |
| for name in sorted(os.listdir(directory)): | |
| if not name.endswith(".py"): | |
| continue | |
| path = os.path.join(directory, name) | |
| rel = os.path.relpath(path, ROOT).replace(os.sep, "/") | |
| tree = ast.parse(open(path, "r", encoding="utf-8").read(), filename=path) | |
| keys = set() | |
| for node in ast.walk(tree): | |
| if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): | |
| # A decorated function starts its code object on the first decorator line. | |
| start = min([dec.lineno for dec in node.decorator_list] or [node.lineno]) | |
| keys.add("%s:%d" % (node.name, start)) | |
| elif isinstance(node, ast.Lambda): | |
| keys.add("<lambda>:%d" % node.lineno) | |
| out[rel] = keys | |
| return out | |
| def main(argv=None) -> int: | |
| parser = argparse.ArgumentParser(description="Measure suite coverage of the package.") | |
| parser.add_argument("--floor", type=float, default=0.90, | |
| help="minimum share of functions entered (D6 says 0.90)") | |
| parser.add_argument("--out", default=os.path.join(RESULTS_DIR, "test_coverage.json")) | |
| args = parser.parse_args(argv) | |
| defined: Dict[str, Set[str]] = {} | |
| for package in TRACED_PACKAGES: | |
| defined.update(defined_functions(os.path.join(ROOT, package))) | |
| total = sum(len(keys) for keys in defined.values()) | |
| entered: Set[str] = set() | |
| def tracer(frame, event, _arg): | |
| if event != "call": | |
| return tracer | |
| name = frame.f_code.co_filename | |
| if not name.startswith(ROOT): | |
| return tracer | |
| rel = os.path.relpath(name, ROOT).replace(os.sep, "/") | |
| entered.add("%s:%s:%d" % (rel, frame.f_code.co_name, frame.f_code.co_firstlineno)) | |
| return tracer | |
| import pytest # noqa: E402 | |
| sys.settrace(tracer) | |
| try: | |
| code = pytest.main(["-q", os.path.join(ROOT, "tests")]) | |
| finally: | |
| sys.settrace(None) | |
| per_module = {} | |
| hit_total = 0 | |
| for path, keys in sorted(defined.items()): | |
| hit = sum(1 for key in keys if path + ":" + key in entered) | |
| hit_total += hit | |
| per_module[path] = {"defined": len(keys), "entered": hit, | |
| "missing": sorted(key for key in keys | |
| if path + ":" + key not in entered)} | |
| share = round(hit_total / total, 4) if total else 0.0 | |
| report = {"functions_defined": total, "functions_entered": hit_total, | |
| "share": share, "floor": args.floor, "per_module": per_module, | |
| "pytest_exit": int(code)} | |
| os.makedirs(RESULTS_DIR, exist_ok=True) | |
| with open(args.out, "w", encoding="utf-8", newline="\n") as handle: | |
| json.dump(report, handle, indent=2, sort_keys=True) | |
| handle.write("\n") | |
| print("suite entered %d of %d functions (%.2f%%), floor %.0f%%" | |
| % (hit_total, total, share * 100, args.floor * 100)) | |
| for path, cell in sorted(per_module.items()): | |
| if cell["entered"] < cell["defined"]: | |
| print(" %s %d/%d %s" % (path, cell["entered"], cell["defined"], | |
| " ".join(cell["missing"]))) | |
| if code != 0: | |
| print("FAIL the suite did not pass") | |
| return 1 | |
| if share < args.floor: | |
| print("FAIL share %.2f%% under the floor" % (share * 100)) | |
| return 1 | |
| return 0 | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |