diff options
Diffstat (limited to 'plugins/code-modernization/scripts')
| -rw-r--r-- | plugins/code-modernization/scripts/baseline_diff.py | 346 | ||||
| -rw-r--r-- | plugins/code-modernization/scripts/build_report.py | 57 | ||||
| -rw-r--r-- | plugins/code-modernization/scripts/proof_pack.py | 246 | ||||
| -rw-r--r-- | plugins/code-modernization/scripts/tests/test_proof_tools.py | 587 | ||||
| -rw-r--r-- | plugins/code-modernization/scripts/uplift_checks.py | 356 |
5 files changed, 1460 insertions, 132 deletions
diff --git a/plugins/code-modernization/scripts/baseline_diff.py b/plugins/code-modernization/scripts/baseline_diff.py index ccbb2713..93686737 100644 --- a/plugins/code-modernization/scripts/baseline_diff.py +++ b/plugins/code-modernization/scripts/baseline_diff.py @@ -13,6 +13,11 @@ Baseline, any of these (the most detailed one found is used): a totals table | Executed | 946 |, | Passed | 945 |, | Failed | 1 | ... a line target-only: <why the old version could not run here> (nothing to compare) +Measured or typed: a baseline typed by hand proves nothing about the old version. The old version's own evidence is looked for in +analysis/<system>/baseline/ and at the paths on a "Recorded:" or "Machine-readable:" line of BASELINE.md inside analysis/<system>/ (JUnit or .trx XML, a per-test JSON map of test ids to +outcomes, or a raw runner log with a known summary line; a file that only holds counts is ignored, and sources that disagree are a conflict). When it exists, it is what the fresh results are compared with, +and the typed table must agree with it; when it does not, the report says "typed table only". + Fresh results: JUnit-style XML (Maven surefire, Gradle, pytest --junitxml, Ant, jest-junit ...) or Visual Studio .trx files. Give a file or a folder; a folder is searched for result files, links are never followed, and a file that declares a DTD or entity is refused. A test id is @@ -31,6 +36,7 @@ import argparse import json import os import re +import stat import sys from xml.parsers import expat @@ -55,6 +61,20 @@ class InputError(Exception): pass +def read_capped(path, cap): + """Bytes of a regular file inside the size cap; raises InputError with a plain reason for a link, a huge file or an unreadable one.""" + try: + st = os.lstat(path) + if not stat.S_ISREG(st.st_mode): + raise InputError("%s is a link or not a regular file" % clean(os.path.basename(path), 80)) + if st.st_size > cap: + raise InputError("%s is larger than %d MB" % (clean(os.path.basename(path), 80), cap >> 20)) + with open(path, "rb") as fh: + return fh.read() + except OSError as err: + raise InputError("cannot read %s (%s)" % (clean(os.path.basename(path), 80), err.__class__.__name__)) + + # ---------------------------------------------------------------- the baseline def cell(text): text = text.replace("\\|", "|").strip() @@ -309,6 +329,302 @@ def read_results(paths): return out +# ---------------------------------------------------------------- raw runner logs (a saved run's own summary lines) +LOG_CAP, LOG_LINE = 16 << 20, 2000 +NUM_WORD = re.compile(r"(\d+)\s+([A-Za-z]+)") + + +def words(text): + """{'passed': 10, 'failed': 2} from '2 failed, 10 passed' style text.""" + out = {} + for n, w in NUM_WORD.findall(text[:LOG_LINE]): + out[w.lower()] = out.get(w.lower(), 0) + int(n) + return out + + +def _maven(m): + run, f, e, sk = (int(g) for g in m.groups()) + return max(0, run - f - e - sk), f + e, sk + + +def _pytest(m): + w = words(m.group(1)) + return w.get("passed", 0) + w.get("xpassed", 0) + w.get("xfailed", 0), w.get("failed", 0) + w.get("error", 0) + w.get("errors", 0), w.get("skipped", 0) + + +def _jest(m): + w = words(m.group(1)) + return w.get("passed", 0), w.get("failed", 0), w.get("skipped", 0) + + +def _php(m): + w = {k.lower(): int(v) for k, v in re.findall(r"([A-Za-z]+):\s*(\d+)", m.group(1)[:LOG_LINE])} + failed, skipped = w.get("failures", 0) + w.get("errors", 0), w.get("skipped", 0) + w.get("incomplete", 0) + return max(0, w.get("tests", 0) - failed - skipped), failed, skipped + + +def _ctest(m): + failed, total = int(m.group(1)), int(m.group(2)) + return max(0, total - failed), failed, 0 + + +def _gradle(m): + total, failed, skipped = int(m.group(1)), int(m.group(2) or 0), int(m.group(3) or 0) + return max(0, total - failed - skipped), failed, skipped + + +# runner, a line pattern, and how to read (passed, failed, skipped) from a match. Every pattern is anchored and bounded. +LOG_LINES = ( + ("maven", re.compile(r"^(?:\[\w+\]\s*)?Tests run: (\d+), Failures: (\d+), Errors: (\d+), Skipped: (\d+)\s*$"), _maven), + ("gradle", re.compile(r"^(\d+) tests? completed(?:, (\d+) failed)?(?:, (\d+) skipped)?\s*$"), _gradle), + ("cargo", re.compile(r"^test result: (?:ok|FAILED)\. (\d+) passed; (\d+) failed; (\d+) ignored;"), lambda m: (int(m.group(1)), int(m.group(2)), int(m.group(3)))), + ("pytest", re.compile(r"^(?:=+ )?((?:\d+ [a-z]+(?:, )?)+) in [\d.]+s(?: \([\d:]+\))?(?: =+)?\s*$"), _pytest), + ("pytest", re.compile(r"^(?:=+ )?no tests ran in [\d.]+s"), lambda m: (0, 0, 0)), + ("go test", re.compile(r"^\s*--- (PASS|FAIL|SKIP): \S"), lambda m: {"PASS": (1, 0, 0), "FAIL": (0, 1, 0), "SKIP": (0, 0, 1)}[m.group(1)]), + ("go test -json", re.compile(r'^\{.*"Action":"(pass|fail|skip)".*"Test":"[^"]+"'), lambda m: {"pass": (1, 0, 0), "fail": (0, 1, 0), "skip": (0, 0, 1)}[m.group(1)]), + ("dotnet test", re.compile(r"^(?:Passed|Failed)!\s+-\s+Failed:\s+(\d+),\s+Passed:\s+(\d+),\s+Skipped:\s+(\d+)"), lambda m: (int(m.group(2)), int(m.group(1)), int(m.group(3)))), + ("jest", re.compile(r"^\s*Tests:\s+(.*\b\d+ total)\s*$"), _jest), + ("vitest", re.compile(r"^\s*Tests\s{2,}(.*)\(\d+\)\s*$"), _jest), + ("ctest", re.compile(r"^\d+% tests passed, (\d+) tests? failed out of (\d+)"), _ctest), + ("phpunit", re.compile(r"^OK \((\d+) tests?, \d+ assertions?\)"), lambda m: (int(m.group(1)), 0, 0)), + ("phpunit", re.compile(r"^(Tests: \d+, Assertions: \d+.*?)\.?\s*$"), _php), +) +UNITTEST_RAN = re.compile(r"^Ran (\d+) tests? in [\d.]+s\s*$") +UNITTEST_END = re.compile(r"^(?:OK|FAILED)(?: \(([^)]*)\))?\s*$") + + +def parse_runner_log(text): + """(executed, failed, skipped, runners) from the runner's own summary lines, summed over the log; None when no line is recognised. + Recognised: Maven/Gradle, cargo, pytest, unittest, go test (-v or -json), dotnet test, jest, vitest, ctest, phpunit.""" + passed = failed = skipped = 0 + seen, ran = [], None + for line in text.split("\n")[:3000000]: + line = line.rstrip("\r")[:LOG_LINE] + if ran is not None and line.strip(): + m = UNITTEST_END.match(line) + if m: + w = {k: int(v) for k, v in re.findall(r"(\w+)=(\d+)", (m.group(1) or "")[:LOG_LINE])} + f, sk = w.get("failures", 0) + w.get("errors", 0), w.get("skipped", 0) + passed, failed, skipped = passed + max(0, ran - f - sk), failed + f, skipped + sk + seen.append("unittest") + ran = None + m = UNITTEST_RAN.match(line) + if m: + ran = int(m.group(1)) + continue + for name, rx, read in LOG_LINES: + m = rx.match(line) + if m: + p, f, sk = read(m) + passed, failed, skipped = passed + p, failed + f, skipped + sk + seen.append(name) + break + return (passed + failed, failed, skipped, sorted(set(seen))) if seen else None + + +def read_logs(paths): + """Saved runner logs -> {"files", "executed", "failed", "skipped", "runners", "oldest", "newest", "unrecognised"}. A log without a summary line of a known runner is no evidence.""" + out = {"files": 0, "executed": 0, "failed": 0, "skipped": 0, "runners": [], "oldest": None, "newest": None, "unrecognised": []} + for path in paths: + try: + st = os.lstat(path) + if not stat.S_ISREG(st.st_mode) or st.st_size > LOG_CAP: + out["unrecognised"].append("%s (a link, not a file, or larger than %d MB)" % (clean(os.path.basename(path), 80), LOG_CAP >> 20)) + continue + with open(path, "rb") as fh: + got = parse_runner_log(fh.read(LOG_CAP).decode("utf-8", "replace")) + except OSError: + out["unrecognised"].append("%s (could not be read)" % clean(os.path.basename(path), 80)) + continue + if got is None: + out["unrecognised"].append("%s (no summary line of a runner this script knows)" % clean(os.path.basename(path), 80)) + continue + out["files"] += 1 + out["executed"], out["failed"], out["skipped"] = out["executed"] + got[0], out["failed"] + got[1], out["skipped"] + got[2] + out["runners"] = sorted(set(out["runners"]) | set(got[3])) + out["oldest"] = st.st_mtime if out["oldest"] is None else min(out["oldest"], st.st_mtime) + out["newest"] = st.st_mtime if out["newest"] is None else max(out["newest"], st.st_mtime) + return out + + +# ---------------------------------------------------------------- measured baselines: result files, raw logs, machine-readable results +EVIDENCE_EXT = (".xml", ".trx", ".json", ".txt", ".log", ".out") +PATH_TOKEN = re.compile(r"[A-Za-z0-9_.@+~-]+(?:/[A-Za-z0-9_.@+~-]+)*/?") + + +RECORDED = re.compile(r"^[ \t>*-]*\**[ \t]*(?:recorded|machine-readable)\b[^:\n]{0,40}:", re.I) + + +def evidence_paths(baseline_path, text): + """Where the old version's measured results are kept: the folder analysis/<system>/baseline/, and the paths on a line of BASELINE.md + that starts with "Recorded:" or "Machine-readable:" (a folder, or a file ending in .xml .trx .json .txt .log .out). Paths mentioned + anywhere else in the file are prose, not evidence. A path with a `..`, a link anywhere below the analysis folder, or a place outside + analysis/<system>/ is never used. -> the existing paths, at most 50.""" + adir = os.path.dirname(os.path.abspath(baseline_path)) + system, real_adir, found, seen = os.path.basename(adir), os.path.realpath(adir), [], set() + + def add(comps): + cur = adir + for c in comps: + cur = os.path.join(cur, c) + if os.path.islink(cur): + return + if not os.path.lexists(cur): + return + real = os.path.realpath(cur) + try: + ok = os.path.commonpath([real_adir, real]) == real_adir + except ValueError: + ok = False + if ok and real not in seen and (os.path.isdir(cur) or os.path.isfile(cur)): + seen.add(real) + found.append(cur) + + add(["baseline"]) + for line in text.split("\n")[:20000]: + if not RECORDED.match(line[:4000]): + continue + for m in PATH_TOKEN.finditer(line[:4000]): + tok = m.group(0) + if not (tok.lower().endswith(EVIDENCE_EXT) or tok.endswith("/")): + continue + comps = [c for c in tok.split("/") if c] + if comps and comps[0] == "analysis": + comps = comps[2:] if len(comps) >= 3 and comps[1] == system else [] + if comps and not any(c in (".", "..") for c in comps): + add(comps) + if len(found) >= 50: + return found + return found + + +def parse_results_json(data): + """{test id: status} from a machine-readable per-test results document, or None. Recognised: {"test id": "PASS", ...}, {"tests": ...} + and [{"name": ..., "status": ...}, ...]. A document that only holds counts ({"PASS": 10, "FAIL": 1}) is not evidence of any test: anyone + can type one, so it is ignored.""" + def status(v): + return STATUS.get(re.sub(r"[^a-z]", "", v.lower())) if isinstance(v, str) else None + + obj = data["tests"] if isinstance(data, dict) and isinstance(data.get("tests"), (dict, list)) else data + tests = {} + if isinstance(obj, dict): + items = list(obj.items())[:MAX_CASES] + good = {str(k)[:400]: status(v) for k, v in items if status(v)} + if good and len(good) >= 0.9 * len(items): + tests = good + elif isinstance(obj, list): + for e in obj[:MAX_CASES]: + if isinstance(e, dict): + name = next((e[k] for k in ("test", "id", "name", "fullName", "fullname") if isinstance(e.get(k), str) and e[k]), None) + st = next((status(e[k]) for k in ("status", "result", "outcome") if status(e.get(k))), None) + if name and st: + tests.setdefault(name[:400], st) + return tests or None + + +def read_baseline_evidence(paths): + """Read what evidence_paths found: JUnit/TRX XML, machine-readable per-test JSON, and raw runner logs with a known summary line. + Two sources that disagree are reported as conflicts, never resolved by taking the first. + -> {"tests": {id: status} or None, "counts": {...} or None (a log alone), "sources", "considered", "ignored", "unreadable", "conflicts", "measured"}.""" + out = {"tests": None, "counts": None, "sources": [], "considered": [], "ignored": [], "unreadable": [], "conflicts": [], "measured": False} + files = [] + for p in paths: + if os.path.islink(p): + continue + if os.path.isdir(p): + for base, dirs, names in os.walk(p, followlinks=False): + dirs[:] = [d for d in sorted(dirs) if d not in SKIP_DIRS and not os.path.islink(os.path.join(base, d))] + files += [os.path.join(base, n) for n in sorted(names) if n.lower().endswith(EVIDENCE_EXT) and not os.path.islink(os.path.join(base, n))] + if len(files) >= 2000: + break + elif p.lower().endswith(EVIDENCE_EXT): + files.append(p) + files = files[:2000] + out["considered"] = [clean(os.path.basename(f), 80) for f in files[:20]] + cat = lambda st: "BAD" if st in BAD else st # noqa: E731 + tests, conflicts = {}, [] + + def merge(more, label): + for k, v in more.items(): + if k not in tests: + tests[k] = v + elif cat(tests[k]) != cat(v): + conflicts.append("%s: %s in one source, %s in %s" % (clean(k, 100), tests[k], v, label)) + + xml = [f for f in files if f.lower().endswith((".xml", ".trx"))] + if xml: + got = read_results(xml) + out["unreadable"] += got["unreadable"][:5] + if got["files"]: + merge(got["tests"], "the result files") + out["sources"].append({"kind": "result files", "files": got["files"], "tests": len(got["tests"])}) + for f in [f for f in files if f.lower().endswith(".json")]: + name = clean(os.path.basename(f), 80) + try: + t = parse_results_json(json.loads(read_capped(f, MAX_FILE).decode("utf-8-sig"))) + except (InputError, ValueError, RecursionError) as err: + out["unreadable"].append("%s: %s" % (name, clean(err, 100))) + continue + if t: + merge(t, name) + out["sources"].append({"kind": "machine-readable results", "files": 1, "tests": len(t), "name": name}) + else: + out["ignored"].append(name) # counts only, or no test entries: nothing that can be checked test by test + logs = read_logs([f for f in files if f.lower().endswith((".txt", ".log", ".out"))]) + if logs["files"]: + out["sources"].append({"kind": "runner log", "files": logs["files"], "executed": logs["executed"], "runners": logs["runners"]}) + if tests: + c = tally(tests.values()) + if c["executed"] != logs["executed"] or c["fail"] + c["error"] != logs["failed"]: + conflicts.append("the runner log says %d executed and %d failed; the per-test results say %d and %d" % (logs["executed"], logs["failed"], c["executed"], c["fail"] + c["error"])) + out["tests"] = tests or None + out["counts"] = {"executed": logs["executed"], "failed": logs["failed"], "skipped": logs["skipped"]} if logs["files"] and not tests else None + out["conflicts"] = conflicts[:20] + out["measured"] = bool(tests or out["counts"]) + return out + + +def assess_baseline(base, measured): + """Is BASELINE.md measured or only typed? -> {"kind": "target-only" | "measured" | "typed" | "none", "sources", "disagree", "examples", ...}. + A typed table is measured only when a result file, a machine-readable results file or a raw log that this script parsed backs it, and + agrees with it (the same tests with the same outcomes, or the same executed and failed counts).""" + typed = bool(base["tests"] or base["modules"] or base["totals"]) + info = {"kind": "typed" if typed else "none", "sources": [], "disagree": 0, "examples": [], "conflict": 0, "conflictExamples": [], "considered": list((measured or {}).get("considered", []))[:20], + "ignored": list((measured or {}).get("ignored", []))[:10], "unreadable": list((measured or {}).get("unreadable", []))[:5], "measuredTests": 0, + "measuredExecuted": None, "measuredFailed": None} + if base["targetOnly"]: + info["kind"] = "target-only" + return info + if not measured or not measured["measured"]: + return info + info["kind"], info["sources"] = "measured", list(measured["sources"])[:10] + info["conflict"] = len(measured.get("conflicts", [])) + info["conflictExamples"] = [clean(c, 200) for c in measured.get("conflicts", [])[:3]] + cat = lambda st: "BAD" if st in BAD else st # noqa: E731 + typed_counts, _ = baseline_counts(base) + if measured["tests"] is not None: + c = tally(measured["tests"].values()) + info.update(measuredTests=len(measured["tests"]), measuredExecuted=c["executed"], measuredFailed=c["fail"] + c["error"]) + if base["tests"]: + bad = [t for t, st in base["tests"].items() if cat(measured["tests"].get(t, "")) != cat(st)] + info["disagree"], info["examples"] = len(bad), [clean(t, 120) for t in bad[:5]] + elif typed_counts and (typed_counts["executed"] != c["executed"] or typed_counts["fail"] + typed_counts["error"] != c["fail"] + c["error"]): + info["disagree"], info["examples"] = 1, ["typed: %d executed, %d failed; measured: %d executed, %d failed" % ( + typed_counts["executed"], typed_counts["fail"] + typed_counts["error"], c["executed"], c["fail"] + c["error"])] + else: + m = measured["counts"] + info.update(measuredExecuted=m["executed"], measuredFailed=m["failed"]) + if typed_counts and (typed_counts["executed"] != m["executed"] or typed_counts["fail"] + typed_counts["error"] != m["failed"]): + info["disagree"], info["examples"] = 1, ["typed: %d executed, %d failed; measured: %d executed, %d failed" % ( + typed_counts["executed"], typed_counts["fail"] + typed_counts["error"], m["executed"], m["failed"])] + totals = base["totals"] # a Totals table typed beside the rows must say what the evidence says + ex, fl = info["measuredExecuted"], info["measuredFailed"] + if totals and ex is not None and (("executed" in totals and totals["executed"] != ex) or (("fail" in totals or "error" in totals) and totals.get("fail", 0) + totals.get("error", 0) != fl)): + info["disagree"] += 1 + info["examples"].append("the Totals table says %s executed and %s failed; measured: %d and %d" % (totals.get("executed", "?"), totals.get("fail", 0) + totals.get("error", 0), ex, fl)) + return info + + # ---------------------------------------------------------------- the comparison def keep(items): return items[:KEEP] @@ -318,7 +634,9 @@ def compare(base, fresh): """-> the report dict (see the module docstring).""" counts_b, source = baseline_counts(base) counts_f = tally(fresh["tests"].values()) - rep = {"baseline": {"targetOnly": base["targetOnly"], "why": base["why"], "source": source, "counts": counts_b}, + if base.get("measuredTests"): + source = "measured results" + rep = {"baseline": {"targetOnly": base["targetOnly"], "why": base["why"], "source": source, "counts": counts_b, "assessment": base.get("assessment")}, "fresh": {"files": fresh["files"], "counts": counts_f, "unreadable": fresh["unreadable"][:20], "unreadableCount": len(fresh["unreadable"]), "oldest": fresh["oldest"], "newest": fresh["newest"]}, "regressions": [], "flaky": [], "newFailures": [], "stillFailing": [], "fixed": [], "newlySkipped": [], "missing": [], "renamed": 0, @@ -401,6 +719,16 @@ def render(rep, limit=10): "this run (%d result file(s)): %s" % (rep["fresh"]["files"], show(f))] if rep["baseline"]["targetOnly"]: lines.append("BASELINE.md says target-only (%s): there is no old-version result to compare with." % (rep["baseline"]["why"] or "no reason given")) + a = rep["baseline"].get("assessment") + if a and a["kind"] == "measured": + lines.append("baseline evidence: measured (%s)" % "; ".join("%s%s" % (s["kind"], " %s" % s["name"] if s.get("name") else "") for s in a["sources"][:4])) + if a["conflict"]: + lines.append(" but the sources disagree with each other: %s" % "; ".join(a["conflictExamples"][:3])) + elif a["disagree"]: + lines.append(" but the typed table disagrees with it on %d test(s): %s" % (a["disagree"], "; ".join(a["examples"][:3]))) + elif a and a["kind"] == "typed": + lines.append("baseline evidence: typed table only. No result file, per-test results file or raw log that this script can read was found in analysis/<system>/baseline/ or on a Recorded: or Machine-readable: line of BASELINE.md.%s" % ( + " Ignored (counts only): " + ", ".join(a["ignored"][:3]) if a["ignored"] else "")) def block(title, key, fmt=lambda x: clean(x, 160)): if rep[key + "Count"]: @@ -433,8 +761,10 @@ def render(rep, limit=10): return "\n".join(lines) -def run(baseline_path, paths): - """-> the report. Raises InputError for a baseline or results that cannot be used.""" +def run(baseline_path, paths, measured="auto"): + """-> the report. Raises InputError for a baseline or results that cannot be used. `measured` is the old version's own evidence + (from read_baseline_evidence); by default it is looked for beside BASELINE.md (see evidence_paths). Measured per-test results, + when there are any, are what the fresh results are compared with; the typed table is only checked against them.""" if os.path.islink(baseline_path): raise InputError("%s is a symbolic link" % baseline_path) try: @@ -445,6 +775,12 @@ def run(baseline_path, paths): base = parse_baseline(text) if not (base["targetOnly"] or base["modules"] or base["tests"] or base["totals"]): raise InputError("%s has no per-test table, per-module table, totals or target-only line that can be read" % baseline_path) + if measured == "auto": + found = evidence_paths(baseline_path, text) + measured = read_baseline_evidence(found) if found else None + base["assessment"] = assess_baseline(base, measured) + if base["assessment"]["kind"] == "measured" and measured["tests"]: + base["tests"], base["measuredTests"] = measured["tests"], True return compare(base, read_results(paths)) @@ -452,6 +788,8 @@ def main(argv=None): ap = argparse.ArgumentParser(description="Compare a fresh test run with BASELINE.md.") ap.add_argument("baseline", help="analysis/<system>/BASELINE.md") ap.add_argument("--junit", "--trx", action="append", default=[], metavar="PATH", help="a results file or a folder to search (repeat for several)") + ap.add_argument("--baseline-evidence", action="append", default=[], metavar="PATH", + help="a file or folder with the old version's own results (XML, JSON map, raw log); default: analysis/<system>/baseline/ and the paths BASELINE.md names") ap.add_argument("--json", action="store_true", help="print the full report as JSON") ap.add_argument("--max-list", type=int, default=10, help="how many entries to print per list (default 10)") args = ap.parse_args(argv) @@ -459,7 +797,7 @@ def main(argv=None): print("baseline_diff.py: give at least one --junit file or folder", file=sys.stderr) return 2 try: - rep = run(args.baseline, args.junit) + rep = run(args.baseline, args.junit, read_baseline_evidence(args.baseline_evidence) if args.baseline_evidence else "auto") except InputError as err: print("baseline_diff.py: %s" % err, file=sys.stderr) return 2 diff --git a/plugins/code-modernization/scripts/build_report.py b/plugins/code-modernization/scripts/build_report.py index c86c6298..942bb2ab 100644 --- a/plugins/code-modernization/scripts/build_report.py +++ b/plugins/code-modernization/scripts/build_report.py @@ -321,6 +321,8 @@ def equivalence_view(obj): # ---------------------------------------------------------------- the proof pack (VERIFICATION.json) PROOF_VERDICTS = ("PROVEN", "PARTLY PROVEN", "NOT PROVEN") PROOF_CHECKS = (("tests", "Tests ran"), ("rules", "Rules traced"), ("same", "Same behavior"), ("fresh", "Fresh inputs"), ("canary", "Canary"), ("source", "Source untouched")) +UPLIFT_CHECKS = (("baseline", "Baseline measured"), ("kept", "Tests kept"), ("deltas", "Deltas covered")) # an uplift has these three as well +KEPT_SHARE = 0.25 RULE_STATES = ("tested", "claimed only", "code only", "none") FRESH_NEEDED = 10 @@ -351,14 +353,42 @@ def counts_of(obj, keys): return {k: count_of(obj.get(k)) for k in keys} +def uplift_view(ev): + """The uplift-only evidence of a pack, made safe: the baseline's assessment, the test files that changed, and the deltas no test names.""" + bev, tc, dc = ev.get("baselineEvidence"), ev.get("testsChanged"), ev.get("deltas") + if not any(isinstance(x, dict) for x in (bev, tc, dc)): + return {"baseline": None, "testsChanged": None, "deltas": None} + files = lambda xs, keys: [dict({"path": text_of(x.get("path"), 300)}, **{k: count_of(x.get(k)) for k in keys}, note=text_of(x.get("note"), 80)) for x in (xs if isinstance(xs, list) else [])[:40] if isinstance(x, dict)] # noqa: E731 + listed = lambda xs: [{"id": text_of(x.get("id"), 40), "title": text_of(x.get("title"), 200), "why": text_of(x.get("why"), 200), "sites": texts_of(x.get("sites"), 200, 5)} for x in (xs if isinstance(xs, list) else [])[:40] if isinstance(x, dict)] # noqa: E731 + out = {"baseline": None, "testsChanged": None, "deltas": None} + if isinstance(bev, dict): + out["baseline"] = {"kind": bev.get("kind") if bev.get("kind") in ("measured", "typed", "target-only", "none") else "none", "disagree": count_of(bev.get("disagree")), "conflict": count_of(bev.get("conflict")), + "sources": [{"kind": text_of(x.get("kind"), 40), "name": text_of(x.get("name"), 80), "tests": count_of(x.get("tests")), "executed": count_of(x.get("executed"))} + for x in (bev.get("sources") if isinstance(bev.get("sources"), list) else [])[:10] if isinstance(x, dict)], + "examples": texts_of(bev.get("examples"), 200, 5), "conflictExamples": texts_of(bev.get("conflictExamples"), 200, 5), "considered": texts_of(bev.get("considered"), 80, 10), "ignored": texts_of(bev.get("ignored"), 80, 10)} + if isinstance(tc, dict): + counts = counts_of(tc.get("counts"), ("added", "removed", "changed")) + out["testsChanged"] = {"checked": tc.get("checked") is True, "why": text_of(tc.get("why"), 300), "legacyTests": count_of(tc.get("legacyTests")), "workTests": count_of(tc.get("workTests")), + "counts": counts, "share": num_of(tc.get("share")), "removed": files(tc.get("removed"), ("lines",)), "added": files(tc.get("added"), ("lines",)), + "changed": files(tc.get("changed"), ("added", "removed"))} + if isinstance(dc, dict): + unc = listed(dc.get("uncovered")) + out["deltas"] = {"parsed": count_of(dc.get("parsed")), "silent": count_of(dc.get("silent")), "coveredCount": len(dc["covered"]) if isinstance(dc.get("covered"), list) else 0, + "uncoveredCount": max(len(unc), len(dc["uncovered"]) if isinstance(dc.get("uncovered"), list) else 0), "uncovered": unc, "config": listed(dc.get("config")), "why": text_of(dc.get("why"), 300)} + return out + + def proof_module(m, problems): """One module of VERIFICATION.json, made safe, with its verdict recomputed from its own checks: the file's word is never taken.""" name = text_of(m.get("name"), 120) or "(unnamed)" ev = m["evidence"] if isinstance(m.get("evidence"), dict) else {} + track = text_of(m.get("track"), 20) + required = PROOF_CHECKS + (UPLIFT_CHECKS if track == "uplift" else ()) + known = dict(PROOF_CHECKS + UPLIFT_CHECKS) by_id = {} for c in (m["checks"] if isinstance(m.get("checks"), list) else [])[:20]: - if isinstance(c, dict) and c.get("id") in dict(PROOF_CHECKS) and c.get("state") in ("pass", "gap", "fail", "na") and c["id"] not in by_id: - by_id[c["id"]] = {"id": c["id"], "label": dict(PROOF_CHECKS)[c["id"]], "state": c["state"], "detail": text_of(c.get("detail"), 700)} + if isinstance(c, dict) and c.get("id") in known and c.get("state") in ("pass", "gap", "fail", "na") and c["id"] not in by_id: + by_id[c["id"]] = {"id": c["id"], "label": known[c["id"]], "state": c["state"], "detail": text_of(c.get("detail"), 700)} tests = counts_of(ev.get("tests"), ("executed", "failed", "skipped")) rules = ev["rules"] if isinstance(ev.get("rules"), dict) else None p0 = [{"id": text_of(r.get("id"), 40), "name": text_of(r.get("name"), 200), "confidence": text_of(r.get("confidence"), 10), @@ -367,7 +397,7 @@ def proof_module(m, problems): fresh = dict(counts_of(ev.get("fresh"), ("inputs", "executed", "same", "differs", "missing", "withinTolerance")), tolerances=tolerances_of(ev.get("fresh"))) if isinstance(ev.get("fresh"), dict) else None eq = ev.get("equivalence") if isinstance(ev.get("equivalence"), dict) else None notes = [] - for cid, label in PROOF_CHECKS: # a pack that leaves a check out cannot be PROVEN + for cid, label in required: # a pack that leaves a check out cannot be PROVEN if cid not in by_id: by_id[cid] = {"id": cid, "label": label, "state": "gap", "detail": "This check is missing from VERIFICATION.json."} notes.append("the %s check is missing" % label.lower()) @@ -384,10 +414,25 @@ def proof_module(m, problems): if by_id[cid]["state"] == "pass" and isinstance(bad, dict) and (count_of(bad.get("differs")) or count_of(bad.get("missing"))): by_id[cid].update(state="fail", detail="Some cases differ or are missing, whatever the file says.") notes.append("it says %s passed but cases differ or are missing" % by_id[cid]["label"].lower()) - if by_id["tests"]["state"] == "pass" and tests["failed"] and text_of(m.get("track"), 20) != "uplift": + if by_id["tests"]["state"] == "pass" and tests["failed"] and track != "uplift": by_id["tests"].update(state="fail", detail="Some tests failed, whatever the file says.") notes.append("it says tests passed but some failed") - checks = [by_id[cid] for cid, _ in PROOF_CHECKS] + up = uplift_view(ev) if track == "uplift" else None + if up is not None: # the three uplift checks must match the evidence beside them + bev, tc, dc = up["baseline"], up["testsChanged"], up["deltas"] + expected = "na" if bev is None or bev["kind"] == "target-only" else "pass" if bev["kind"] == "measured" and not bev["disagree"] and not bev["conflict"] else "gap" + if by_id["baseline"]["state"] in ("pass", "na") and expected == "gap": + by_id["baseline"].update(state="gap", detail="The baseline is not shown to be measured, whatever the file says.") + notes.append("it says the baseline is measured but the evidence shows otherwise") + kept_ok = tc is not None and tc["checked"] and tc["legacyTests"] > 0 and not tc["counts"]["removed"] and tc["counts"]["changed"] <= KEPT_SHARE * tc["legacyTests"] + if by_id["kept"]["state"] in ("pass", "na") and not kept_ok: + by_id["kept"].update(state="gap", detail="The test files are not shown to be kept, whatever the file says.") + notes.append("it says the tests were kept but the evidence shows otherwise") + deltas_ok = dc is not None and dc["parsed"] > 0 and not dc["uncoveredCount"] + if by_id["deltas"]["state"] in ("pass", "na") and not deltas_ok: + by_id["deltas"].update(state="gap", detail="The deltas are not shown to be covered, whatever the file says.") + notes.append("it says the deltas are covered but the evidence shows otherwise") + checks = [by_id[cid] for cid, _ in required] states = {c["state"] for c in checks} verdict = "NOT PROVEN" if "fail" in states else "PARTLY PROVEN" if "gap" in states else "PROVEN" if m.get("verdict") in PROOF_VERDICTS and m.get("verdict") != verdict or notes: @@ -404,7 +449,7 @@ def proof_module(m, problems): masks=[{"why": text_of(k.get("why"), 200), "cases": count_of(k.get("cases"))} for k in (eq.get("masks") if isinstance(eq.get("masks"), list) else [])[:10] if isinstance(k, dict)]) if eq else None, "fresh": fresh, "baseline": counts_of(base, ("regressionsCount", "newFailuresCount", "fixedCount", "missingCount", "renamed")) if base else None, "canary": [{"change": text_of(c.get("change"), 200), "testsFailed": count_of(c.get("testsFailed")), "shown": c.get("shown") is True} for c in (ev.get("canary") if isinstance(ev.get("canary"), list) else [])[:10] if isinstance(c, dict)], - "notProven": texts_of(m.get("notProven"), 400, 12), "needsPerson": texts_of(m.get("needsPerson"), 300, 10), "caveats": texts_of(m.get("caveats"), 400, 20), + "uplift": up, "notProven": texts_of(m.get("notProven"), 400, 16), "needsPerson": texts_of(m.get("needsPerson"), 300, 10), "caveats": texts_of(m.get("caveats"), 400, 20), "people": items, "peopleCount": max(count_of(brief.get("count")), len(items)), "briefFound": brief.get("found") is True} diff --git a/plugins/code-modernization/scripts/proof_pack.py b/plugins/code-modernization/scripts/proof_pack.py index 33838d34..acf9c997 100644 --- a/plugins/code-modernization/scripts/proof_pack.py +++ b/plugins/code-modernization/scripts/proof_pack.py @@ -56,13 +56,15 @@ sys.path.insert(0, HERE) import baseline_diff # noqa: E402 import compare # noqa: E402 import trace_rules # noqa: E402 +import uplift_checks # noqa: E402 FRESH_MIN, LIST_CAP, JSON_CAP = 10, 40, 8 << 20 VERDICTS = ("PROVEN", "PARTLY PROVEN", "NOT PROVEN") +UPLIFT_CHECKS = (("baseline", "Baseline measured"), ("kept", "Tests kept"), ("deltas", "Deltas covered")) CHECKS = (("tests", "Tests ran"), ("rules", "Rules traced"), ("same", "Same behavior"), ("fresh", "Fresh inputs"), - ("canary", "Canary"), ("source", "Source untouched")) + ("canary", "Canary"), ("source", "Source untouched")) + UPLIFT_CHECKS RULES_TEXT = ( - "PROVEN needs all six checks to pass. NOT PROVEN when any check fails. PARTLY PROVEN when nothing failed but a check could not pass.", + "PROVEN needs every check to pass: the six below, and for an uplift three more (7 to 9). NOT PROVEN when any check fails. PARTLY PROVEN when nothing failed but a check could not pass.", "1. Tests ran: at least one test executed in a fresh run, none failed, none was skipped without a reason, and every result file is newer than the code. " "The counts must be read by this script from result files or a saved raw runner log; counts only typed in cannot reach PROVEN.", "2. Rules traced (rewrite and reimagine): every P0 rule the module answers for is named by at least one test. A rule that only the notes name is claimed, not tested.", @@ -72,6 +74,11 @@ RULES_TEXT = ( "when it could not, the proof is trace-based and the best verdict is PARTLY PROVEN.", "5. Canary: a deliberate one-line break whose own result file or saved runner log shows failing tests. A line in the notes is a claim.", "6. Source untouched: no file under legacy/<system> is newer than the analysis (PREFLIGHT.md), by a plain file walk; no version-control tool is run.", + "7. Baseline measured (uplift): the old version's numbers in BASELINE.md come from per-test result files, a per-test results file or a raw runner log that this script parsed " + "(in analysis/<system>/baseline/, or on a Recorded: or Machine-readable: line of BASELINE.md), and the typed table agrees with them. A table typed by hand, or sources that disagree, cannot reach PROVEN.", + "8. Tests kept (uplift): no test file of the untouched legacy tree is missing from the working copy, no more than 25% of them changed, and the legacy tree has test files to compare against " + "(walked by file, no process is run). The list is for a person to review; weakened assertions cannot be detected, only that files changed.", + "9. Deltas covered (uplift): every Behavioral-silent delta in DELTA_CATALOG.md has its site's file named, as a whole word, by some test file of the working copy. A name is not proof that the test exercises the change.", "Open questions, unticked criteria and the sign-off are for a person. They never change the verdict.", ) WORDS = {"pass": "pass", "gap": "not proven", "fail": "FAIL", "na": "not applicable"} @@ -190,122 +197,8 @@ def code_mtime(root): return newest -# ---------------------------------------------------------------- raw runner logs -LOG_CAP, LOG_LINE = 16 << 20, 2000 -NUM_WORD = re.compile(r"(\d+)\s+([A-Za-z]+)") - - -def words(text): - """{'passed': 10, 'failed': 2} from '2 failed, 10 passed' style text.""" - out = {} - for n, w in NUM_WORD.findall(text[:LOG_LINE]): - out[w.lower()] = out.get(w.lower(), 0) + int(n) - return out - - -def _maven(m): - run, f, e, sk = (int(g) for g in m.groups()) - return max(0, run - f - e - sk), f + e, sk - - -def _pytest(m): - w = words(m.group(1)) - return w.get("passed", 0) + w.get("xpassed", 0) + w.get("xfailed", 0), w.get("failed", 0) + w.get("error", 0) + w.get("errors", 0), w.get("skipped", 0) - - -def _jest(m): - w = words(m.group(1)) - return w.get("passed", 0), w.get("failed", 0), w.get("skipped", 0) - - -def _php(m): - w = {k.lower(): int(v) for k, v in re.findall(r"([A-Za-z]+):\s*(\d+)", m.group(1)[:LOG_LINE])} - failed, skipped = w.get("failures", 0) + w.get("errors", 0), w.get("skipped", 0) + w.get("incomplete", 0) - return max(0, w.get("tests", 0) - failed - skipped), failed, skipped - - -def _ctest(m): - failed, total = int(m.group(1)), int(m.group(2)) - return max(0, total - failed), failed, 0 - - -def _gradle(m): - total, failed, skipped = int(m.group(1)), int(m.group(2) or 0), int(m.group(3) or 0) - return max(0, total - failed - skipped), failed, skipped - - -# runner, a line pattern, and how to read (passed, failed, skipped) from a match. Every pattern is anchored and bounded. -LOG_LINES = ( - ("maven", re.compile(r"^(?:\[\w+\]\s*)?Tests run: (\d+), Failures: (\d+), Errors: (\d+), Skipped: (\d+)\s*$"), _maven), - ("gradle", re.compile(r"^(\d+) tests? completed(?:, (\d+) failed)?(?:, (\d+) skipped)?\s*$"), _gradle), - ("cargo", re.compile(r"^test result: (?:ok|FAILED)\. (\d+) passed; (\d+) failed; (\d+) ignored;"), lambda m: (int(m.group(1)), int(m.group(2)), int(m.group(3)))), - ("pytest", re.compile(r"^(?:=+ )?((?:\d+ [a-z]+(?:, )?)+) in [\d.]+s(?: \([\d:]+\))?(?: =+)?\s*$"), _pytest), - ("pytest", re.compile(r"^(?:=+ )?no tests ran in [\d.]+s"), lambda m: (0, 0, 0)), - ("go test", re.compile(r"^\s*--- (PASS|FAIL|SKIP): \S"), lambda m: {"PASS": (1, 0, 0), "FAIL": (0, 1, 0), "SKIP": (0, 0, 1)}[m.group(1)]), - ("go test -json", re.compile(r'^\{.*"Action":"(pass|fail|skip)".*"Test":"[^"]+"'), lambda m: {"pass": (1, 0, 0), "fail": (0, 1, 0), "skip": (0, 0, 1)}[m.group(1)]), - ("dotnet test", re.compile(r"^(?:Passed|Failed)!\s+-\s+Failed:\s+(\d+),\s+Passed:\s+(\d+),\s+Skipped:\s+(\d+)"), lambda m: (int(m.group(2)), int(m.group(1)), int(m.group(3)))), - ("jest", re.compile(r"^\s*Tests:\s+(.*\b\d+ total)\s*$"), _jest), - ("vitest", re.compile(r"^\s*Tests\s{2,}(.*)\(\d+\)\s*$"), _jest), - ("ctest", re.compile(r"^\d+% tests passed, (\d+) tests? failed out of (\d+)"), _ctest), - ("phpunit", re.compile(r"^OK \((\d+) tests?, \d+ assertions?\)"), lambda m: (int(m.group(1)), 0, 0)), - ("phpunit", re.compile(r"^(Tests: \d+, Assertions: \d+.*?)\.?\s*$"), _php), -) -UNITTEST_RAN = re.compile(r"^Ran (\d+) tests? in [\d.]+s\s*$") -UNITTEST_END = re.compile(r"^(?:OK|FAILED)(?: \(([^)]*)\))?\s*$") - - -def parse_runner_log(text): - """(executed, failed, skipped, runners) from the runner's own summary lines, summed over the log; None when no line is recognised. - Recognised: Maven/Gradle, cargo, pytest, unittest, go test (-v or -json), dotnet test, jest, vitest, ctest, phpunit.""" - passed = failed = skipped = 0 - seen, ran = [], None - for line in text.split("\n")[:3000000]: - line = line.rstrip("\r")[:LOG_LINE] - if ran is not None and line.strip(): - m = UNITTEST_END.match(line) - if m: - w = {k: int(v) for k, v in re.findall(r"(\w+)=(\d+)", (m.group(1) or "")[:LOG_LINE])} - f, sk = w.get("failures", 0) + w.get("errors", 0), w.get("skipped", 0) - passed, failed, skipped = passed + max(0, ran - f - sk), failed + f, skipped + sk - seen.append("unittest") - ran = None - m = UNITTEST_RAN.match(line) - if m: - ran = int(m.group(1)) - continue - for name, rx, read in LOG_LINES: - m = rx.match(line) - if m: - p, f, sk = read(m) - passed, failed, skipped = passed + p, failed + f, skipped + sk - seen.append(name) - break - return (passed + failed, failed, skipped, sorted(set(seen))) if seen else None - - -def read_logs(paths): - """Saved runner logs -> {"files", "executed", "failed", "skipped", "runners", "oldest", "newest", "unrecognised"}. A log without a summary line of a known runner is no evidence.""" - out = {"files": 0, "executed": 0, "failed": 0, "skipped": 0, "runners": [], "oldest": None, "newest": None, "unrecognised": []} - for path in paths: - try: - st = os.lstat(path) - if not stat.S_ISREG(st.st_mode) or st.st_size > LOG_CAP: - out["unrecognised"].append("%s (a link, not a file, or larger than %d MB)" % (clean(os.path.basename(path), 80), LOG_CAP >> 20)) - continue - with open(path, "rb") as fh: - got = parse_runner_log(fh.read(LOG_CAP).decode("utf-8", "replace")) - except OSError: - out["unrecognised"].append("%s (could not be read)" % clean(os.path.basename(path), 80)) - continue - if got is None: - out["unrecognised"].append("%s (no summary line of a runner this script knows)" % clean(os.path.basename(path), 80)) - continue - out["files"] += 1 - out["executed"], out["failed"], out["skipped"] = out["executed"] + got[0], out["failed"] + got[1], out["skipped"] + got[2] - out["runners"] = sorted(set(out["runners"]) | set(got[3])) - out["oldest"] = st.st_mtime if out["oldest"] is None else min(out["oldest"], st.st_mtime) - out["newest"] = st.st_mtime if out["newest"] is None else max(out["newest"], st.st_mtime) - return out +# ---------------------------------------------------------------- raw runner logs (read by baseline_diff.py, which the baseline check shares) +LOG_CAP, parse_runner_log, read_logs = baseline_diff.LOG_CAP, baseline_diff.parse_runner_log, baseline_diff.read_logs def utc(ts): @@ -594,7 +487,18 @@ def check_rules(ctx, subject, evidence, caveats): return row("rules", "pass", "All %d P0 rule(s) this module answers for are named by at least one test." % len(p0)) -def baseline_state(ctx, suites, xml_paths, evidence, caveats, person): +def baseline_info(ctx): + """(assessment of BASELINE.md, the measured evidence) for an uplift: is the baseline measured or only typed? (None, None) without a BASELINE.md.""" + path = os.path.join(ctx["adir"], "BASELINE.md") + text = read_text(path) + if text is None: + return None, None + found = baseline_diff.evidence_paths(path, text) + measured = baseline_diff.read_baseline_evidence(found) if found else None + return baseline_diff.assess_baseline(baseline_diff.parse_baseline(text), measured), measured + + +def baseline_state(ctx, suites, xml_paths, evidence, caveats, person, measured=None): """The uplift's baseline comparison: (state, detail, whether it could compare).""" path = os.path.join(ctx["adir"], "BASELINE.md") if not os.path.isfile(path): @@ -602,7 +506,7 @@ def baseline_state(ctx, suites, xml_paths, evidence, caveats, person): if not xml_paths: return "gap", "BASELINE.md exists, but there are no result files to compare it with.", False try: - b = baseline_diff.run(path, xml_paths) + b = baseline_diff.run(path, xml_paths, measured=measured) except baseline_diff.InputError as err: return "gap", clean(str(err), 300), False keys = ("ok", "regressionsCount", "newFailuresCount", "fixedCount", "missingCount", "missingModulesCount", "moduleDiffsCount", "renamed", "executedDrop", "skippedGrowth", @@ -632,6 +536,65 @@ def baseline_state(ctx, suites, xml_paths, evidence, caveats, person): return "pass", "No regression: %d test(s) executed against %d in the baseline (%s)." % (b["fresh"]["counts"]["executed"], b["baseline"]["counts"]["executed"], b["baseline"]["source"]), True +def check_baseline_measured(info, evidence): + """Check 7 (uplift): is the old version's baseline measured, or only typed?""" + if info is None: + return row("baseline", "na", "There is no BASELINE.md to check (see Same behavior).") + evidence["baselineEvidence"] = info + if info["kind"] == "target-only": + return row("baseline", "na", "BASELINE.md says target-only: the old version was not measured here (see Same behavior).") + if info["kind"] in ("typed", "none"): + ignored = " Files that only hold counts were ignored: %s." % ", ".join(info["ignored"][:3]) if info["ignored"] else "" + return row("baseline", "gap", "BASELINE.md is a table typed by hand: no per-test result file, per-test results file or raw runner log that this script can read backs it, so nothing shows the old " + "version really produced those numbers. Save the old version's results in analysis/<system>/baseline/ (or name them on a Recorded: line of BASELINE.md) " + "and run this again.%s" % ignored) + names = ", ".join("%s%s" % (x["kind"], " " + x["name"] if x.get("name") else "") for x in info["sources"][:3]) + if info["conflict"]: + return row("baseline", "gap", "The baseline's own sources disagree with each other (%s), so it cannot be trusted." % "; ".join(info["conflictExamples"][:2])) + if info["disagree"]: + return row("baseline", "gap", "The measured results and BASELINE.md's typed table disagree on %d test(s) or count(s) (%s): the measured results were used, but a typed table that does not match its evidence cannot be trusted." % ( + info["disagree"], "; ".join(info["examples"][:2]))) + what = "%d test(s) (%d executed, %d failed)" % (info["measuredTests"], info["measuredExecuted"], info["measuredFailed"]) if info["measuredTests"] else "%d executed, %d failed" % ( + info["measuredExecuted"] or 0, info["measuredFailed"] or 0) + return row("baseline", "pass", "The baseline is measured: %s from %s, and BASELINE.md agrees with it." % (what, names)) + + +def check_tests_kept(tc, person): + """Check 8 (uplift): were the tests kept as they were?""" + if not tc["checked"]: + return row("kept", "gap", "The test files could not be compared: %s." % tc["why"]) + c = tc["counts"] + if c["added"] or c["removed"] or c["changed"]: + person.append("Review the test files that changed during the uplift (%d changed, %d added, %d removed; the list is in VERIFICATION.md). Weakened assertions cannot be detected, only that files changed." % ( + c["changed"], c["added"], c["removed"])) + if not tc["legacyTests"]: + return row("kept", "gap", "%s (%d test file(s) in the working copy)." % (tc["why"][:1].upper() + tc["why"][1:], tc["workTests"])) + reasons = [] + if c["removed"]: + reasons.append("%d legacy test file(s) are missing from the working copy (%s)" % (c["removed"], ", ".join(x["path"].rsplit("/", 1)[-1] for x in tc["removed"][:3]))) + if tc["legacyTests"] and c["changed"] > uplift_checks.SHARE_LIMIT * tc["legacyTests"]: + reasons.append("%d of %d legacy test files (%.0f%%) were changed, more than the 25%% allowed" % (c["changed"], tc["legacyTests"], 100 * tc["share"])) + if reasons: + return row("kept", "gap", "; ".join(reasons) + ": the tests were edited or deleted, so passing them proves less. A person should review the list.") + return row("kept", "pass", "No legacy test file was removed and %d of %d (%.0f%%) changed; %d test file(s) were added. The list is for a person to review." % (c["changed"], tc["legacyTests"], 100 * tc["share"], c["added"])) + + +def check_deltas(dc, person): + """Check 9 (uplift): does some test name the site of every Behavioral-silent delta?""" + if dc["parsed"] == 0: + return row("deltas", "gap", "%s." % dc["why"]) + if dc["config"]: + person.append("%d Behavioral-silent delta(s) sit at a build or configuration file that a test cannot name (%s): a person decides how each is checked." % ( + len(dc["config"]), ", ".join(x["id"] for x in dc["config"][:6]))) + extra = " %d more at a build or configuration file (a test cannot name it; for a person)." % len(dc["config"]) if dc["config"] else "" + if dc["uncovered"]: + listed = "; ".join("%s (%s)" % (x["id"], x.get("why", "")) for x in dc["uncovered"][:4]) + return row("deltas", "gap", "%d of %d Behavioral-silent delta(s) have no test that names their site: %s.%s" % (len(dc["uncovered"]), dc["silent"], listed, extra)) + if not dc["silent"]: + return row("deltas", "pass", "%d delta(s) are in DELTA_CATALOG.md and none is Behavioral-silent.%s" % (dc["parsed"], extra)) + return row("deltas", "pass", "All %d Behavioral-silent delta(s) (of %d in the catalog) have their site's file named by a test in the working copy.%s" % (len(dc["covered"]), dc["parsed"], extra)) + + def check_same(ctx, subject, paths, dev, dev_problem, base, evidence, caveats): """Check 3. `base` is baseline_state's answer for an uplift, else None.""" uplift, dev_state, dev_detail = subject["track"] == "uplift", None, "" @@ -784,6 +747,9 @@ def not_proven(subject, ev, legacy_ran): out.append("It does not cover speed, capacity, security, concurrency, or anything the tests and cases do not exercise.") if subject["track"] != "uplift": out.append("It traces only the rules that were extracted: behavior nobody wrote down as a rule has no rule to trace.") + else: + out.append("Weakened assertions cannot be detected: only that test files changed. A test file that was edited may check less than it did.") + out.append("A silent version change counts as covered when some test names its site's file, not when a test exercises the changed behavior.") out.append("A test that names a rule shows the rule is mentioned, not that the test is a good one. The canary shows only that some test can fail.") out.append("It does not replace the review and sign-off of the people who own the system.") return out @@ -808,7 +774,8 @@ def evaluate(subject, ctx): g.update({"suites": per, "stale": oldest is not None and code_mtime(subject["path"]) > oldest + 2}) # any result file older than the code: not a clean run evidence["tests"] = dict({k: g[k] for k in ("executed", "failed", "skipped", "skippedNoReason", "stale")}, suites=[{k: e.get(k, "") for k in ("name", "command", "date", "note", "source", "files", "written", "executed", "failed", "skipped")} for e in per][:20]) - base = baseline_state(ctx, suites, xml_paths, evidence, caveats, person) if uplift else None + binfo, bmeasured = baseline_info(ctx) if uplift else (None, None) + base = baseline_state(ctx, suites, xml_paths, evidence, caveats, person, bmeasured) if uplift else None paths = cases_paths(ctx["adir"], module, len(ctx["subjects"])) dev, dev_problem = judge(paths["cases"]) if paths["cases"] else (None, None) frs, fr_problem = judge(paths["fresh"]) if paths["fresh"] else (None, None) @@ -820,6 +787,12 @@ def evaluate(subject, ctx): evidence["legacy"] = dict(ctx["runs"]["legacy"], ran=legacy_ran) checks = [check_tests(g, uplift, bool(base and base[2])), check_rules(ctx, subject, evidence, caveats), check_same(ctx, subject, paths, dev, dev_problem, base, evidence, caveats), check_fresh(ctx, paths, dev, legacy_ran, frs, fr_problem, evidence), check_canary(subject, module, ctx["runs"], evidence, ws, {x["name"].lower() for x in ctx["subjects"] if x["track"] != "uplift"}, clean_ids, g["failed"]), check_source(ctx)] + if uplift: + legacy_root = os.path.realpath(os.path.join(ws, "legacy", ctx["system"])) if os.path.lexists(os.path.join(ws, "legacy", ctx["system"])) else "" + evidence["testsChanged"] = uplift_checks.tests_changed(legacy_root, subject["path"]) + catalog = read_text(os.path.join(ctx["adir"], "DELTA_CATALOG.md")) + evidence["deltas"] = uplift_checks.delta_coverage(catalog, subject["path"]) + checks += [check_baseline_measured(binfo, evidence), check_tests_kept(evidence["testsChanged"], person), check_deltas(evidence["deltas"], person)] states = [c["state"] for c in checks] label = dict(CHECKS) return {"name": module, "track": subject["track"], "path": subject["rel"], "verdict": "NOT PROVEN" if "fail" in states else "PARTLY PROVEN" if "gap" in states else "PROVEN", @@ -915,6 +888,37 @@ def render_md(pack): out += ["- Regression: %s (%s, now %s)" % (cell(x["id"]), x["before"], x["now"]) for x in b["regressions"][:10]] + ["- New failure: " + cell(x) for x in b["newFailures"][:10]] if ev.get("baseline", {}).get("approvedCount"): out += ["- Difference a person approved in BASELINE.md: %s (%s)" % (cell(x["id"]), cell(x["reason"] or "no reason given")) for x in ev["baseline"]["approved"][:10]] + if ev.get("baselineEvidence"): + a = ev["baselineEvidence"] + out += ["", "### Baseline evidence", "", ("Measured: %s." % ", ".join("%s%s" % (x["kind"], " " + cell(x["name"]) if x.get("name") else "") for x in a["sources"][:5])) if a["kind"] == "measured" else + "Typed by hand: no per-test result file, per-test results file or raw runner log backs BASELINE.md."] + out += ["- The typed table disagrees on %d test(s) or count(s): %s" % (a["disagree"], "; ".join(cell(x) for x in a["examples"][:3]))] if a["disagree"] else [] + out += ["- Sources disagree: " + "; ".join(cell(x) for x in a["conflictExamples"][:3])] if a["conflict"] else [] + out += ["- Looked at: " + ", ".join(cell(x) for x in a["considered"][:8])] if a["considered"] else [] + if ev.get("testsChanged"): + tc = ev["testsChanged"] + out += ["", "### Test files changed during the uplift", ""] + if tc["checked"]: + out += ["%d test file(s) in the legacy tree, %d in the working copy: %d removed, %d added, %d changed (%.0f%% of the legacy test files). Weakened assertions cannot be detected, only that files changed." % ( + tc["legacyTests"], tc["workTests"], tc["counts"]["removed"], tc["counts"]["added"], tc["counts"]["changed"], 100 * tc["share"])] + out += ["- Removed: `%s` (%d lines)" % (cell(x["path"]), x["lines"]) for x in tc["removed"]] + out += ["- Changed: `%s` (+%d -%d lines%s)" % (cell(x["path"]), x["added"], x["removed"], "; " + cell(x["note"]) if x["note"] else "") for x in tc["changed"]] + out += ["- Added: `%s` (%d lines)" % (cell(x["path"]), x["lines"]) for x in tc["added"]] + shown = len(tc["removed"]) + len(tc["changed"]) + len(tc["added"]) + if sum(tc["counts"].values()) > shown: + out.append("- ... and %d more (see VERIFICATION.json)." % (sum(tc["counts"].values()) - shown)) + else: + out.append("Not compared: %s." % cell(tc["why"])) + if ev.get("deltas"): + dc = ev["deltas"] + out += ["", "### Version changes (deltas) and the tests that name them", ""] + if dc["parsed"]: + out += ["%d delta(s) in DELTA_CATALOG.md; %d are Behavioral-silent: %d have a test naming their site, %d do not; %d more at a build or configuration file." % ( + dc["parsed"], dc["silent"], len(dc["covered"]), len(dc["uncovered"]), len(dc["config"]))] + out += ["- Not named by any test: %s %s (%s)" % (cell(x["id"]), cell(x["title"]), cell(x.get("why", ""))) for x in dc["uncovered"][:LIST_CAP]] + out += ["- At a build or configuration file (for a person): %s %s (%s)" % (cell(x["id"]), cell(x["title"]), ", ".join(cell(y) for y in x["sites"][:3])) for x in dc["config"][:LIST_CAP]] + else: + out.append(cell(dc["why"]) + ".") if ev.get("leftOut"): out += ["", "Inputs left out of the fresh check: " + "; ".join(cell(x) for x in ev["leftOut"])] if "fresh" in ev: diff --git a/plugins/code-modernization/scripts/tests/test_proof_tools.py b/plugins/code-modernization/scripts/tests/test_proof_tools.py index 29e38997..930670f8 100644 --- a/plugins/code-modernization/scripts/tests/test_proof_tools.py +++ b/plugins/code-modernization/scripts/tests/test_proof_tools.py @@ -23,6 +23,7 @@ import build_report as br # noqa: E402 import compare as cmp # noqa: E402 import proof_pack as pp # noqa: E402 import trace_rules as tr # noqa: E402 +import uplift_checks as uc # noqa: E402 TEMPLATE = os.path.join(PLUGIN, "assets", "report-template.html") NODE = shutil.which("node") @@ -265,7 +266,7 @@ BASELINE_MD = """# BASELINE | | Count | |---|---| -| Executed | 4 | +| Executed | 5 | ## Known-flaky tests @@ -986,6 +987,309 @@ class RunnerLogs(unittest.TestCase): self.assertEqual(len(got["unrecognised"]), 3) +class BaselineEvidence(unittest.TestCase): + """baseline_diff.py: where the old version's measured results are looked for, and what counts as measured.""" + + def setUp(self): + self.root = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, self.root, True) + self.base = put(self.root, "analysis/s/BASELINE.md", BASELINE_MD) + self.per_test = json.dumps({"A#pass1": "PASS", "A#pass2": "PASS", "A#failed": "FAIL", "A#skipped": "SKIP", "B#flip": "PASS", "B#gone": "PASS"}) + + def found(self, text=""): + return [os.path.relpath(p, os.path.join(self.root, "analysis", "s")) for p in bd.evidence_paths(self.base, BASELINE_MD + text)] + + def test_per_test_json_shapes_are_read_and_counts_or_prose_are_not(self): + self.assertEqual(bd.parse_results_json({"A#x": "PASS", "A#y": "failed", "A#z": "Skipped"}), {"A#x": "PASS", "A#y": "FAIL", "A#z": "SKIP"}) + self.assertEqual(bd.parse_results_json({"tests": {"A#x": "ok"}}), {"A#x": "PASS"}) + self.assertEqual(bd.parse_results_json([{"name": "A#x", "status": "pass"}, {"test": "A#y", "result": "FAIL"}, {"id": "A#z", "outcome": "error"}, {"name": "no status"}, 5]), + {"A#x": "PASS", "A#y": "FAIL", "A#z": "ERROR"}) + for bad in ({"PASS": 10, "FAIL": 1}, {"passed": 5, "failed": 0, "executed": 5}, {"tests": {"count": 3}}, {"a": "hello", "b": "world"}, [], {}, "text", 5, None, [1, 2], {"a": {"b": "PASS"}}): + self.assertIsNone(bd.parse_results_json(bad), bad) + many = bd.parse_results_json({"t%d" % i: "PASS" for i in range(1000)} | {"junk": "hello"} if sys.version_info >= (3, 9) else dict({"t%d" % i: "PASS" for i in range(1000)}, junk="hello")) + self.assertEqual(len(many), 1000) # one stray value in a thousand does not spoil it + self.assertIsNone(bd.parse_results_json({"a": "PASS", "b": "hello", "c": "world"})) # but a mostly-unrecognised map is no evidence + + def test_the_baseline_folder_and_recorded_lines_are_the_only_places(self): + put(self.root, "analysis/s/baseline/old.json", self.per_test) + put(self.root, "analysis/s/harness/named.json", self.per_test) + put(self.root, "analysis/s/harness/prose.json", self.per_test) + put(self.root, "analysis/s/harness/bare.log", "x") + self.assertEqual(self.found(), ["baseline"]) + self.assertEqual(self.found("\nSee `analysis/s/harness/prose.json` too.\n"), ["baseline"]) + self.assertEqual(self.found("\n- **Recorded:** 2026-09-24. Machine-readable per-test results: `analysis/s/harness/named.json`; tool: `analysis/s/harness/prose.json`\n"), + ["baseline", "harness/named.json", "harness/prose.json"]) # everything on the Recorded line counts + self.assertEqual(self.found("\nMachine-readable: harness/bare.log\n"), ["baseline", "harness/bare.log"]) + self.assertEqual(self.found("\n * recorded on Thursday: harness/named.json\n"), ["baseline", "harness/named.json"]) + self.assertEqual(self.found("\nNot recorded: harness/named.json\n"), ["baseline"]) # the line must start with the label + + def test_paths_that_leave_analysis_or_go_through_links_are_refused(self): + outside = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, outside, True) + put(outside, "o.json", self.per_test) + put(self.root, "analysis/other/o.json", self.per_test) + put(self.root, "modernized/o.json", self.per_test) + put(self.root, "analysis/s/inner.json", self.per_test) + make_symlink(self, os.path.join(outside, "o.json"), os.path.join(self.root, "analysis", "s", "link.json")) + make_symlink(self, outside, os.path.join(self.root, "analysis", "s", "dirlink")) + make_symlink(self, os.path.join(self.root, "analysis", "other"), os.path.join(self.root, "analysis", "s", "sibling")) + for line in ("../other/o.json", "analysis/other/o.json", "analysis/s/../other/o.json", "modernized/o.json", outside + "/o.json", "link.json", "dirlink/o.json", "sibling/o.json", "./../s/../other/o.json"): + self.assertEqual(self.found("\nRecorded: `%s`\n" % line), [], line) + self.assertEqual(self.found("\nRecorded: `analysis/s/inner.json`\n"), ["inner.json"]) + os.rename(os.path.join(self.root, "analysis", "s", "dirlink"), os.path.join(self.root, "dirlink-moved")) + make_symlink(self, outside, os.path.join(self.root, "analysis", "s", "baseline")) + self.assertEqual(self.found(), []) # a linked baseline/ folder is not entered + + def test_result_files_json_and_logs_are_all_read_and_counts_only_files_are_ignored(self): + put(self.root, "analysis/s/baseline/xml/TEST-A.xml", junit([("A", "one", "PASS", ""), ("A", "two", "FAIL", "")])) + put(self.root, "analysis/s/baseline/map.json", json.dumps({"B#x": "PASS"})) + put(self.root, "analysis/s/baseline/counts.json", json.dumps({"PASS": 9})) + put(self.root, "analysis/s/baseline/bad.json", "{not json") + put(self.root, "analysis/s/baseline/notes.txt", "nothing that looks like a runner summary") + got = bd.read_baseline_evidence(bd.evidence_paths(self.base, "")) + self.assertEqual(got["tests"], {"A#one": "PASS", "A#two": "FAIL", "B#x": "PASS"}) + self.assertEqual((got["measured"], got["conflicts"], got["ignored"]), (True, [], ["counts.json"])) + self.assertEqual([x["kind"] for x in got["sources"]], ["result files", "machine-readable results"]) + self.assertTrue(any("bad.json" in u for u in got["unreadable"])) + only_log = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, only_log, True) + put(only_log, "run.log", "[INFO] Tests run: 5, Failures: 1, Errors: 0, Skipped: 0\n") + got = bd.read_baseline_evidence([only_log]) + self.assertEqual((got["tests"], got["counts"], got["measured"]), (None, {"executed": 5, "failed": 1, "skipped": 0}, True)) + nothing = bd.read_baseline_evidence([os.path.join(self.root, "analysis", "s", "baseline", "counts.json")]) + self.assertEqual((nothing["measured"], nothing["tests"], nothing["counts"]), (False, None, None)) + + def test_sources_that_disagree_are_conflicts_not_first_wins(self): + put(self.root, "analysis/s/baseline/a.json", json.dumps({"A#x": "PASS", "A#y": "PASS"})) + put(self.root, "analysis/s/baseline/b.json", json.dumps({"A#x": "FAIL", "A#y": "PASS", "A#z": "PASS"})) + got = bd.read_baseline_evidence(bd.evidence_paths(self.base, "")) + self.assertEqual(len(got["conflicts"]), 1) + self.assertIn("A#x", got["conflicts"][0]) + self.assertEqual(got["tests"]["A#x"], "PASS") # kept only so the report can show something; the conflict is what counts + info = bd.assess_baseline(bd.parse_baseline("| Test | Result |\n|---|---|\n| `A#x` | PASS |\n"), got) + self.assertEqual((info["kind"], info["conflict"]), ("measured", 1)) + put(self.root, "analysis/s/baseline/b.json", json.dumps({"A#x": "ERROR", "A#y": "PASS"})) + put(self.root, "analysis/s/baseline/a.json", json.dumps({"A#x": "FAIL"})) + self.assertEqual(bd.read_baseline_evidence(bd.evidence_paths(self.base, ""))["conflicts"], []) # FAIL and ERROR are both red + + def test_assess_says_typed_measured_disagreeing_or_target_only(self): + typed = bd.parse_baseline(BASELINE_MD) + self.assertEqual(bd.assess_baseline(typed, None)["kind"], "typed") + self.assertEqual(bd.assess_baseline(bd.parse_baseline("target-only: no old runtime\n"), {"measured": True, "tests": {"a": "PASS"}, "counts": None, "sources": []})["kind"], "target-only") + self.assertEqual(bd.assess_baseline(bd.parse_baseline("nothing here"), None)["kind"], "none") + good = {"measured": True, "tests": {"A#pass1": "PASS", "A#pass2": "PASS", "A#failed": "FAIL", "A#skipped": "SKIP", "B#flip": "PASS", "B#gone": "PASS"}, "counts": None, + "sources": [{"kind": "machine-readable results", "name": "x.json"}], "conflicts": []} + info = bd.assess_baseline(typed, good) + self.assertEqual((info["kind"], info["disagree"], info["measuredTests"], info["measuredExecuted"], info["measuredFailed"]), ("measured", 0, 6, 5, 1)) + bad = dict(good, tests=dict(good["tests"], **{"A#pass1": "FAIL"})) + self.assertEqual(bd.assess_baseline(typed, bad)["disagree"], 1) + missing = dict(good, tests={k: v for k, v in good["tests"].items() if k != "B#gone"}) + self.assertEqual(bd.assess_baseline(typed, missing)["disagree"], 2) # the missing row, and the Totals table that counts it + + def test_the_cli_can_be_given_the_evidence_and_says_typed_only_otherwise(self): + folder = os.path.join(self.root, "res") + put(folder, "TEST-x.xml", junit([("A", "pass1", "PASS", ""), ("A", "pass2", "PASS", ""), ("A", "failed", "FAIL", ""), ("A", "skipped", "SKIP", ""), ("B", "flip", "PASS", ""), ("B", "gone", "PASS", "")])) + code, out, _ = run_main(bd.main, [self.base, "--junit", folder]) + self.assertIn("typed table only", out) + put(self.root, "analysis/s/baseline/old.json", self.per_test) + code, out, _ = run_main(bd.main, [self.base, "--junit", folder]) + self.assertIn("baseline evidence: measured (machine-readable results old.json)", out) + evidence = os.path.join(self.root, "elsewhere.json") + put(self.root, "elsewhere.json", self.per_test) + code, out, _ = run_main(bd.main, [self.base, "--junit", folder, "--baseline-evidence", evidence, "--json"]) + self.assertEqual(json.loads(out)["baseline"]["assessment"]["kind"], "measured") + + +class UpliftChecks(unittest.TestCase): + """uplift_checks.py: the test files of the untouched tree against the working copy, and the deltas no test names.""" + + def setUp(self): + self.root = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, self.root, True) + self.old, self.new = os.path.join(self.root, "old"), os.path.join(self.root, "new") + + def both(self, rel, old, new=None, kind="w"): + put(self.old, rel, old) + put(self.new, rel, old if new is None else new) + + def test_which_files_count_as_tests_and_what_is_skipped(self): + for rel in ("src/test/java/AThing.java", "tests/b.py", "web/__tests__/c.js", "spec/d.rb", "src/FooTest.java", "pkg/test_e.py", "pkg/e_test.go", "web/f.spec.ts", "src/test/resources/data.json"): + put(self.old, rel, "x") + for rel in ("src/main/A.java", "README.md", "src/test/notes.txt", "target/test/X.java", "node_modules/y/test/Z.js", ".hidden/test/H.java", "src/test/.dotfile"): + put(self.old, rel, "x") + got, cut, links = uc.walk_tests(self.old) + self.assertEqual(sorted(got), ["pkg/e_test.go", "pkg/test_e.py", "spec/d.rb", "src/FooTest.java", "src/test/java/AThing.java", "src/test/resources/data.json", "tests/b.py", + "web/__tests__/c.js", "web/f.spec.ts"]) + self.assertEqual((cut, links), (False, 0)) + self.assertEqual(uc.walk_tests(os.path.join(self.root, "missing")), ({}, False, 0)) + + def test_removed_added_and_changed_with_line_counts(self): + self.both("t/keep/AKeepTest.java", "one\ntwo\nthree\n") + self.both("t/edit/AEditTest.java", "one\ntwo\nthree\nfour\n", "one\nTWO\nthree\nfour\nfive\n") + put(self.old, "t/gone/AGoneTest.java", "x\ny\n") + put(self.new, "t/new/ANewTest.java", "a\nb\nc\n") + got = uc.tests_changed(self.old, self.new) + self.assertEqual((got["checked"], got["legacyTests"], got["workTests"], got["counts"]), (True, 3, 3, {"added": 1, "removed": 1, "changed": 1})) + self.assertEqual(got["changed"], [{"path": "t/edit/AEditTest.java", "added": 2, "removed": 1, "note": ""}]) + self.assertEqual((got["removed"], got["added"]), ([{"path": "t/gone/AGoneTest.java", "lines": 3}], [{"path": "t/new/ANewTest.java", "lines": 4}])) + self.assertTrue(got["gap"]) # a removed file + self.assertEqual(round(got["share"], 3), round(1 / 3, 3)) + + def test_a_quarter_changed_is_not_a_gap_and_more_is_and_line_endings_are_ignored(self): + for i in range(4): + self.both("t/T%dTest.java" % i, "line %d\r\nsecond\r\n" % i) + put(self.new, "t/T0Test.java", "line 0\nsecond\n") # only the line endings differ + self.assertEqual(uc.tests_changed(self.old, self.new)["counts"]["changed"], 0) + put(self.new, "t/T1Test.java", "line 1 edited\nsecond\n") + got = uc.tests_changed(self.old, self.new) + self.assertEqual((got["counts"]["changed"], got["gap"], got["share"]), (1, False, 0.25)) + put(self.new, "t/T2Test.java", "line 2 edited\nsecond\n") + self.assertTrue(uc.tests_changed(self.old, self.new)["gap"]) + + def test_no_legacy_tests_is_a_gap_and_so_is_a_missing_tree(self): + put(self.new, "t/ANewTest.java", "x") + put(self.old, "src/main/A.java", "the legacy tree exists but holds no test file") + got = uc.tests_changed(self.old, self.new) + self.assertEqual((got["checked"], got["legacyTests"], got["gap"]), (True, 0, True)) + self.assertIn("nothing shows that the working copy's tests were not written during the uplift", got["why"]) + for old, new in ((os.path.join(self.root, "none"), self.new), ("", self.new), (self.old, os.path.join(self.root, "none")), (self.old, "")): + got = uc.tests_changed(old, new) + self.assertEqual(got["checked"], False, (old, new)) + self.assertTrue(got["why"]) + + def test_binary_large_and_unreadable_files_are_compared_without_crashing(self): + self.both("t/data/a.bin.Test.dat", b"\x00\x01\x02", b"\x00\x01\x03") + self.both("t/big/BigTest.java", "x\n" * (1 << 20), "x\n" * (1 << 20) + "y\n") + self.both("t/same/SameBigTest.java", "z\n" * (1 << 20)) + self.both("t/lines/ManyTest.java", "".join("line %d\n" % i for i in range(9000)), "".join("line %d\n" % i for i in range(1, 9001))) + got = uc.tests_changed(self.old, self.new) + notes = {c["path"]: c["note"] for c in got["changed"]} + self.assertEqual(notes["t/data/a.bin.Test.dat"], "binary file") + self.assertEqual(notes["t/big/BigTest.java"], "large file, lines not counted") + self.assertEqual(notes["t/lines/ManyTest.java"], "lines counted approximately") + self.assertNotIn("t/same/SameBigTest.java", notes) + many = next(c for c in got["changed"] if c["path"] == "t/lines/ManyTest.java") + self.assertEqual((many["added"], many["removed"]), (1, 1)) + + def test_links_are_never_followed_and_hostile_trees_stay_bounded(self): + outside = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, outside, True) + put(outside, "OutTest.java", "outside") + self.both("t/InTest.java", "in") + make_symlink(self, os.path.join(outside, "OutTest.java"), os.path.join(self.new, "t", "LinkTest.java")) + make_symlink(self, outside, os.path.join(self.new, "t", "linked")) + got = uc.tests_changed(self.old, self.new) + self.assertEqual((got["workTests"], got["counts"]), (1, {"added": 0, "removed": 0, "changed": 0})) + self.assertNotIn("Out", json.dumps(got)) + for i in range(300): + self.both("t/many/M%03dTest.java" % i, "a\n" * 50, "a\n" * 50 + "edit %d\n" % i) + started = time.time() + got = uc.tests_changed(self.old, self.new) + self.assertLess(time.time() - started, 30) + self.assertEqual((got["counts"]["changed"], len(got["changed"])), (300, 40)) # the count is complete, the list is cut + self.assertNotRegex(json.dumps(uc.tests_changed(self.old, self.new)), "\x1b") + + def test_a_hostile_file_name_is_cleaned(self): + self.both("t/ev\x1b[31mil\nTest.java", "a", "b") + got = uc.tests_changed(self.old, self.new) + self.assertNotRegex(got["changed"][0]["path"], r"[\x00-\x1f]") + + CARDS = """# DELTA_CATALOG: x + +| ID | Category | Fix | Site | Old to new | +|---|---|---|---|---| +| **D-01** | Behavioral-silent | Judgment | `a/b/Alpha.java:916` | changed | +| **D-02** | Behavioral-silent (pre-existing bug, wider on 17) | Judgment | `Beta.java` (`decode`) | changed | +| **D-03** | Project-system | Judgment | root `pom.xml:629` | build | + +| # | Category | Fix | Conf. | Delta | Site | Sites | Note | +|---|---|---|---|---|---|---|---| +| 9 | Behavioral-silent | Mechanical | High | CLDR listing dates | `x/y/Resource.java:574` | 1 | Gamma.java is mentioned in prose only | +| 10 | Dependency | Mechanical | High | JaCoCo agent | `pom.xml:614` | 3 | n | + +## Card detail + +### 9. CLDR listing dates +- **Category / fix / confidence:** Behavioral-silent / Mechanical / High; sites: 1; cited: `x/y/Resource.java:574` +- **Blast radius:** One site. Sites: Delta.java:12, and Epsilon.java:40 also matter. + +### 11. A card that only exists as a card +- **Category / fix / confidence:** Behaviour-Silent / Judgment / Low; sites: 2; cited: `p/Zeta.py:3`, `p/Eta.py:9` + +### 12. A numbered heading with no category line +- Some prose about Theta.java:1. + +### D-04 Another id style +- **Category:** behavioral silent +- **Site:** `q/Iota.cs:5` +""" + + def test_deltas_are_read_from_tables_and_cards_and_merged(self): + got = {d["id"]: d for d in uc.parse_deltas(self.CARDS)} + self.assertEqual(sorted(got), ["11", "9", "10", "D-01", "D-02", "D-03", "D-04"] if False else sorted(["11", "9", "10", "D-01", "D-02", "D-03", "D-04"])) + self.assertEqual([s["stem"] for s in got["D-01"]["sites"]], ["Alpha"]) + self.assertEqual(got["D-01"]["sites"][0]["line"], 916) + self.assertEqual([s["stem"] for s in got["D-02"]["sites"]], ["Beta"]) # a site without a line, with a known extension + self.assertEqual(got["D-02"]["category"], "Behavioral-silent (pre-existing bug, wider on 17)") + self.assertEqual([s["stem"] for s in got["9"]["sites"]], ["Resource"]) # the table and the card agree; prose files are not sites + self.assertEqual(got["9"]["title"], "CLDR listing dates") + self.assertEqual([s["stem"] for s in got["11"]["sites"]], ["Zeta", "Eta"]) + self.assertEqual(got["11"]["category"], "Behaviour-Silent") + self.assertEqual(got["D-04"]["category"], "behavioral silent") + self.assertEqual([s["stem"] for s in got["D-04"]["sites"]], ["Iota"]) + self.assertNotIn("12", got) + + def test_the_parser_is_tolerant_and_bounded(self): + for text in ("", "no tables at all", "| a | b |\n|---|---|\n| 1 | 2 |\n", "| Category |\n|---|\n| Behavioral-silent |\n", "### 1. x\n" * 10, "|" * 100000, "#" * 100000, + "### 3. t\n- **Category:** " + "Behavioral-silent " * 100000 + "\n", "| # | Category | Site |\n|---|---|---|\n| 1 | Behavioral-silent | " + "a/" * 100000 + "B.java:1 |\n"): + started = time.time() + uc.parse_deltas(text) + self.assertLess(time.time() - started, 10) + many = "| # | Category | Site |\n|---|---|---|\n" + "".join("| %d | Behavioral-silent | `S%d.java:1` |\n" % (i, i) for i in range(6000)) + self.assertLessEqual(len(uc.parse_deltas(many)), uc.DELTA_CAP) + weird = uc.parse_deltas("| # | Category | Site |\n|---|---|---|\n| 1\x1b[31m | Behavioral-silent\x00 | `Ev\x1bil.java:1` |\n") + self.assertNotRegex(json.dumps(weird), r"\\u001b|\\u0000") + + def test_coverage_names_sites_as_whole_words_in_test_files_only(self): + put(self.new, "src/main/Alpha.java", "class Alpha {}") + put(self.new, "src/test/AlphaTest.java", "class AlphaTest { Alpha a; AlphaBeta x; Gamma_ y; }") + put(self.new, "src/main/Beta.java", "class Beta { Delta d; }") + put(self.new, "src/test/notes.txt", "Delta is discussed here") + cat = ("| # | Category | Site |\n|---|---|---|\n| 1 | Behavioral-silent | `src/main/Alpha.java:1` |\n| 2 | Behavioral-silent | `src/main/Beta.java:2` |\n" + "| 3 | Behavioral-silent | `src/main/Gamma.java:3` |\n| 4 | Behavioral-silent | `src/main/Delta.java:4` |\n| 5 | Dependency | `src/main/Other.java:5` |\n" + "| 6 | Behavioral-silent | `src/main/Alpha.java:1`, `src/main/Beta.java:2` |\n| 7 | Behavioral-silent | no site here |\n| 8 | Behavioral-silent | `pom.xml:9` |\n") + got = uc.delta_coverage(cat, self.new) + self.assertEqual((got["parsed"], got["silent"], got["other"], got["testFiles"]), (8, 7, 1, 1)) + self.assertEqual([d["id"] for d in got["covered"]], ["1"]) + self.assertEqual({d["id"]: d["why"] for d in got["uncovered"]}, {"2": "no test names Beta", "3": "no test names Gamma", "4": "no test names Delta", "6": "no test names Beta", "7": "no site is named in the catalog"}) + self.assertEqual([d["id"] for d in got["config"]], ["8"]) + self.assertTrue(got["gap"]) + + def test_no_catalog_or_an_unreadable_one_is_a_gap(self): + self.assertTrue(uc.delta_coverage(None, self.new)["gap"]) + got = uc.delta_coverage("Nothing to read here.", self.new) + self.assertEqual((got["parsed"], got["gap"]), (0, True)) + ok = uc.delta_coverage("| # | Category | Site |\n|---|---|---|\n| 1 | API-removed | `A.java:1` |\n", self.new) + self.assertEqual((ok["silent"], ok["gap"]), (0, False)) + + def test_the_command_line_prints_a_summary_json_and_the_exit_code(self): + self.both("t/InTest.java", "Alpha") + put(self.new, "src/main/Alpha.java", "class Alpha {}") + cat = put(self.root, "CAT.md", "| # | Category | Site |\n|---|---|---|\n| 1 | Behavioral-silent | `src/main/Alpha.java:1` |\n") + code, out, _ = run_main(uc.main, [self.old, self.new, cat]) + self.assertEqual(code, 0) + self.assertIn("tests kept: ok", out) + self.assertIn("deltas covered: ok", out) + code, out, _ = run_main(uc.main, [self.old, self.new, cat, "--json"]) + self.assertEqual(json.loads(out)["deltas"]["silent"], 1) + os.remove(os.path.join(self.new, "t", "InTest.java")) + code, out, _ = run_main(uc.main, [self.old, self.new]) + self.assertEqual(code, 1) + self.assertIn("removed: t/InTest.java", out) + self.assertEqual(run_main(uc.main, [os.path.join(self.root, "none"), self.new])[0], 2) + self.assertEqual(run_main(uc.main, [self.old, self.new, os.path.join(self.root, "none.md")])[0], 2) + + class ProofOutputs(unittest.TestCase): def setUp(self): self.ws = Ws(self) @@ -1049,14 +1353,20 @@ class ProofOutputs(unittest.TestCase): class ProofUplift(unittest.TestCase): BASE = "# BASELINE\n\n## Per-test results\n\n| Test | Result |\n|---|---|\n| `T#a` | PASS |\n| `T#b` | PASS |\n| `T#c` | FAIL |\n| `T#d` | SKIP |\n" + CATALOG = ("# DELTA_CATALOG: s\n\n| # | Category | Fix | Delta | Site |\n|---|---|---|---|---|\n| 1 | Behavioral-silent | Judgment | Locale default changed | `unit/src/Main.java:12` |\n" + "| 2 | API-removed | Mechanical | Old API gone | `unit/src/Other.java:3` |\n") def setUp(self): self.root = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, self.root, True) put(self.root, "legacy/s/pom.xml", "<project/>", T0) + put(self.root, "legacy/s/unit/src/test/MainTest.java", "class MainTest { Main m; }\n", T0) put(self.root, "analysis/s/PREFLIGHT.md", "x", T0 + 10) put(self.root, "analysis/s/BASELINE.md", self.BASE, T0 + 10) + put(self.root, "analysis/s/baseline/results.json", json.dumps({"T#a": "PASS", "T#b": "PASS", "T#c": "FAIL", "T#d": "SKIP"}), T0 + 5) + put(self.root, "analysis/s/DELTA_CATALOG.md", self.CATALOG, T0 + 10) put(self.root, "modernized/s-uplifted/unit/src/Main.java", "class Main {}\n", T0 + 20) + put(self.root, "modernized/s-uplifted/unit/src/test/MainTest.java", "class MainTest { Main m; }\n", T0 + 20) put(self.root, "modernized/s-uplifted/UPLIFT_NOTES.md", "Canary: break a comparison -> 2 tests failed\n", T0 + 20) put(self.root, "analysis/s/equivalence/canary/TEST-C.xml", junit([("T", "a", "FAIL", ""), ("T", "b", "FAIL", "")]), T0 + 35) self.results([("T", "a", "PASS", ""), ("T", "b", "PASS", ""), ("T", "c", "FAIL", ""), ("T", "d", "SKIP", "")]) @@ -1134,6 +1444,187 @@ class ProofUplift(unittest.TestCase): self.assertEqual(m["verdict"], "PARTLY PROVEN") self.assertIn("BASELINE.md is missing", " ".join(m["reasons"])) + def states(self): + return {c["id"]: c["state"] for c in self.module()["checks"]} + + def test_all_nine_checks_pass_for_a_clean_uplift(self): + m = self.module() + self.assertEqual(self.states(), {"tests": "pass", "rules": "na", "same": "pass", "fresh": "pass", "canary": "pass", "source": "pass", "baseline": "pass", "kept": "pass", "deltas": "pass"}) + self.assertEqual(m["evidence"]["baselineEvidence"]["kind"], "measured") + self.assertEqual(m["evidence"]["deltas"]["silent"], 1) + + # -- (1) a measured baseline + def test_a_baseline_typed_by_hand_is_a_gap_and_says_so_in_plain_words(self): + os.remove(os.path.join(self.root, "analysis", "s", "baseline", "results.json")) + m = self.module() + self.assertEqual((m["verdict"], self.states()["baseline"], self.states()["same"]), ("PARTLY PROVEN", "gap", "pass")) + detail = next(c["detail"] for c in m["checks"] if c["id"] == "baseline") + self.assertIn("typed by hand", detail) + self.assertIn("analysis/<system>/baseline/", detail) + self.assertIn("Recorded:", detail) + self.assertIn("### Baseline evidence", pp.render_md(pp.overall(pp.build("s", self.root, now="x")))) + + def test_a_forged_counts_file_is_not_evidence(self): + os.remove(os.path.join(self.root, "analysis", "s", "baseline", "results.json")) + put(self.root, "analysis/s/baseline/counts.json", json.dumps({"PASS": 2, "FAIL": 1, "SKIP": 1, "executed": 3}), T0 + 5) + put(self.root, "analysis/s/baseline/counts2.json", json.dumps({"tests": {"count": 3}}), T0 + 5) + m = self.module() + self.assertEqual(self.states()["baseline"], "gap") + info = m["evidence"]["baselineEvidence"] + self.assertEqual(info["kind"], "typed") + self.assertIn("counts.json", info["ignored"]) + self.assertIn("Files that only hold counts were ignored", next(c["detail"] for c in m["checks"] if c["id"] == "baseline")) + + def test_only_the_baseline_folder_and_recorded_lines_are_looked_at(self): + os.remove(os.path.join(self.root, "analysis", "s", "baseline", "results.json")) + put(self.root, "analysis/s/harness/stray.json", json.dumps({"T#a": "PASS", "T#b": "PASS", "T#c": "FAIL", "T#d": "SKIP"}), T0 + 5) + put(self.root, "analysis/s/BASELINE.md", self.BASE + "\nSee also `analysis/s/harness/stray.json` for the details.\n", T0 + 10) + self.assertEqual(self.states()["baseline"], "gap") # a path in prose is not evidence + put(self.root, "analysis/s/BASELINE.md", self.BASE + "\n- **Recorded:** 2026-09-24. Machine-readable per-test results: `analysis/s/harness/stray.json`\n", T0 + 10) + self.assertEqual(self.states()["baseline"], "pass") + put(self.root, "analysis/s/BASELINE.md", self.BASE + "\nMachine-readable: harness/stray.json\n", T0 + 10) + self.assertEqual(self.states()["baseline"], "pass") # relative to analysis/<system>/ + + def test_evidence_outside_analysis_or_through_a_link_is_never_used(self): + outside = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, outside, True) + full = json.dumps({"T#a": "PASS", "T#b": "PASS", "T#c": "FAIL", "T#d": "SKIP"}) + put(outside, "results.json", full) + os.remove(os.path.join(self.root, "analysis", "s", "baseline", "results.json")) + put(self.root, "analysis/other/results.json", full, T0 + 5) + put(self.root, "modernized/results.json", full, T0 + 5) + make_symlink(self, os.path.join(outside, "results.json"), os.path.join(self.root, "analysis", "s", "baseline", "link.json")) + make_symlink(self, outside, os.path.join(self.root, "analysis", "s", "linked")) + for line in ("Recorded: `../other/results.json`", "Recorded: `analysis/other/results.json`", "Recorded: `analysis/s/../other/results.json`", "Recorded: `modernized/results.json`", + "Recorded: `%s/results.json`" % outside, "Recorded: `analysis/s/linked/results.json`", "Recorded: `analysis/s/baseline/link.json`"): + put(self.root, "analysis/s/BASELINE.md", self.BASE + "\n" + line + "\n", T0 + 10) + self.assertEqual(self.states()["baseline"], "gap", line) + + def test_baseline_sources_that_disagree_are_a_gap_not_first_one_wins(self): + put(self.root, "analysis/s/baseline/second.json", json.dumps({"T#a": "FAIL", "T#b": "PASS"}), T0 + 5) + m = self.module() + self.assertEqual(self.states()["baseline"], "gap") + detail = next(c["detail"] for c in m["checks"] if c["id"] == "baseline") + self.assertIn("disagree with each other", detail) + self.assertIn("T#a: PASS in one source, FAIL in second.json", detail) # the example names the test and the file + put(self.root, "analysis/s/baseline/second.json", json.dumps({"T#a": "PASS"}), T0 + 5) # agrees on what they share + self.assertEqual(self.states()["baseline"], "pass") + put(self.root, "analysis/s/baseline/old.test-output.txt", "Tests run: 9, Failures: 0, Errors: 0, Skipped: 0\n", T0 + 5) # a log with other totals + self.assertEqual(self.states()["baseline"], "gap") + + def test_a_typed_table_that_disagrees_with_its_evidence_is_a_gap(self): + put(self.root, "analysis/s/baseline/results.json", json.dumps({"T#a": "PASS", "T#b": "FAIL", "T#c": "FAIL", "T#d": "SKIP"}), T0 + 5) + m = self.module() + self.assertEqual(self.states()["baseline"], "gap") + self.assertIn("disagree on 1 test", next(c["detail"] for c in m["checks"] if c["id"] == "baseline")) + self.assertEqual(m["evidence"]["baselineEvidence"]["disagree"], 1) + + def test_a_raw_runner_log_can_measure_the_baseline_and_must_match_the_typed_counts(self): + os.remove(os.path.join(self.root, "analysis", "s", "baseline", "results.json")) + put(self.root, "analysis/s/baseline/old.test-output.txt", "[INFO] Tests run: 4, Failures: 1, Errors: 0, Skipped: 1\n", T0 + 5) # 3 executed, 1 failed, 1 skipped + m = self.module() + self.assertEqual(self.states()["baseline"], "pass") + self.assertIn("runner log", next(c["detail"] for c in m["checks"] if c["id"] == "baseline")) + put(self.root, "analysis/s/baseline/old.test-output.txt", "[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 1\n", T0 + 5) + self.assertEqual(self.states()["baseline"], "gap") + + def test_target_only_and_a_missing_baseline_leave_the_measured_check_not_applicable(self): + put(self.root, "analysis/s/BASELINE.md", "target-only: Java 8 is not installed here\n", T0 + 10) + self.assertEqual(self.states()["baseline"], "na") + os.remove(os.path.join(self.root, "analysis", "s", "BASELINE.md")) + self.assertEqual((self.states()["baseline"], self.states()["same"]), ("na", "gap")) + + def test_measured_per_test_results_are_what_the_new_run_is_compared_with(self): + put(self.root, "analysis/s/baseline/results.json", json.dumps({"T#a": "PASS", "T#b": "PASS", "T#c": "FAIL", "T#d": "SKIP", "T#extra": "PASS"}), T0 + 5) + self.results([("T", "a", "PASS", ""), ("T", "b", "PASS", ""), ("T", "c", "FAIL", ""), ("T", "d", "SKIP", "")]) + m = self.module() + self.assertEqual(m["evidence"]["baseline"]["source"], "measured results") + self.assertEqual(self.states()["same"], "gap") # T#extra was measured on the old version and did not run now + self.assertEqual(self.states()["baseline"], "pass") # the typed table lists fewer tests than were measured, and agrees on all it lists + self.assertTrue(any("did not run now" in r for r in m["reasons"])) + + def test_a_totals_table_typed_beside_the_rows_must_match_the_evidence_too(self): + put(self.root, "analysis/s/BASELINE.md", self.BASE + "\n## Totals\n\n| | Count |\n|---|---|\n| Executed | 50 |\n| Failed | 0 |\n", T0 + 10) + m = self.module() + self.assertEqual(self.states()["baseline"], "gap") + self.assertIn("Totals table says 50 executed", " ".join(m["evidence"]["baselineEvidence"]["examples"])) + put(self.root, "analysis/s/BASELINE.md", self.BASE + "\n## Totals\n\n| | Count |\n|---|---|\n| Executed | 3 |\n| Failed | 1 |\n", T0 + 10) + self.assertEqual(self.states()["baseline"], "pass") + + # -- (2) tests changed during the uplift + def test_a_removed_legacy_test_file_is_a_gap_and_the_list_says_which(self): + os.remove(os.path.join(self.root, "modernized", "s-uplifted", "unit", "src", "test", "MainTest.java")) + m = self.module() + self.assertEqual((m["verdict"], self.states()["kept"]), ("PARTLY PROVEN", "gap")) + detail = next(c["detail"] for c in m["checks"] if c["id"] == "kept") + self.assertIn("MainTest.java", detail) + self.assertIn("edited or deleted", detail) + self.assertEqual(m["evidence"]["testsChanged"]["removed"][0]["path"], "unit/src/test/MainTest.java") + self.assertTrue(any("Review the test files" in n for n in m["needsPerson"])) + + def test_more_than_a_quarter_of_the_test_files_changed_is_a_gap_and_a_quarter_is_not(self): + for i in range(3): + put(self.root, "legacy/s/unit/src/test/T%d.java" % i, "class T%d { int a = 1; }\n" % i, T0) + put(self.root, "modernized/s-uplifted/unit/src/test/T%d.java" % i, "class T%d { int a = 1; }\n" % i, T0 + 20) + put(self.root, "modernized/s-uplifted/unit/src/test/T0.java", "class T0 { int a = 2; }\n", T0 + 20) # 1 of 4 changed: exactly a quarter + m = self.module() + self.assertEqual(self.states()["kept"], "pass") + self.assertEqual(m["evidence"]["testsChanged"]["changed"][0], {"path": "unit/src/test/T0.java", "added": 1, "removed": 1, "note": ""}) + self.assertTrue(any("1 changed" in n for n in m["needsPerson"])) + put(self.root, "modernized/s-uplifted/unit/src/test/T1.java", "class T1 { int a = 2; }\n", T0 + 20) # 2 of 4 + m = self.module() + self.assertEqual(self.states()["kept"], "gap") + self.assertIn("2 of 4 legacy test files (50%) were changed", next(c["detail"] for c in m["checks"] if c["id"] == "kept")) + + def test_no_legacy_tests_or_no_legacy_tree_is_a_gap(self): + os.remove(os.path.join(self.root, "legacy", "s", "unit", "src", "test", "MainTest.java")) + m = self.module() + self.assertEqual(self.states()["kept"], "gap") + self.assertIn("nothing shows that the working copy's tests were not written during the uplift", next(c["detail"] for c in m["checks"] if c["id"] == "kept")) + shutil.rmtree(os.path.join(self.root, "legacy")) + m = self.module() + self.assertEqual(self.states()["kept"], "gap") + self.assertIn("legacy tree was not found", next(c["detail"] for c in m["checks"] if c["id"] == "kept")) + + def test_added_tests_are_listed_and_never_a_gap(self): + put(self.root, "modernized/s-uplifted/unit/src/test/NewCharacterizationTest.java", "class NewCharacterizationTest { Main m; }\n", T0 + 20) + m = self.module() + self.assertEqual(self.states()["kept"], "pass") + self.assertEqual(m["evidence"]["testsChanged"]["added"], [{"path": "unit/src/test/NewCharacterizationTest.java", "lines": 2}]) + md = pp.render_md(pp.overall(pp.build("s", self.root, now="x"))) + self.assertIn("### Test files changed during the uplift", md) + self.assertIn("Added: `unit/src/test/NewCharacterizationTest.java`", md) + self.assertIn("Weakened assertions cannot be detected", md) + self.assertTrue(any("Weakened assertions cannot be detected" in n for n in m["notProven"])) + + # -- (3) delta coverage + def test_a_silent_delta_no_test_names_is_a_gap_and_other_categories_are_only_listed(self): + put(self.root, "analysis/s/DELTA_CATALOG.md", self.CATALOG + "| 3 | Behavioral-silent | Judgment | Rounding changed | `unit/src/Money.java:40` |\n", T0 + 10) + m = self.module() + self.assertEqual((m["verdict"], self.states()["deltas"]), ("PARTLY PROVEN", "gap")) + detail = next(c["detail"] for c in m["checks"] if c["id"] == "deltas") + self.assertIn("1 of 2 Behavioral-silent", detail) + self.assertIn("no test names Money", detail) + self.assertEqual(m["evidence"]["deltas"]["uncovered"][0]["id"], "3") + self.assertIn("Not named by any test: 3 Rounding changed", pp.render_md(pp.overall(pp.build("s", self.root, now="x")))) + put(self.root, "modernized/s-uplifted/unit/src/test/MoneyTest.java", "class MoneyTest { Money m; }\n", T0 + 20) + self.assertEqual(self.states()["deltas"], "pass") + + def test_a_missing_or_unreadable_catalog_is_a_gap(self): + os.remove(os.path.join(self.root, "analysis", "s", "DELTA_CATALOG.md")) + m = self.module() + self.assertEqual(self.states()["deltas"], "gap") + self.assertIn("DELTA_CATALOG.md was not found", next(c["detail"] for c in m["checks"] if c["id"] == "deltas")) + put(self.root, "analysis/s/DELTA_CATALOG.md", "Some prose about the version change. No table, no cards.\n", T0 + 10) + self.assertEqual(self.states()["deltas"], "gap") + + def test_a_delta_at_a_build_file_is_listed_for_a_person_not_judged(self): + put(self.root, "analysis/s/DELTA_CATALOG.md", self.CATALOG + "| 4 | Behavioral-silent | Judgment | Bundle plugin | `pom.xml:629` |\n", T0 + 10) + m = self.module() + self.assertEqual(self.states()["deltas"], "pass") + self.assertEqual(m["evidence"]["deltas"]["config"][0]["id"], "4") + self.assertTrue(any("build or configuration file" in n for n in m["needsPerson"])) + def test_a_unit_argument_narrows_the_suites_and_an_unknown_name_is_an_error(self): pack = pp.build("s", self.root, "unit", now="x") self.assertEqual(pack["modules"][0]["name"], "s-uplifted") @@ -1158,6 +1649,22 @@ def good_pack(**module_change): return {"v": 1, "system": "s", "generated": "2026-09-24 00:00 UTC", "problems": [], "legacy": {"path": "legacy/s", "ran": True}, "modules": [m], "signoff": {}, "rules": ["PROVEN needs all six checks."]} +def good_uplift_pack(**evidence): + """A pack for an uplift whose nine checks all pass, with the evidence that backs them; a test changes the evidence and looks at the view.""" + pack = good_pack() + m = pack["modules"][0] + m.update(name="s-uplifted", track="uplift") + m["checks"] = [c for c in m["checks"] if c["id"] != "rules"] + [{"id": "rules", "label": "Rules traced", "state": "na", "detail": "An uplift keeps the code."}] + [ + {"id": cid, "label": label, "state": "pass", "detail": "fine"} for cid, label in br.UPLIFT_CHECKS] + m["evidence"].pop("rules", None) + m["evidence"].update(baselineEvidence={"kind": "measured", "sources": [{"kind": "machine-readable results", "name": "base.json", "tests": 40}], "disagree": 0, "conflict": 0, "examples": [], "considered": ["base.json"]}, + testsChanged={"checked": True, "why": "", "legacyTests": 8, "workTests": 9, "counts": {"added": 1, "removed": 0, "changed": 1}, "share": 0.125, + "removed": [], "added": [{"path": "t/NewTest.java", "lines": 12}], "changed": [{"path": "t/OldTest.java", "added": 3, "removed": 1, "note": ""}]}, + deltas={"parsed": 5, "silent": 2, "covered": [{"id": "1"}, {"id": "2"}], "uncovered": [], "config": [{"id": "4", "title": "Bundle plugin", "sites": ["pom.xml:9"]}], "other": 3, "gap": False}) + m["evidence"].update(evidence) + return pack + + class ProofReport(unittest.TestCase): def setUp(self): self.root = tempfile.mkdtemp() @@ -1223,6 +1730,71 @@ class ProofReport(unittest.TestCase): self.assertIn("missing from VERIFICATION.json", pv["modules"][0]["reasons"][0]) self.assertEqual(self.proof(self.report(dict(good_pack(), modules=[])))[1]["verdict"], "NOT PROVEN") + def test_an_uplift_needs_its_three_extra_checks_and_a_rewrite_does_not(self): + _, pv = self.proof(self.report(good_uplift_pack())) + m = pv["modules"][0] + self.assertEqual((m["verdict"], [c["id"] for c in m["checks"]]), ("PROVEN", ["tests", "rules", "same", "fresh", "canary", "source", "baseline", "kept", "deltas"])) + self.assertEqual(m["uplift"]["testsChanged"]["counts"], {"added": 1, "removed": 0, "changed": 1}) + self.assertEqual(m["uplift"]["deltas"]["coveredCount"], 2) + pack = good_uplift_pack() + pack["modules"][0]["checks"] = [c for c in pack["modules"][0]["checks"] if c["id"] != "kept"] + _, pv = self.proof(self.report(pack)) + self.assertEqual(pv["modules"][0]["verdict"], "PARTLY PROVEN") + self.assertIn("tests kept check is missing", " ".join(pv["problems"])) + _, pv = self.proof(self.report(good_pack())) # a rewrite never needs them + self.assertEqual((pv["modules"][0]["verdict"], len(pv["modules"][0]["checks"]), pv["modules"][0]["uplift"]), ("PROVEN", 6, None)) + + def test_forged_uplift_passes_are_downgraded_by_the_evidence_beside_them(self): + cases = (("baseline", {"baselineEvidence": {"kind": "typed"}}), ("baseline", {"baselineEvidence": {"kind": "measured", "disagree": 2}}), ("baseline", {"baselineEvidence": {"kind": "measured", "conflict": 1}}), + ("kept", {"testsChanged": {"checked": False}}), ("kept", {"testsChanged": {"checked": True, "legacyTests": 0, "counts": {}}}), + ("kept", {"testsChanged": {"checked": True, "legacyTests": 8, "counts": {"removed": 1, "changed": 0, "added": 0}}}), + ("kept", {"testsChanged": {"checked": True, "legacyTests": 8, "counts": {"removed": 0, "changed": 3, "added": 0}}}), + ("deltas", {"deltas": {"parsed": 4, "silent": 1, "covered": [], "uncovered": [{"id": "9"}]}}), ("deltas", {"deltas": {"parsed": 0}}), ("deltas", {"deltas": "nope"})) + for cid, change in cases: + _, pv = self.proof(self.report(good_uplift_pack(**change))) + m = pv["modules"][0] + self.assertEqual({c["id"]: c["state"] for c in m["checks"]}[cid], "gap", (cid, change)) + self.assertEqual(m["verdict"], "PARTLY PROVEN", (cid, change)) + for state in ("na", "gap"): # "not applicable" is no way out for the kept and deltas checks + pack = good_uplift_pack(testsChanged={"checked": False}, deltas={"parsed": 0}) + for c in pack["modules"][0]["checks"]: + if c["id"] in ("kept", "deltas"): + c["state"] = state + self.assertEqual(self.proof(self.report(pack))[1]["modules"][0]["verdict"], "PARTLY PROVEN") + pack = good_uplift_pack(baselineEvidence={"kind": "target-only"}) + for c in pack["modules"][0]["checks"]: + if c["id"] == "baseline": + c["state"] = "na" + self.assertEqual(self.proof(self.report(pack))[1]["modules"][0]["checks"][6]["state"], "na") # a target-only baseline may say so + + def test_the_uplift_evidence_is_cut_and_cleaned(self): + evil = "<script>alert(1)</script>" + chr(0x2028) + _, pv = self.proof(self.report(good_uplift_pack( + baselineEvidence={"kind": evil, "sources": [{"kind": evil * 5, "name": evil}] * 50, "disagree": "x", "examples": [evil * 20] * 20, "considered": [evil] * 50}, + testsChanged={"checked": True, "legacyTests": 8, "workTests": 8, "counts": {"added": 1, "removed": 0, "changed": 0}, "share": "x", "added": [{"path": evil * 20, "lines": "x"}] * 300, "removed": "x", "changed": [1, None]}, + deltas={"parsed": 3, "silent": 1, "covered": [], "uncovered": [{"id": evil * 5, "title": evil * 10, "why": evil * 10, "sites": [evil] * 20}] * 300, "config": "x"}))) + up = pv["modules"][0]["uplift"] + self.assertEqual(up["baseline"]["kind"], "none") + self.assertLessEqual((len(up["baseline"]["sources"]), len(up["baseline"]["examples"]), len(up["testsChanged"]["added"]), len(up["deltas"]["uncovered"])), (10, 5, 40, 40)) + self.assertEqual((up["testsChanged"]["share"], up["testsChanged"]["added"][0]["lines"], up["testsChanged"]["removed"], up["deltas"]["config"]), (0.0, 0, [], [])) + self.assertGreater(up["deltas"]["uncoveredCount"], 0) + self.assertEqual(pv["modules"][0]["verdict"], "PARTLY PROVEN") + + def test_a_real_uplift_pack_from_proof_pack_carries_its_evidence_to_the_report(self): + base = ProofUplift("test_all_nine_checks_pass_for_a_clean_uplift") + base.setUp() + base.addCleanup(shutil.rmtree, base.root, True) + put(base.root, "modernized/s-uplifted/unit/src/test/NewCharacterizationTest.java", "class NewCharacterizationTest { Main m; }\n", T0 + 20) + run_main(pp.main, ["s", "--workspace", base.root]) + run_main(br.main, ["s", "--workspace", base.root]) + data = page_data(read(os.path.join(base.root, "analysis", "s", "REPORT.html"))) + pv = next(p["proof"] for sec in data["sections"] if sec["id"] == "proof" for p in sec["parts"]) + m = pv["modules"][0] + self.assertEqual((pv["verdict"], len(m["checks"])), ("PROVEN", 9)) + self.assertEqual(m["uplift"]["testsChanged"]["added"][0]["path"], "unit/src/test/NewCharacterizationTest.java") + self.assertEqual(m["uplift"]["baseline"]["kind"], "measured") + self.assertEqual(m["uplift"]["deltas"]["silent"], 1) + def test_a_real_pack_written_by_proof_pack_renders_the_same_verdict(self): ws = Ws(self) put(ws.root, "modernized/s/mod/src/test/CalcTest.java", "// RULE-001\n", T0 + 20) @@ -1316,6 +1888,11 @@ class ProofScript(unittest.TestCase): good_pack(name=evil, track=evil, notProven=[evil], brief={"found": True, "count": 900, "items": [{"text": evil, "where": evil}]}, evidence={"tests": {"executed": 1}, "rules": {"p0": [{"id": evil, "name": evil, "status": "__proto__", "tests": 1, "main": 1, "where": evil}] * 200}}), dict(good_pack(), legacy={"path": evil, "target": evil, "ran": False}, problems=[evil], signoff={"name": evil, "role": "", "date": "", "decision": ""})] + packs.append(good_uplift_pack(deltas={"parsed": 5, "silent": 2, "covered": [{"id": "1"}], "uncovered": [{"id": "2", "title": "Rounding changed", "why": "no test names Money", "sites": ["Money.java:4"]}], + "config": [{"id": "4", "title": "Bundle plugin", "sites": ["pom.xml:9"]}]}, + testsChanged={"checked": True, "legacyTests": 8, "workTests": 8, "counts": {"added": 0, "removed": 1, "changed": 0}, "share": 0.0, + "removed": [{"path": "t/GoneTest.java", "lines": 7}], "added": [], "changed": []}, + baselineEvidence={"kind": "typed", "sources": [], "disagree": 0, "conflict": 0, "examples": [], "considered": [], "ignored": ["counts.json"]})) views = [br.proof_view(p) for p in packs] views[3]["verdict"] = "__proto__" views[3]["modules"][0]["verdict"] = "constructor" @@ -1358,6 +1935,14 @@ class ProofScript(unittest.TestCase): self.assertIn(needle, text) self.assertIn("It could not run here, so the proof is trace-based.", self.out[4]["text"]) + def test_an_uplift_shows_its_baseline_test_files_and_deltas(self): + text = self.out[5]["text"] + for needle in ("Baseline evidence: typed by hand", "Test files: 8 in the legacy tree, 8 in the working copy: 1 removed, 0 added, 0 changed", "Removed test files", "t/GoneTest.java (7 lines)", + "2 Behavioral-silent: 1 have a test naming their site, 1 do not", "Not named by any test", "2 Rounding changed (no test names Money)", + "At a build or configuration file (for a person)", "4 Bundle plugin (pom.xml:9)", "Baseline measured", "Tests kept", "Deltas covered"): + self.assertIn(needle, text) + self.assertNotIn("Baseline evidence: typed by hand", self.out[0]["text"]) + def test_the_template_keeps_its_own_contract(self): with open(TEMPLATE, encoding="utf-8") as fh: text = fh.read() diff --git a/plugins/code-modernization/scripts/uplift_checks.py b/plugins/code-modernization/scripts/uplift_checks.py new file mode 100644 index 00000000..33af819c --- /dev/null +++ b/plugins/code-modernization/scripts/uplift_checks.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Two checks that only an uplift needs, for the proof pack (proof_pack.py imports this; it also runs on its own). + + python3 uplift_checks.py <legacy folder> <working copy> [DELTA_CATALOG.md] + +An uplift keeps the code and the tests and changes the version underneath. A green test run then proves less than it seems to in two ways: + + Tests changed during the uplift. The test files of the untouched legacy tree are compared with those of the working copy by walking + files only (no process is run, no link followed, build output skipped). A test file is a test file by the rules trace_rules.py uses. + Removed, added and changed files are listed with a line-diff count. A removed test file, more than 25% of the legacy test files + changed, or a legacy tree with no test files to compare against, is a gap: passing edited or deleted tests proves less, so a person reviews the list. Weakened assertions cannot be detected, + only that files changed. + + Deltas covered. DELTA_CATALOG.md lists the version changes that hit this code. For every delta whose category says Behavioral-silent + (the kind nothing reports when it changes behavior) the file of each listed site must be named, as a whole word, by some test file of + the working copy. A name is not proof that the test exercises the changed behavior; a silent delta no test even names is untested. + Other categories are listed, not judged. + +Everything read is untrusted text: files are only read, links are not followed, sizes and counts are capped, and no pattern here can be made +slow by a hostile line. Exit 0 when neither check finds a gap, 1 when one does, 2 for input that cannot be used. +""" +import argparse +import difflib +import hashlib +import json +import os +import re +import stat +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.dont_write_bytecode = True +sys.path.insert(0, HERE) +import baseline_diff # noqa: E402 +import trace_rules # noqa: E402 + +LIST_CAP, FILE_CAP, HASH_CAP, MAX_FILES, TEXT_CAP = 40, 2 << 20, 64 << 20, 60000, 400 << 20 +DIFF_LINES, DIFF_BUDGET, SHARE_LIMIT = 4000, 300000000, 0.25 +DELTA_CAP, CATALOG_CAP, LINE_CAP = 2000, 8 << 20, 4000 +SILENT = re.compile(r"behaviou?ral[\s_-]*silent|silent[\s_-]*behaviou?ral", re.I) +CONFIG_EXT = {"xml", "yml", "yaml", "json", "properties", "gradle", "toml", "ini", "cfg"} # build and configuration files: a test cannot name them +CODE_EXT = {"java", "kt", "kts", "scala", "groovy", "cs", "vb", "fs", "py", "js", "jsx", "ts", "tsx", "mjs", "cjs", "go", "rs", "rb", "php", "c", "h", "cc", "cpp", "hpp", "swift", + "m", "sql", "cbl", "cob", "cpy", "jcl", "pl", "pm", "sh", "ps1", "xml", "yml", "yaml", "json", "properties", "gradle", "toml", "ini", "cfg"} +# path/Stem.ext:line, or path/Stem.ext for a known extension; every quantifier is bounded, so a hostile line cannot make it slow +SITE = re.compile(r"((?:[\w.$@+-]{1,80}/){0,12})([A-Za-z_$][\w$-]{0,80})((?:\.[A-Za-z][A-Za-z0-9]{0,7}){1,3})(?::(\d{1,7}))?") +WORD = re.compile(r"[A-Za-z_$][\w$]{0,200}") +DASHED = re.compile(r"[A-Za-z0-9_$]{1,100}(?:-[A-Za-z0-9_$]{1,100}){1,8}") +clean = trace_rules.clean + + +# ---------------------------------------------------------------- walking test files +def walk_tests(root): + """({relative path: absolute path}, cut short, links skipped) for every regular test file under `root`. + A test file is one trace_rules.file_kind calls a test. Links, hidden folders and build output are never entered.""" + out, links = {}, 0 + if os.path.islink(root) or not os.path.isdir(root): + return out, False, 0 + for base, dirs, names in os.walk(root, followlinks=False): + keep = [] + for d in sorted(dirs): + if d in trace_rules.SKIP_DIRS or d.startswith("."): + continue + if os.path.islink(os.path.join(base, d)): + links += 1 + continue + keep.append(d) + dirs[:] = keep + for n in sorted(names): + full = os.path.join(base, n) + if n.startswith("."): + continue + try: + st = os.lstat(full) + except OSError: + continue + if stat.S_ISLNK(st.st_mode): + links += 1 + continue + rel = os.path.relpath(full, root).replace(os.sep, "/") + if stat.S_ISREG(st.st_mode) and trace_rules.file_kind(rel) == "test": + out[rel] = full + if len(out) >= MAX_FILES: + return out, True, links + return out, False, links + + +def read_head(path, cap=FILE_CAP): + """Up to cap+1 bytes of a file, or None.""" + try: + with open(path, "rb") as fh: + return fh.read(cap + 1) + except OSError: + return None + + +def digest(path): + """sha256 of a file's bytes (read in blocks, at most HASH_CAP), or None.""" + h, n = hashlib.sha256(), 0 + try: + with open(path, "rb") as fh: + while n < HASH_CAP: + block = fh.read(1 << 20) + if not block: + break + h.update(block) + n += len(block) + except OSError: + return None + return h.hexdigest() + + +def count_lines(path): + """Number of lines of a text file (0 for a binary or unreadable one).""" + raw = read_head(path) + return len(as_lines(raw)) if raw is not None and b"\x00" not in raw[:8192] else 0 + + +def as_lines(raw): + return raw.decode("utf-8", "replace").replace("\r\n", "\n").replace("\r", "\n").split("\n") + + +def line_diff(a, b, budget): + """(lines added, lines removed) turning list a into list b. difflib for files of ordinary size while the budget lasts, else a count of + lines that appear more often on one side (order is ignored, which is the price of being fast). -> (added, removed, exact, budget left).""" + if len(a) <= DIFF_LINES and len(b) <= DIFF_LINES and len(a) * len(b) <= budget: + added = removed = 0 + for tag, i1, i2, j1, j2 in difflib.SequenceMatcher(None, a, b, autojunk=False).get_opcodes(): + if tag in ("replace", "delete"): + removed += i2 - i1 + if tag in ("replace", "insert"): + added += j2 - j1 + return added, removed, True, budget - len(a) * len(b) + ca, cb = {}, {} + for line in a: + ca[line] = ca.get(line, 0) + 1 + for line in b: + cb[line] = cb.get(line, 0) + 1 + return (sum(max(0, n - ca.get(k, 0)) for k, n in cb.items()), sum(max(0, n - cb.get(k, 0)) for k, n in ca.items()), False, budget) + + +def compare_files(old, new, budget): + """None when the two files hold the same content (line endings aside), else ({"added", "removed", "note"}, budget left).""" + ra, rb = read_head(old), read_head(new) + if ra is None or rb is None: + return {"added": 0, "removed": 0, "note": "could not be read"}, budget + if len(ra) > FILE_CAP or len(rb) > FILE_CAP: + da, db = digest(old), digest(new) + return (None, budget) if da is not None and da == db else ({"added": 0, "removed": 0, "note": "large file, lines not counted"}, budget) + if b"\x00" in ra[:8192] or b"\x00" in rb[:8192]: + return (None, budget) if ra == rb else ({"added": 0, "removed": 0, "note": "binary file"}, budget) + la, lb = as_lines(ra), as_lines(rb) + if la == lb: + return None, budget + added, removed, exact, budget = line_diff(la, lb, budget) + return {"added": added, "removed": removed, "note": "" if exact else "lines counted approximately"}, budget + + +# ---------------------------------------------------------------- tests changed during the uplift +def tests_changed(legacy_root, work_root): + """Compare the test files of the untouched legacy tree with those of the working copy. + -> {"checked", "why", "legacyTests", "workTests", "counts": {added, removed, changed}, "added", "removed", "changed" (lists cut to 40), "share", "gap", "cut"}.""" + out = {"checked": False, "why": "", "legacyTests": 0, "workTests": 0, "counts": {"added": 0, "removed": 0, "changed": 0}, "added": [], "removed": [], "changed": [], + "share": 0.0, "gap": False, "cut": False} + if not legacy_root or not os.path.isdir(legacy_root): + out["why"] = "the legacy tree was not found, so its test files could not be compared with the working copy's" + return out + if not work_root or not os.path.isdir(work_root): + out["why"] = "the working copy was not found" + return out + old, cut_a, _ = walk_tests(legacy_root) + new, cut_b, _ = walk_tests(work_root) + out.update({"checked": True, "legacyTests": len(old), "workTests": len(new), "cut": cut_a or cut_b}) + removed = sorted(set(old) - set(new)) + added = sorted(set(new) - set(old)) + changed, budget = [], DIFF_BUDGET + for rel in sorted(set(old) & set(new)): + got, budget = compare_files(old[rel], new[rel], budget) + if got is not None: + changed.append(dict(got, path=clean(rel, 300))) + out["counts"] = {"added": len(added), "removed": len(removed), "changed": len(changed)} + changed.sort(key=lambda c: (-(c["added"] + c["removed"]), c["path"])) + out["removed"] = [{"path": clean(r, 300), "lines": count_lines(old[r])} for r in removed[:LIST_CAP]] + out["added"] = [{"path": clean(r, 300), "lines": count_lines(new[r])} for r in added[:LIST_CAP]] + out["changed"] = changed[:LIST_CAP] + out["share"] = round(len(changed) / len(old), 4) if old else 0.0 + out["gap"] = bool(removed) or not old or len(changed) > SHARE_LIMIT * len(old) + if not old: + out["why"] = "the legacy tree has no test files, so nothing shows that the working copy's tests were not written during the uplift" + return out + + +# ---------------------------------------------------------------- reading DELTA_CATALOG.md +def norm_id(text): + return re.sub(r"[\s*`#.]+", "", text or "").lower()[:40] + + +def sites_in(text): + """[{"path", "stem", "line"}] for every file mention in `text` that is a file:line, or a file with a known extension.""" + out = [] + for m in SITE.finditer(text[:LINE_CAP]): + ext = m.group(3).lstrip(".").split(".")[-1].lower() + stem = m.group(2) + if len(stem) < 2 or (m.group(4) is None and ext not in CODE_EXT): + continue + site = {"path": clean((m.group(1) + stem + m.group(3)), 200), "stem": stem, "line": int(m.group(4)) if m.group(4) else 0, "ext": ext} + if not any(o["path"] == site["path"] for o in out): + out.append(site) + return out[:20] + + +def add_delta(found, did, title, category, sites): + key = norm_id(did) + if not key or (len(found) >= DELTA_CAP and key not in found): + return + d = found.setdefault(key, {"id": clean(did.replace("*", "").strip(), 40), "title": "", "category": "", "sites": []}) + d["title"] = d["title"] or clean(title, 200) + d["category"] = d["category"] or clean(category, 80) + d["sites"] += [s for s in sites if not any(o["path"] == s["path"] for o in d["sites"])] + d["sites"] = d["sites"][:20] + + +def parse_deltas(text): + """Deltas from DELTA_CATALOG.md, tolerantly: pipe tables with a Category column (an id in the first or an ID/# column, sites in a + Site column), and cards (`### 9. title` or `### D-01 title`, with a `Category ...:` line and a `cited:` or `Site:` line). + Rows and cards of the same id are merged. -> [{"id", "title", "category", "sites": [{"path", "stem", "line"}]}].""" + found = {} + for _heading, header, rows in baseline_diff.md_tables(text[:CATALOG_CAP]): + low = [h.lower() for h in header] + cat = next((i for i, h in enumerate(low) if re.search(r"\bcat", h)), None) + if cat is None: + continue + idc = next((i for i, h in enumerate(low) if re.fullmatch(r"(?:id|#|no\.?|delta|card|ref)", h.strip())), 0) + titlec = next((i for i, h in enumerate(low) if re.search(r"delta|title|name|change|summary|\bold\b", h) and i != idc), None) + sitec = [i for i, h in enumerate(low) if re.search(r"\bsites?\b|location|cited|file", h)] + for row in rows[:5000]: + if cat >= len(row) or idc >= len(row) or not row[idc].strip(): + continue + cells = [row[i] for i in sitec if i < len(row) and not re.fullmatch(r"\s*\d+\s*", row[i])] + sites = sites_in(" ".join(cells)) if sitec else sites_in(" ".join(c for i, c in enumerate(row) if i not in (cat, idc))) + add_delta(found, row[idc], row[titlec] if titlec is not None and titlec < len(row) else "", row[cat], sites) + lines, i = [ln[:LINE_CAP] for ln in text[:CATALOG_CAP].split("\n")], 0 + while i < len(lines): + m = re.match(r"#{2,6}[ \t]+(?:\*\*)?(D-\d{1,4}|\d{1,4})(?:\*\*)?[.):\s][ \t]*(.*)$", lines[i]) + i += 1 + if not m: + continue + category, sites = "", [] + while i < len(lines) and not lines[i].startswith("#"): + line = lines[i] + c = re.search(r"categor[^:\n]{0,40}:\**[ \t]*(.{1,200})", line, re.I) + if c and not category: + category = re.split(r"[/;]", c.group(1))[0].strip(" *`") + cited = re.search(r"\bcited\s*:", line, re.I) or re.match(r"^[ \t>*-]*\**(?:sites?|location|source)\b[^:\n]{0,30}:", line, re.I) + if cited: # only the site the card cites, never files that its prose merely mentions + sites += [s for s in sites_in(line[cited.end():]) if not any(o["path"] == s["path"] for o in sites)] + i += 1 + if category or norm_id(m.group(1)) in found: # a numbered heading with no Category line is not a delta card + add_delta(found, m.group(1), m.group(2), category, sites) + return list(found.values()) + + +# ---------------------------------------------------------------- deltas covered by tests +def test_words(work_root): + """(the set of words that appear in the working copy's test files, number of test files read). Files are read as text, up to 2 MB each.""" + words, total, files = set(), 0, 0 + tests, _cut, _links = walk_tests(work_root) + for rel in sorted(tests): + raw = read_head(tests[rel]) + if raw is None or b"\x00" in raw[:8192]: + continue + total += len(raw) + if total > TEXT_CAP: + break + text = raw[:FILE_CAP].decode("utf-8", "replace") + words.update(WORD.findall(text)) + words.update(DASHED.findall(text)) + files += 1 + return words, files + + +def delta_coverage(catalog_text, work_root): + """Which Behavioral-silent deltas have their site's file named by a test in the working copy? A delta whose only sites are build or + configuration files cannot be named by a test: it is listed for a person, not judged. + -> {"parsed", "silent", "covered": [...], "uncovered": [...], "config": [...], "other": n, "testFiles", "gap", "why"}.""" + out = {"parsed": 0, "silent": 0, "covered": [], "uncovered": [], "config": [], "other": 0, "testFiles": 0, "gap": False, "why": ""} + if catalog_text is None: + out.update(gap=True, why="DELTA_CATALOG.md was not found, so it is not known which version changes hit this code") + return out + deltas = parse_deltas(catalog_text) + out["parsed"] = len(deltas) + if not deltas: + out.update(gap=True, why="no delta could be read from DELTA_CATALOG.md (a table with a Category column, or cards with a Category line)") + return out + words, out["testFiles"] = test_words(work_root) + for d in deltas: + if not SILENT.search(d["category"]): + out["other"] += 1 + continue + out["silent"] += 1 + code = [s for s in d["sites"] if s["ext"] not in CONFIG_EXT] + rec = {"id": d["id"], "title": d["title"], "sites": [s["path"] + (":%d" % s["line"] if s["line"] else "") for s in d["sites"][:5]]} + if d["sites"] and not code: + out["config"].append(rec) + continue + missing = [s["stem"] for s in code if s["stem"] not in words] + if code and not missing: + out["covered"].append(rec) + else: + rec["why"] = "no site is named in the catalog" if not code else "no test names " + ", ".join(clean(x, 60) for x in list(dict.fromkeys(missing))[:5]) + out["uncovered"].append(rec) + out["gap"] = bool(out["uncovered"]) + return out + + +# ---------------------------------------------------------------- command line +def main(argv=None): + ap = argparse.ArgumentParser(description="Uplift-only checks: test files changed since the legacy tree, and silent deltas no test names.") + ap.add_argument("legacy", help="the untouched legacy folder (legacy/<system>)") + ap.add_argument("work", help="the uplifted working copy (modernized/<system>-uplifted)") + ap.add_argument("catalog", nargs="?", help="analysis/<system>/DELTA_CATALOG.md") + ap.add_argument("--json", action="store_true", help="print the full result as JSON") + args = ap.parse_args(argv) + for path in (args.legacy, args.work): + if not os.path.isdir(path): + print("uplift_checks.py: %s is not a folder" % path, file=sys.stderr) + return 2 + text = None + if args.catalog: + try: + text = baseline_diff.read_capped(args.catalog, CATALOG_CAP).decode("utf-8", "replace") + except baseline_diff.InputError as err: + print("uplift_checks.py: %s" % err, file=sys.stderr) + return 2 + changed = tests_changed(os.path.realpath(args.legacy), os.path.realpath(args.work)) + deltas = delta_coverage(text, os.path.realpath(args.work)) if args.catalog else None + if args.json: + print(json.dumps({"testsChanged": changed, "deltas": deltas}, indent=1, ensure_ascii=True)) + else: + c = changed["counts"] + print("test files: %d in the legacy tree, %d in the working copy; %d removed, %d added, %d changed (%.0f%% of the legacy test files)" % ( + changed["legacyTests"], changed["workTests"], c["removed"], c["added"], c["changed"], 100 * changed["share"])) + for key in ("removed", "changed", "added"): + for e in changed[key][:10]: + print(" %s: %s%s" % (key, e["path"], " (+%d -%d lines)" % (e["added"], e["removed"]) if key == "changed" else "")) + print("tests kept: " + ("GAP" if changed["gap"] else "ok") + ("" if not changed["why"] else " (" + changed["why"] + ")")) + if deltas is not None: + print("deltas: %d parsed, %d behavioral-silent, %d covered, %d not named by any test, %d at a build or configuration file" % ( + deltas["parsed"], deltas["silent"], len(deltas["covered"]), len(deltas["uncovered"]), len(deltas["config"]))) + for d in deltas["uncovered"][:10]: + print(" uncovered: %s %s (%s)" % (d["id"], d["title"], d.get("why", ""))) + print("deltas covered: " + ("GAP" if deltas["gap"] else "ok") + ("" if not deltas["why"] else " (" + deltas["why"] + ")")) + return 1 if changed["gap"] or (deltas is not None and deltas["gap"]) else 0 + + +if __name__ == "__main__": + sys.exit(main()) |
