diff options
| author | Morgan Lunt <morganl@anthropic.com> | 2026-09-25 11:28:44 -0700 |
|---|---|---|
| committer | Morgan Lunt <morganl@anthropic.com> | 2026-09-25 11:28:44 -0700 |
| commit | d49ccb3844876e35262a32f145b7b717646da733 (patch) | |
| tree | cbaefc469ac837a85ac154e797fff20dd1905d62 /plugins/code-modernization/scripts | |
| parent | d3a40f72165764888f9a57a3e93db86e88f8e063 (diff) | |
code-modernization: a rule is tested only if a test that ran backs it
A rule named only by a skipped or pending test no longer counts as covered. It is listed as "named, not run" and fails the rules check. A test-only folder is listed as tooling and gets no verdict. The verify command tries malformed records only when the person asked for exact behavior, so a proof loop has an end. The report parses rule headings and fields in linear time, and the report and pane show the new status.
Diffstat (limited to 'plugins/code-modernization/scripts')
6 files changed, 808 insertions, 77 deletions
diff --git a/plugins/code-modernization/scripts/build_report.py b/plugins/code-modernization/scripts/build_report.py index 942bb2ab..b690eb3f 100644 --- a/plugins/code-modernization/scripts/build_report.py +++ b/plugins/code-modernization/scripts/build_report.py @@ -42,7 +42,7 @@ DOCS = [("overview", ["PREFLIGHT.md"]), ("assessment", ["ASSESSMENT.md"]), ("spec", ["AI_NATIVE_SPEC.md", "REIMAGINED_ARCHITECTURE.md"])] MERMAID_FENCE = re.compile(r"(?m)^ {0,3}(?:`{3,}|~{3,})[ \t]*mermaid\b") ID = r"[A-Z][A-Z0-9]*(?:-[A-Z][A-Z0-9]*)*-\d+[a-z]?" -CARD = re.compile(r"^(#{3,4})[ \t]+[*`]*(" + ID + r")[*`]*(?:[ \t]*[·:\-–—][ \t]*(.*?))?[ \t]*#*[ \t]*$") +CARD = re.compile(r"^(#{3,4})[ \t]+[*`]*(" + ID + r")[*`]*(?:[ \t]*[·:\-–—][ \t]*(.*))?$") # the title's trailing spaces and #s are cut in Python: no nested quantifiers here FENCE = re.compile(r"^ {0,3}(`{3,}|~{3,})") CITE = re.compile(r"[A-Za-z0-9_][\w./+-]*\.[A-Za-z][A-Za-z0-9]{0,7}:\d+(?:-\d+)?(?:,\s*\d+(?:-\d+)?)*") DAY = "%Y-%m-%d" @@ -138,8 +138,10 @@ def tables(text): def field(body, name): - m = re.search(r"(?im)^[ \t>*-]*\**" + name + r"\**[ \t]*:[ \t]*\**[ \t]*(.+?)[ \t]*$", body) - return m.group(1) if m else "" + for m in re.finditer(r"(?im)^[ \t>*-]*\**" + name + r"\**[ \t]*:[ \t]*\**[ \t]*(.*)$", body): + if m.group(1).strip(): + return m.group(1).strip() + return "" def parse_rules(text): @@ -162,11 +164,11 @@ def parse_rules(text): elif f: fence = f.group(1) else: - m, h = CARD.match(line), re.match(r"(#{1,6})\s", line) + m, h = CARD.match(line.rstrip()), re.match(r"(#{1,6})\s", line) if m or (h and card is not None and len(h.group(1)) <= len(card[0])): flush() if m: - card = (m.group(1), m.group(2), (m.group(3) or "").strip(), re.sub(r"^#+\s*", "", line).strip()) + card = (m.group(1), m.group(2), (m.group(3) or "").rstrip(" \t#").strip(), re.sub(r"^#+\s*", "", line).strip()) continue buf.append(line) flush() @@ -323,7 +325,7 @@ 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") +RULE_STATES = ("tested", "named, not run", "claimed only", "code only", "none") FRESH_NEEDED = 10 @@ -444,7 +446,8 @@ def proof_module(m, problems): return {"name": name, "track": text_of(m.get("track"), 20), "verdict": verdict, "verifiedAt": text_of(m.get("verifiedAt"), 40), "checks": checks, "reasons": ["%s: %s" % (c["label"], c["detail"]) for c in checks if c["state"] in ("fail", "gap")], "passed": ["%s: %s" % (c["label"], c["detail"]) for c in checks if c["state"] == "pass"], "tests": tests, "hasRules": rules is not None, "p0": p0, - "p0Counts": {"tested": sum(1 for r in p0 if r["status"] == "tested"), "claimedOnly": sum(1 for r in p0 if r["status"] == "claimed only"), "none": sum(1 for r in p0 if r["status"] not in ("tested", "claimed only"))}, + "p0Counts": {"tested": sum(1 for r in p0 if r["status"] == "tested"), "claimedOnly": sum(1 for r in p0 if r["status"] == "claimed only"), + "notRun": sum(1 for r in p0 if r["status"] == "named, not run"), "none": sum(1 for r in p0 if r["status"] not in ("tested", "claimed only", "named, not run"))}, "equivalence": dict(counts_of(eq, ("cases", "executed", "same", "differs", "missing", "withinTolerance")), tolerances=tolerances_of(eq), approved=[{"id": text_of(a.get("id"), 80), "why": text_of(a.get("why"), 300)} for a in (eq.get("approved") if isinstance(eq.get("approved"), list) else [])[:20] if isinstance(a, dict)], 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, @@ -464,7 +467,8 @@ def proof_view(obj): lg = obj["legacy"] if isinstance(obj.get("legacy"), dict) else {} so = obj["signoff"] if isinstance(obj.get("signoff"), dict) else {} headline = "Proof: %s (%d module%s)." % (", ".join("%d %s" % (counts[v], v) for v in PROOF_VERDICTS if counts[v]) or "no module was verified", len(mods), "" if len(mods) == 1 else "s") - return {"generated": text_of(obj.get("generated"), 40), "verdict": verdict, "counts": counts, "headline": headline, "problems": problems, "modules": mods, + tooling = [{"name": text_of(t.get("name"), 120), "path": text_of(t.get("path"), 200)} for t in (obj["toolingOnly"] if isinstance(obj.get("toolingOnly"), list) else [])[:20] if isinstance(t, dict)] + return {"generated": text_of(obj.get("generated"), 40), "verdict": verdict, "counts": counts, "headline": headline, "problems": problems, "modules": mods, "tooling": tooling, "legacy": {"path": text_of(lg.get("path"), 200), "target": text_of(lg.get("target"), 300), "ran": lg.get("ran") if isinstance(lg.get("ran"), bool) else None, "state": text_of(lg.get("state"), 20), "detail": text_of(lg.get("detail"), 300)}, "rules": texts_of(obj.get("rules"), 700, 12), "signoff": {k: text_of(so.get(k), 120) for k in ("name", "role", "date", "decision")}} diff --git a/plugins/code-modernization/scripts/proof_pack.py b/plugins/code-modernization/scripts/proof_pack.py index acf9c997..260326a7 100644 --- a/plugins/code-modernization/scripts/proof_pack.py +++ b/plugins/code-modernization/scripts/proof_pack.py @@ -17,9 +17,13 @@ the output so an auditor can follow it: come from files this script parsed itself: JUnit-style XML, or a saved raw runner log (Maven/Gradle, cargo, pytest, unittest, go test, dotnet test, jest, vitest, ctest, phpunit). Counts only typed into test-runs.json cap the check at "gap". - 2 Rules traced rewrite and reimagine only: every P0 rule the module answers for is named by a - test (an id in a test name or comment). A rule only the notes name is "claimed", - not tested. Uplifts keep the code, so they trace no rules. + 2 Rules traced rewrite and reimagine only: every P0 rule the module answers for is backed by a + test that ran and passed here: the rule id is in the name (test or class) of a test + result this script parsed, or a test file names it on a line not marked skipped or + pending and its class or file is one of a test that passed. A rule named only by + skipped, pending or failing tests is "named, not run"; one only the notes name is + "claimed": neither is tested. Counts and logs name no test, so they back no rule. + Uplifts keep the code, so they trace no rules. 3 Same behavior the development cases, judged again here by compare.py, executed at least one case with none differing or missing (a case a person approved is allowed and listed); for an uplift, baseline_diff.py may stand in: no regression, no new @@ -34,6 +38,8 @@ the output so an auditor can follow it: file walk, no version-control tool is run inside the untrusted tree. Open questions, unticked criteria and the sign-off are for a person: they never change the verdict. +A built folder that holds only test code and the files that build it (a parity harness, for one) is not a +module: it is listed as "Test tooling (not judged)", under "toolingOnly" in the JSON, and not counted. Evidence read (under analysis/<system>/, or as named): equivalence/test-runs.json (written by the modernize-verify command), equivalence/[<module>/]cases.json and fresh-cases.json (judged again here, @@ -67,7 +73,8 @@ RULES_TEXT = ( "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.", + "2. Rules traced (rewrite and reimagine): every P0 rule the module answers for is backed by a test that ran and passed: its id is in the test or class name of a result this script parsed, " + "or a test file names it on a line not marked skipped or pending and that file's class ran and passed. A rule named only by skipped, pending or failing tests is named, not run; one only the notes name is claimed. Neither is tested.", "3. Same behavior: the development cases, judged again by compare.py, executed at least one case and none differs or is missing (a difference a person approved is allowed and listed); " "for an uplift, no regression, no new failure, no missing test and no drop in executed tests against BASELINE.md.", "4. Fresh inputs: at least 10 new inputs, none with the same output as a development case, ran on the legacy and the new code with no difference. Needed whenever the legacy could run here; " @@ -80,6 +87,7 @@ RULES_TEXT = ( "(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.", + "A folder that holds only test code and the files that build it is test tooling: it is listed, not judged, and not counted.", ) WORDS = {"pass": "pass", "gap": "not proven", "fail": "FAIL", "na": "not applicable"} CANARY = re.compile(r"Canary[^:\n|]{0,20}:\s*(.{1,300}?)\s*(?:→|->|=>|,)\s*(\d[\d,]*)\s+tests?\s+(?:failed|went red|failing)", re.I) @@ -245,6 +253,18 @@ def suite_evidence(suite, workspace): return ev, None +def suite_results(ctx, suite): + """suite_evidence once per suite: a result file is parsed a single time, however many times it is asked for.""" + if id(suite) not in ctx["parsed"]: + ctx["parsed"][id(suite)] = suite_evidence(suite, ctx["workspace"]) + return ctx["parsed"][id(suite)] + + +def module_run(ctx, subject): + """What ran for one module (trace_rules.run_evidence): read from its suites' result files. Counts and logs name no test, so they back no rule.""" + return trace_rules.run_evidence([suite_results(ctx, s)[1] for s in suites_for(ctx["runs"], subject, ctx["unit"], ctx["subjects"])]) + + # ---------------------------------------------------------------- the source check SOURCE_CAP, EXAMPLES = 400000, 20 NO_VCS = "by modification time, and no version-control tool was run" @@ -474,17 +494,27 @@ def check_rules(ctx, subject, evidence, caveats): view = trace_rules.module_view(tr, subject["rel"]) p0 = [r for r in view["rows"] if r["priority"] == "P0"] missing = [r["id"] for r in p0 if r["status"] != "tested"] - evidence["rules"] = {"tied": view["tied"], "counted": len(view["rows"]), "outOfScope": view["outOfScope"], "totals": view["totals"], "p0NoTests": missing, - "p0": [{"id": r["id"], "name": r["name"], "confidence": r["confidence"], "status": r["status"], "main": r["main"], "tests": r["tests"], "claimed": r["claimed"], - "where": clean((r["samples"]["tests"] or r["samples"]["main"] or [""])[0], 200)} for r in p0][:100]} + unrun = [r["id"] for r in p0 if r["status"] == trace_rules.NOT_RUN] + known = bool((ctx["ran"].get(subject["rel"]) or trace_rules.NO_RUN).get("known")) + evidence["rules"] = {"tied": view["tied"], "counted": len(view["rows"]), "outOfScope": view["outOfScope"], "totals": view["totals"], "p0NoTests": missing, "namedNotRun": unrun[:100], "perTestResults": known, + "p0": [{"id": r["id"], "name": r["name"], "confidence": r["confidence"], "status": r["status"], "main": r["main"], "tests": r["tests"], "claimed": r["claimed"], "by": r["by"], + "where": clean(r["at"] or (r["samples"]["tests"] or r["samples"]["main"] or [""])[0], 200)} for r in p0][:100]} if not view["tied"]: caveats.append("Nothing ties a rule to this module by name, so every rule in BUSINESS_RULES.md was counted.") if not p0: return row("rules", "pass", "No rule this module answers for is rated P0 (%d rule(s) counted)." % len(view["rows"])) if missing: - claimed = sum(1 for r in p0 if r["status"] == "claimed only") - return row("rules", "gap", "%d of %d P0 rule(s) are not named by any test: %s%s." % (len(missing), len(p0), ", ".join(missing[:12]), " (%d claimed only in the notes)" % claimed if claimed else "")) - return row("rules", "pass", "All %d P0 rule(s) this module answers for are named by at least one test." % len(p0)) + other = [r for r in p0 if r["status"] not in ("tested", trace_rules.NOT_RUN)] + say = [] + if unrun: + listed = ", ".join(unrun[:12]) + (" and %d more" % (len(unrun) - 12) if len(unrun) > 12 else "") + say.append("P0 rules named only by tests that did not run: %s (skipped, pending, failing or missing from the results)." % listed if known else + "P0 rules named by tests, but no result file lists each test, so nothing shows one ran: %s." % listed) + if other: + claimed = sum(1 for r in other if r["status"] == "claimed only") + say.append("%d of %d P0 rule(s) are not named by any test: %s%s." % (len(other), len(p0), ", ".join(r["id"] for r in other[:12]), " (%d claimed only in the notes)" % claimed if claimed else "")) + return row("rules", "gap", " ".join(say)) + return row("rules", "pass", "All %d P0 rule(s) this module answers for are backed by a test that ran and passed." % len(p0)) def baseline_info(ctx): @@ -762,7 +792,7 @@ def evaluate(subject, ctx): evidence, caveats, person = {}, [], [] per, xml_paths, oldest, clean_ids = [], [], None, set() for s in suites: - ev, fresh = suite_evidence(s, ws) + ev, fresh = suite_results(ctx, s) per.append(ev) caveats += ["%s: %s" % (ev["name"] or "a suite", n) for n in ev["notes"]] if ev["oldest"] is not None: @@ -817,19 +847,24 @@ def build(system, workspace, module=None, now=None): if not any(m["track"] == "uplift" and os.path.isdir(os.path.join(m["path"], module)) and not os.path.islink(os.path.join(m["path"], module)) for m in everything): raise InputError("nothing is built under modernized/ for %s module %s (built: %s)" % (system, module, ", ".join(clean(m["name"], 40) for m in everything[:10]))) unit = module - found = everything runs = load_test_runs(adir) - try: - tr, tr_problem = trace_rules.trace(workspace, system), "" - except OSError as err: - tr, tr_problem = None, "%s, so no rule can be traced (run /code-modernization:modernize-extract-rules %s)." % (clean(str(err), 200), system) brief = read_text(os.path.join(adir, "MODERNIZATION_BRIEF.md")) - ctx = {"workspace": workspace, "adir": adir, "system": system, "runs": runs, "subjects": everything, "unit": unit, "trace": tr, "trace_problem": tr_problem, "now": now, + ctx = {"workspace": workspace, "adir": adir, "system": system, "runs": runs, "subjects": everything, "unit": unit, "trace": None, "trace_problem": "", "now": now, "parsed": {}, "ran": {}, "source": source_check(workspace, system, adir), "brief": lambda mod, track: brief_items(brief, mod, track)} - mods = [evaluate(s, ctx) for s in sorted(found, key=lambda s: s["name"].lower())] + ctx["ran"] = {s["rel"]: module_run(ctx, s) for s in everything if s["track"] != "uplift"} # what ran, per module: a rule is traced against it + try: + ctx["trace"] = trace_rules.trace(workspace, system, ctx["ran"]) + except OSError as err: + ctx["trace_problem"] = "%s, so no rule can be traced (run /code-modernization:modernize-extract-rules %s)." % (clean(str(err), 200), system) + # a folder of only test code and the files that build it (a parity harness) is not a module: listed, not judged, not counted + tooling = [s for s in everything if s["track"] != "uplift" and trace_rules.tooling_only(s["path"])] + mods = [evaluate(s, ctx) for s in sorted(everything, key=lambda s: s["name"].lower()) if s not in tooling] problems = [clean(p, 300) for p in runs["problems"]] + ([] if runs["present"] else ["equivalence/test-runs.json was not found, so no test run is recorded and no module can be proven."]) + if tooling and not mods: + problems.append("Every built folder holds only test code and the files that build it, so there is no module to judge.") return {"v": 1, "system": clean(system, 100), "generated": now, "asked": clean(module or "", 100), "rules": list(RULES_TEXT), "legacy": dict(ctx["source"], ran=runs["legacy"]["ran"]), - "problems": problems, "modules": mods, "signoff": {"name": "", "role": "", "date": "", "decision": ""}} + "problems": problems, "modules": mods, "toolingOnly": [{"name": clean(s["name"], 100), "track": s["track"], "path": clean(s["rel"], 200)} for s in sorted(tooling, key=lambda s: s["name"].lower())], + "signoff": {"name": "", "role": "", "date": "", "decision": ""}} def overall(pack): @@ -859,6 +894,9 @@ def render_md(pack): p0 = ev.get("rules", {}).get("p0", []) tested = "%d of %d" % (sum(1 for r in p0 if r["status"] == "tested"), len(p0)) if "rules" in ev else "not applicable" out.append("| %s | %s | **%s** | %d | %d | %s | %s | %s |" % (cell(m["name"]), m["track"], m["verdict"], ev["tests"]["executed"], ev["tests"]["failed"], tested, WORDS[st["same"]], WORDS[st["fresh"]])) + if pack.get("toolingOnly"): + out += ["", "## Test tooling (not judged)", "", "These folders hold only test code and the files that build it, so there is no behavior in them to prove. They are not in the verdict or its counts. A module whose code is not written yet is listed here too, until its code exists.", ""] + out += ["- `%s` (%s)" % (cell(t["path"]), t["track"]) for t in pack["toolingOnly"]] for m in pack["modules"]: ev, t, br = m["evidence"], m["evidence"]["tests"], m["brief"] out += ["", "## %s: %s" % (cell(m["name"]), m["verdict"]), "", "Track: %s. Folder: `%s`. Checked %s." % (m["track"], cell(m["path"]), m["verifiedAt"]), ""] @@ -972,6 +1010,8 @@ def main(argv=None): print(" %s (%s): %s, tests executed: %d, failed %d" % (clean(m["name"], 60), m["track"], m["verdict"], m["evidence"]["tests"]["executed"], m["evidence"]["tests"]["failed"])) for r in m["reasons"]: print(" - " + clean(r, 300)) + for t in pack["toolingOnly"]: + print(" %s (%s): test tooling, not judged" % (clean(t["name"], 60), t["track"])) print("wrote analysis/%s/VERIFICATION.md and VERIFICATION.json" % args.system) return 0 if pack["overall"]["verdict"] == "PROVEN" else 1 diff --git a/plugins/code-modernization/scripts/tests/test_proof_rules_run.py b/plugins/code-modernization/scripts/tests/test_proof_rules_run.py new file mode 100644 index 00000000..0eb3560c --- /dev/null +++ b/plugins/code-modernization/scripts/tests/test_proof_rules_run.py @@ -0,0 +1,506 @@ +"""Tests for the "Rules traced" check: a rule is tested only when something that ran and passed backs it, and test-only folders are not judged. + +Run: python3 -m unittest discover -s plugins/code-modernization/scripts/tests +A test that names a rule is not a test that ran: skipped and pending tests, and files whose class never ran, leave the rule "named, not run". +""" +import json +import os +import re +import shutil +import sys +import tempfile +import time +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +PLUGIN = os.path.dirname(os.path.dirname(HERE)) +sys.path.insert(0, HERE) +sys.path.insert(0, os.path.join(PLUGIN, "scripts")) +import build_report as br # noqa: E402 +import proof_pack as pp # noqa: E402 +import trace_rules as tr # noqa: E402 +from test_proof_tools import RULES_MD, T0, Ws, junit, load, passing, put, read, run_main # noqa: E402 + +SKIPPED_TEST = '''package p; + +class CalcTest { + @Test + @Disabled("PENDING RULE-001") + void RULE_001_totals() {} + + @Test + @Disabled("PENDING RULE-002") + void RULE_002_rounds() {} +} +''' +NOT_RUN = "named, not run" + + +class RuleWs(Ws): + """The workspace of the proof tests (module mod, P0 rules RULE-001 and RULE-002), with helpers to change what the tests are and what ran.""" + + def module(self, module="mod"): + return super().module(module) + + def p0(self): + return {r["id"]: r for r in self.module()["evidence"]["rules"]["p0"]} + + def statuses(self): + return {r["id"]: r["status"] for r in self.module()["evidence"]["rules"]["p0"]} + + def check_rules(self): + return next(c for c in self.module()["checks"] if c["id"] == "rules") + + def test_file(self, rel, text): + put(self.root, "modernized/s/mod/src/test/" + rel, text, T0 + 20) + + def keep_only(self, *cases): + self.results(list(cases)) + + +class RulesNeedExecutedTests(unittest.TestCase): + def setUp(self): + self.ws = RuleWs(self) + + def test_the_default_workspace_is_tested_by_files_whose_class_ran(self): + self.assertEqual(self.ws.statuses(), {"RULE-001": "tested", "RULE-002": "tested"}) + self.assertEqual(self.ws.check_rules()["state"], "pass") + self.assertIn("backed by a test that ran and passed", self.ws.check_rules()["detail"]) + self.assertEqual(self.ws.module()["verdict"], "PROVEN") + + # (i) the hole that was found: @Disabled("PENDING RULE-001") and a result file that shows it skipped + def test_a_disabled_pending_test_that_the_results_show_skipped_is_named_not_run(self): + self.ws.test_file("CalcTest.java", SKIPPED_TEST) + self.ws.keep_only(("CalcTest", "RULE_001_totals", "SKIP", "PENDING RULE-001"), ("CalcTest", "RULE_002_rounds", "SKIP", "PENDING RULE-002"), ("OtherTest", "works", "PASS", "")) + self.assertEqual(self.ws.statuses(), {"RULE-001": NOT_RUN, "RULE-002": NOT_RUN}) + c = self.ws.check_rules() + self.assertEqual(c["state"], "gap") + self.assertIn("P0 rules named only by tests that did not run: RULE-001, RULE-002 (skipped, pending, failing or missing from the results).", c["detail"]) + m = self.ws.module() + self.assertEqual(m["verdict"], "PARTLY PROVEN") + self.assertEqual(m["evidence"]["rules"]["namedNotRun"], ["RULE-001", "RULE-002"]) + self.assertEqual(m["evidence"]["rules"]["p0NoTests"], ["RULE-001", "RULE-002"]) + self.assertTrue(m["evidence"]["rules"]["perTestResults"]) + self.assertTrue(any(r.startswith("Rules traced: P0 rules named only by tests that did not run") for r in m["reasons"])) + self.assertEqual(m["evidence"]["tests"]["skipped"], 2) + + def test_the_same_test_without_a_skip_marker_but_skipped_at_run_time_is_named_not_run_too(self): + self.ws.test_file("CalcTest.java", "class CalcTest {\n // RULE-001 and RULE-002 need a database\n void a() {}\n}\n") + self.ws.keep_only(("CalcTest", "a", "SKIP", "no database here"), ("OtherTest", "works", "PASS", "")) + self.assertEqual(self.ws.statuses(), {"RULE-001": NOT_RUN, "RULE-002": NOT_RUN}) + self.assertEqual({r["by"] for r in self.ws.p0().values()}, {""}) + + def test_a_test_that_ran_and_failed_backs_nothing(self): + self.ws.test_file("CalcTest.java", "class CalcTest {\n // RULE-001 RULE-002\n void a() {}\n}\n") + self.ws.keep_only(("CalcTest", "RULE_001_totals", "FAIL", ""), ("CalcTest", "RULE_002_rounds", "ERROR", ""), ("OtherTest", "works", "PASS", "")) + self.assertEqual(self.ws.statuses(), {"RULE-001": NOT_RUN, "RULE-002": NOT_RUN}) + self.assertEqual(self.ws.module()["verdict"], "NOT PROVEN") # the failures fail the tests check as they always did + self.assertEqual(self.ws.check_rules()["state"], "gap") + + # (ii) an executed, passing testcase that carries the id in its name + def test_a_passing_test_whose_name_carries_the_id_backs_the_rule_in_any_spelling(self): + self.ws.test_file("CalcTest.java", SKIPPED_TEST) # the only file that names the rules is all skipped + for name in ("RULE-001 totals", "RULE_001_totals", "rule001", "testRule001Totals", "Rule001", "totals[RULE-001]"): + self.ws.keep_only(("ChecksTest", name, "PASS", ""), ("ChecksTest", "test_RULE_002_rounds", "PASS", "")) + self.assertEqual(self.ws.statuses(), {"RULE-001": "tested", "RULE-002": "tested"}, name) + p0 = self.ws.p0() + self.assertEqual((p0["RULE-001"]["by"], p0["RULE-002"]["by"]), ("test name", "test name")) + self.assertEqual(self.ws.check_rules()["state"], "pass") + self.assertEqual(self.ws.module()["verdict"], "PROVEN") + + def test_the_class_name_may_carry_the_id_and_the_shorthand_names_both_rules(self): + self.ws.test_file("CalcTest.java", SKIPPED_TEST) + self.ws.keep_only(("com.x.Rule001Test", "a", "PASS", ""), ("com.x.OtherTest", "RULE-002/003", "PASS", "")) + self.assertEqual(self.ws.statuses(), {"RULE-001": "tested", "RULE-002": "tested"}) + + def test_an_id_in_the_name_of_a_test_that_did_not_pass_or_in_another_modules_results_backs_nothing(self): + self.ws.test_file("CalcTest.java", SKIPPED_TEST) + self.ws.keep_only(("ChecksTest", "RULE_001_a", "SKIP", "x"), ("ChecksTest", "RULE_002_b", "FAIL", ""), ("ChecksTest", "works", "PASS", "")) + self.assertEqual(self.ws.statuses(), {"RULE-001": NOT_RUN, "RULE-002": NOT_RUN}) + put(self.ws.root, "modernized/s/extra/src/main/X.java", "class X {}\n", T0 + 20) + put(self.ws.root, "modernized/s/extra/target/surefire-reports/TEST-X.xml", junit([("XTest", "RULE_001_a", "PASS", ""), ("XTest", "RULE_002_a", "PASS", "")]), T0 + 30) + self.ws.runs(suites=[{"module": "mod", "name": "unit", "junit": ["modernized/s/mod/target/surefire-reports"]}, + {"module": "extra", "name": "unit", "junit": ["modernized/s/extra/target/surefire-reports"]}]) + self.assertEqual(self.ws.statuses(), {"RULE-001": NOT_RUN, "RULE-002": NOT_RUN}) # what extra ran does not count for mod + + # (iii) a plain comment in a test file whose class ran + def test_a_plain_comment_in_a_test_file_whose_class_ran_backs_the_rule(self): + self.ws.test_file("CalcTest.java", "class CalcTest {\n // RULE-001 is pinned by these\n void a() {}\n void rule002_rounds() {}\n}\n") + self.ws.keep_only(("com.x.CalcTest", "a", "PASS", "")) + self.assertEqual(self.ws.statuses(), {"RULE-001": "tested", "RULE-002": "tested"}) + p0 = self.ws.p0() + self.assertEqual(p0["RULE-001"]["by"], "test file") + self.assertTrue(p0["RULE-001"]["where"].endswith("src/test/CalcTest.java:2"), p0["RULE-001"]["where"]) + self.assertEqual(self.ws.module()["verdict"], "PROVEN") + + def test_the_where_points_at_the_mention_that_backs_the_rule_not_at_a_skipped_one(self): + self.ws.test_file("CalcTest.java", SKIPPED_TEST) # sorts before Live.java and names both rules, skipped + self.ws.test_file("Live.java", "// RULE-001 RULE-002 are checked by these\nclass Live {}\n") + self.ws.keep_only(("Live", "a", "PASS", ""), ("CalcTest", "RULE_001_totals", "SKIP", "x")) + p0 = self.ws.p0() + self.assertTrue(p0["RULE-001"]["where"].endswith("src/test/Live.java:1"), p0["RULE-001"]["where"]) + self.assertEqual(self.ws.statuses(), {"RULE-001": "tested", "RULE-002": "tested"}) + + def test_the_class_name_may_be_nested_dotted_a_python_module_or_a_path(self): + same = (("CalcTest.java", "com.x.CalcTest$Inner"), ("CalcTest.java", "com.x.Outer$Deep$CalcTest"), ("CalcTest.java", "com.x.CalcTest$A$B"), ("test_calc.py", "tests.test_calc.TestCalc"), + ("test_calc.py", "tests.test_calc"), ("CalcTests.cs", "Ns.CalcTests"), ("calc.spec.ts", "src/calc.spec.ts"), ("CalcTest.java", "calctest"), ("CalcTest.java", "CALCTEST")) + other = (("CalcTest.java", "com.x.OtherCalcTest"), ("CalcTest.java", "com.calc.test.Other"), ("test_calc.py", "tests.test_other.TestCalc"), ("CalcTest.java", "Calc"), ("CalcTest.java", "")) + for rel, cls in same + other: + self.ws.test_file(rel, "// RULE-001 RULE-002\n") + self.ws.keep_only((cls, "a", "PASS", "")) + self.assertEqual(self.ws.statuses(), {"RULE-001": "tested", "RULE-002": "tested"} if (rel, cls) in same else {"RULE-001": NOT_RUN, "RULE-002": NOT_RUN}, (rel, cls)) + os.remove(os.path.join(self.ws.root, "modernized", "s", "mod", "src", "test", rel)) + self.ws.test_file("CalcTest.java", "// nothing here\n") + + # (iv) a file none of whose tests ran + def test_a_rule_named_only_in_a_file_none_of_whose_tests_ran_is_named_not_run(self): + self.ws.test_file("CalcTest.java", "// RULE-001\nclass CalcTest {}\n") + self.ws.test_file("GhostTest.java", "// RULE-002 is pinned here, and nothing marks it skipped\nclass GhostTest {}\n") + self.ws.keep_only(("CalcTest", "a", "PASS", ""), ("GhostTest", "b", "SKIP", "no docker")) + self.assertEqual(self.ws.statuses(), {"RULE-001": "tested", "RULE-002": NOT_RUN}) + self.ws.keep_only(("CalcTest", "a", "PASS", "")) # the class is not in the results at all + self.assertEqual(self.ws.statuses(), {"RULE-001": "tested", "RULE-002": NOT_RUN}) + c = self.ws.check_rules() + self.assertEqual(c["state"], "gap") + self.assertIn("named only by tests that did not run: RULE-002", c["detail"]) + self.assertNotIn("RULE-001", c["detail"]) + + # (v) counts only + def test_counts_only_evidence_never_backs_a_rule(self): + put(self.ws.root, "analysis/s/equivalence/unit.test-output.txt", "[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0\n", T0 + 30) + for suite in ({"module": "mod", "name": "unit", "command": "mvn test", "log": ["analysis/s/equivalence/unit.test-output.txt"]}, + {"module": "mod", "name": "unit", "executed": 3, "failed": 0, "skipped": 0}): + self.ws.runs(suites=[suite]) + self.assertEqual(self.ws.statuses(), {"RULE-001": NOT_RUN, "RULE-002": NOT_RUN}, suite) + m = self.ws.module() + self.assertFalse(m["evidence"]["rules"]["perTestResults"]) + self.assertEqual(self.ws.check_rules()["state"], "gap") + self.assertIn("named by tests, but no result file lists each test, so nothing shows one ran: RULE-001, RULE-002.", self.ws.check_rules()["detail"]) + self.assertNotEqual(m["verdict"], "PROVEN") + self.ws.runs(suites=[{"module": "mod", "name": "unit", "log": ["analysis/s/equivalence/unit.test-output.txt"]}, + {"module": "mod", "name": "more", "junit": ["modernized/s/mod/target/surefire-reports"]}]) # one suite that lists its tests is enough + self.assertEqual(self.ws.statuses(), {"RULE-001": "tested", "RULE-002": "tested"}) + + def test_no_suite_at_all_or_result_files_with_no_test_in_them_back_nothing(self): + put(self.ws.root, "modernized/s/mod/target/surefire-reports/TEST-CalcTest.xml", '<?xml version="1.0"?><testsuite name="S" tests="0"></testsuite>', T0 + 30) + self.assertEqual(self.ws.statuses(), {"RULE-001": NOT_RUN, "RULE-002": NOT_RUN}) + self.ws.runs(suites=[]) + self.assertEqual(self.ws.statuses(), {"RULE-001": NOT_RUN, "RULE-002": NOT_RUN}) + self.assertEqual(self.ws.module()["verdict"], "NOT PROVEN") + + # (vi) Python, and how far a marker reaches + def test_a_pytest_skip_that_names_the_rule_leaves_it_named_not_run(self): + put(self.ws.root, "analysis/s/BUSINESS_RULES.md", RULES_MD.replace("**Priority:** P2", "**Priority:** P0"), T0 + 10) + put(self.ws.root, "modernized/s/mod/src/main/calc.py", "def fee(): pass\n", T0 + 20) + self.ws.test_file("CalcTest.java", "// RULE-001 RULE-002\nclass CalcTest {}\n") + self.ws.test_file("test_fee.py", 'import pytest\n\n\n@pytest.mark.skip(reason="RULE-004")\ndef test_fee():\n pass\n\n\ndef test_other():\n pass\n') + self.ws.keep_only(("CalcTest", "a", "PASS", ""), ("tests.test_fee", "test_fee", "SKIP", "RULE-004"), ("tests.test_fee", "test_other", "PASS", "")) + self.assertEqual(self.ws.statuses(), {"RULE-001": "tested", "RULE-002": "tested", "RULE-004": NOT_RUN}) + self.assertIn("RULE-004", self.ws.check_rules()["detail"]) + self.ws.test_file("test_fee.py", 'import pytest\n\n\ndef test_fee():\n # RULE-004 is pinned here\n pass\n') # no marker: the class ran and passed + self.assertEqual(self.ws.statuses()["RULE-004"], "tested") + + def test_a_marker_reaches_three_lines_down_and_no_further_and_any_case(self): + put(self.ws.root, "analysis/s/BUSINESS_RULES.md", "### RULE-001: x\n**Priority:** P0\n", T0 + 10) + self.ws.keep_only(("CalcTest", "a", "PASS", "")) + for gap, want in ((0, NOT_RUN), (1, NOT_RUN), (2, NOT_RUN), (3, NOT_RUN), (4, "tested"), (9, "tested")): + lines = ["@Disabled RULE-001"] if gap == 0 else ["@Disabled"] + ["// filler"] * (gap - 1) + ["// RULE-001"] # the mention is `gap` lines below the marker + self.ws.test_file("CalcTest.java", "\n".join(lines) + "\n") + self.assertEqual(self.ws.statuses()["RULE-001"], want, gap) + self.ws.test_file("CalcTest.java", "// RULE-001\n// a marker below the mention does not matter: @Disabled\n") + self.assertEqual(self.ws.statuses()["RULE-001"], "tested") + for marker in ("@Disabled", "@Ignore", "[Ignore]", "@Skip", "#[ignore]", "xit(", "xdescribe(", "it.skip(", "test.skip(", "describe.skip(", "t.Skip()", "@pytest.mark.skip", + "@unittest.skipIf(x)", "pending", "PENDING", "Pending", "todo", "TODO", "@DISABLED", "SKIP", "XIT("): + self.ws.test_file("CalcTest.java", "%s\n// RULE-001\n" % marker) + self.assertEqual(self.ws.statuses()["RULE-001"], NOT_RUN, marker) + self.ws.test_file("CalcTest.java", "// RULE-001 is enabled and runs as a @Test\n") + self.assertEqual(self.ws.statuses()["RULE-001"], "tested") + + def test_one_live_mention_is_enough_when_the_same_file_also_has_skipped_ones(self): + put(self.ws.root, "analysis/s/BUSINESS_RULES.md", "### RULE-001: x\n**Priority:** P0\n", T0 + 10) + self.ws.test_file("CalcTest.java", '@Disabled("PENDING RULE-001")\nvoid a() {}\n\n\n\n\n// RULE-001 also holds for the total\n') + self.ws.keep_only(("CalcTest", "b", "PASS", "")) + self.assertEqual(self.ws.statuses()["RULE-001"], "tested") + + def test_a_rule_a_test_file_names_and_main_code_names_is_named_not_run_until_something_ran(self): + # the default workspace's Calc.java names both rules too: main code never makes a rule tested + self.ws.test_file("CalcTest.java", SKIPPED_TEST) + self.ws.keep_only(("OtherTest", "works", "PASS", "")) + m = self.ws.module() + self.assertEqual({r["id"]: (r["status"], r["main"] > 0) for r in m["evidence"]["rules"]["p0"]}, {"RULE-001": (NOT_RUN, True), "RULE-002": (NOT_RUN, True)}) + + def test_claimed_only_and_missing_rules_keep_their_own_words_beside_named_not_run(self): + put(self.ws.root, "analysis/s/BUSINESS_RULES.md", RULES_MD.replace("**Priority:** P1", "**Priority:** P0").replace("**Priority:** P2", "**Priority:** P0"), T0 + 10) + put(self.ws.root, "modernized/s/mod/src/main/Calc.java", "class Calc {}\n", T0 + 20) + put(self.ws.root, "modernized/s/mod/TRANSFORMATION_NOTES.md", "Legacy: `legacy/s/app/mod.cbl` and `legacy/s/app/other.cbl`\n\n| Rule | Target |\n|---|---|\n| RULE-003 | `src/main/Calc.java` |\n\nCanary: x -> 3 tests failed\n", T0 + 20) + self.ws.test_file("CalcTest.java", "// RULE-001\n@Disabled\n// RULE-002\n") + self.ws.keep_only(("CalcTest", "a", "PASS", "")) + self.assertEqual(self.ws.statuses(), {"RULE-001": "tested", "RULE-002": NOT_RUN, "RULE-003": "claimed only", "RULE-004": "none"}) + d = self.ws.check_rules()["detail"] + self.assertEqual(self.ws.check_rules()["state"], "gap") + self.assertIn("P0 rules named only by tests that did not run: RULE-002 (", d) + self.assertIn("2 of 4 P0 rule(s) are not named by any test: RULE-003, RULE-004 (1 claimed only in the notes).", d) + + def test_a_long_list_is_cut_and_says_how_many_more(self): + cards = "".join("### RULE-%03d: r\n**Priority:** P0\n\n" % n for n in range(1, 31)) + put(self.ws.root, "analysis/s/BUSINESS_RULES.md", cards, T0 + 10) + self.ws.test_file("CalcTest.java", "@Disabled\n" + "".join("// RULE-%03d\n@Disabled\n" % n for n in range(1, 31))) + d = self.ws.check_rules()["detail"] + self.assertIn("RULE-012 and 18 more", d) + self.assertNotIn("RULE-013", d) + + def test_an_uplift_still_traces_no_rules(self): + self.assertEqual(pp.check_rules({"trace": None, "trace_problem": "x", "ran": {}}, {"track": "uplift", "rel": "modernized/s-uplifted"}, {}, [])["state"], "na") + + def test_the_pack_tells_the_report_builder_nothing_it_cannot_read(self): + self.ws.test_file("CalcTest.java", SKIPPED_TEST) + self.ws.keep_only(("OtherTest", "works", "PASS", "")) + pack = self.ws.pack() + view = br.proof_view(pack) + m = view["modules"][0] + self.assertEqual((m["verdict"], pack["modules"][0]["verdict"]), ("PARTLY PROVEN", "PARTLY PROVEN")) + self.assertEqual(view["problems"], []) # the builder finds nothing to correct + self.assertEqual(m["p0Counts"]["tested"], 0) + self.assertTrue(all(r["status"] != "tested" for r in m["p0"])) # an unknown status is never shown as tested + code, out, _ = run_main(pp.main, ["s", "--workspace", self.ws.root]) + self.assertEqual(code, 1) + self.assertIn("P0 rules named only by tests that did not run", out) + + def test_the_markdown_table_says_named_not_run_in_plain_words(self): + self.ws.test_file("CalcTest.java", SKIPPED_TEST) + self.ws.keep_only(("OtherTest", "works", "PASS", "")) + run_main(pp.main, ["s", "--workspace", self.ws.root]) + md = read(os.path.join(self.ws.root, "analysis", "s", "VERIFICATION.md")) + rows = [ln for ln in md.split("\n") if ln.startswith("| RULE-00")] + self.assertEqual(len(rows), 2) + self.assertTrue(all("| named, not run |" in ln for ln in rows), rows) + self.assertIn("| 0 of 2 |", md) # the summary counts tested rules only + self.assertIn("named, not run; one only the notes name is claimed. Neither is tested.", md) + + +class TestOnlyFolders(unittest.TestCase): + def setUp(self): + self.ws = RuleWs(self) + put(self.ws.root, "modernized/s/harness/pom.xml", "<project/>", T0 + 20) + put(self.ws.root, "modernized/s/harness/mvnw", "#!/bin/sh\n", T0 + 20) + put(self.ws.root, "modernized/s/harness/.mvn/wrapper/x.properties", "x=1", T0 + 20) + put(self.ws.root, "modernized/s/harness/README.md", "docs are not code", T0 + 20) + put(self.ws.root, "modernized/s/harness/src/test/java/HarnessTest.java", "// drives the legacy WAR\nclass HarnessTest {}\n", T0 + 20) + put(self.ws.root, "modernized/s/harness/src/test/java/Storefront.java", "class Storefront {}\n", T0 + 20) + put(self.ws.root, "modernized/s/harness/target/classes/A.class", "x", T0 + 20) + self.mod = os.path.join(self.ws.root, "modernized", "s", "harness") + + # (vii) + def test_a_folder_of_only_test_code_and_build_files_is_listed_not_judged_and_not_counted(self): + pack = self.ws.pack() + self.assertEqual([m["name"] for m in pack["modules"]], ["mod"]) + self.assertEqual(pack["toolingOnly"], [{"name": "harness", "track": "rewrite", "path": "modernized/s/harness"}]) + self.assertEqual(pack["overall"], {"verdict": "PROVEN", "counts": {"PROVEN": 1, "PARTLY PROVEN": 0, "NOT PROVEN": 0}}) + code, out, _ = run_main(pp.main, ["s", "--workspace", self.ws.root]) + self.assertEqual(code, 0) + self.assertIn("harness (rewrite): test tooling, not judged", out) + self.assertNotIn("harness (rewrite): NOT PROVEN", out) + data = load(os.path.join(self.ws.root, "analysis", "s", "VERIFICATION.json")) + self.assertEqual((data["toolingOnly"], [m["name"] for m in data["modules"]], data["overall"]["verdict"]), ([{"name": "harness", "track": "rewrite", "path": "modernized/s/harness"}], ["mod"], "PROVEN")) + md = read(os.path.join(self.ws.root, "analysis", "s", "VERIFICATION.md")) + self.assertIn("\n## Test tooling (not judged)\n", md) + self.assertIn("- `modernized/s/harness` (rewrite)", md) + self.assertNotIn("## harness", md) + self.assertEqual(md.count("| mod |"), 1) + self.assertNotIn("| harness |", md) + self.assertIn("**Overall: PROVEN** (1 proven)", md) + view = br.proof_view(data) # the report builder reads the modules and ignores the new list + self.assertEqual(([m["name"] for m in view["modules"]], view["verdict"], view["problems"]), (["mod"], "PROVEN", [])) + + def test_a_pack_with_no_tooling_has_an_empty_list_and_no_heading(self): + shutil.rmtree(self.mod) + run_main(pp.main, ["s", "--workspace", self.ws.root]) + self.assertEqual(load(os.path.join(self.ws.root, "analysis", "s", "VERIFICATION.json"))["toolingOnly"], []) + self.assertNotIn("Test tooling", read(os.path.join(self.ws.root, "analysis", "s", "VERIFICATION.md"))) + + def test_the_tooling_folders_own_suite_and_rule_mentions_change_nothing(self): + put(self.ws.root, "modernized/s/harness/src/test/java/HarnessTest.java", "// RULE-001 RULE-002\nclass HarnessTest {}\n", T0 + 20) + put(self.ws.root, "modernized/s/harness/target/surefire-reports/TEST-HarnessTest.xml", junit([("HarnessTest", "a", "FAIL", "")]), T0 + 30) + self.ws.runs(suites=[{"module": "mod", "name": "unit", "junit": ["modernized/s/mod/target/surefire-reports"]}, + {"module": "harness", "name": "harness", "junit": ["modernized/s/harness/target/surefire-reports"]}]) + pack = self.ws.pack() + self.assertEqual((pack["overall"]["verdict"], [m["verdict"] for m in pack["modules"]]), ("PROVEN", ["PROVEN"])) # a failing harness test is not the module's failure + self.assertEqual(pack["modules"][0]["evidence"]["tests"]["executed"], 3) + + def test_any_main_code_or_any_file_that_is_not_plainly_tooling_means_it_is_judged(self): + for rel in ("src/main/java/Harness.java", "harness.py", "data/input.csv", "LICENSE", "src/main/resources/app.properties", "setup.py"): + put(self.ws.root, "modernized/s/harness/" + rel, "x", T0 + 20) + self.assertFalse(tr.tooling_only(self.mod), rel) + self.assertEqual([m["name"] for m in self.ws.pack()["modules"]], ["harness", "mod"], rel) + os.remove(os.path.join(self.mod, *rel.split("/"))) + self.assertTrue(tr.tooling_only(self.mod)) + + def test_a_folder_with_no_test_file_is_not_tooling_and_neither_is_an_uplift(self): + os.remove(os.path.join(self.mod, "src", "test", "java", "HarnessTest.java")) + os.remove(os.path.join(self.mod, "src", "test", "java", "Storefront.java")) + self.assertFalse(tr.tooling_only(self.mod)) + self.assertEqual(sorted(m["name"] for m in self.ws.pack()["modules"]), ["harness", "mod"]) + empty = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, empty, True) + self.assertFalse(tr.tooling_only(empty)) + put(self.ws.root, "modernized/s-uplifted/src/test/java/ATest.java", "class ATest {}\n", T0 + 20) + self.assertEqual({m["track"] for m in self.ws.pack()["modules"]}, {"rewrite", "uplift"}) # the whole working copy is one thing to prove, tests or not + + def test_what_counts_as_tooling_files(self): + for name in ("pom.xml", "mvnw", "mvnw.cmd", "gradlew", "build.gradle", "build.gradle.kts", "package.json", "package-lock.json", "tsconfig.json", "tsconfig.build.json", "jest.config.js", + "vitest.config.ts", "conftest.py", "pytest.ini", "pyproject.toml", "go.mod", "Cargo.toml", "composer.json", "phpunit.xml.dist", "App.csproj", "All.sln", "Makefile", "Dockerfile", + "docker-compose.yml", "POM.XML"): + self.assertTrue(tr.is_tooling(name), name) + for name in ("Calc.java", "main.py", "index.js", "setup.py", "app.properties", "data.json", "run.sh", "LICENSE", "pom.xml.bak", "xpom.xml", "tsconfig"): + self.assertFalse(tr.is_tooling(name), name) + + def test_only_tooling_at_all_is_not_proven_and_says_why(self): + shutil.rmtree(os.path.join(self.ws.root, "modernized", "s", "mod")) + pack = self.ws.pack() + self.assertEqual((pack["modules"], [t["name"] for t in pack["toolingOnly"]], pack["overall"]["verdict"]), ([], ["harness"], "NOT PROVEN")) + self.assertIn("there is no module to judge", " ".join(pack["problems"])) + code, out, _ = run_main(pp.main, ["s", "--workspace", self.ws.root]) + self.assertEqual(code, 1) + self.assertIn("harness (rewrite): test tooling, not judged", out) + + def test_asking_about_the_tooling_folder_is_allowed_and_changes_nothing(self): + pack = self.ws.pack("harness") + self.assertEqual(([m["name"] for m in pack["modules"]], pack["asked"], len(pack["toolingOnly"])), (["mod"], "harness", 1)) + + def test_the_trace_still_reads_the_tooling_folders_tests(self): + put(self.ws.root, "modernized/s/harness/src/test/java/HarnessTest.java", "// RULE-003\nclass HarnessTest {}\n", T0 + 20) + result = tr.trace(self.ws.root, "s", {"modernized/s/harness": {"known": True, "ids": set(), "keys": {"harnesstest"}}}) + self.assertEqual({r["id"]: r["status"] for r in result["rules"]}["RULE-003"], "tested") + self.assertEqual([m["name"] for m in result["modules"]], ["harness", "mod"]) + + +class RuleTracePieces(unittest.TestCase): + def test_class_keys(self): + cases = {"com.x.CalcTest": {"x", "calctest"}, "com.x.CalcTest$Inner": {"calctest", "inner"}, "a.B$C$D": {"b", "c", "d"}, "tests.test_calc.TestCalc": {"test_calc", "testcalc"}, + "src/calc.spec.ts": {"spec", "ts", "calc.spec.ts", "calc.spec"}, "": set(), "Only": {"only"}, "github.com/x/y": {"x", "y"}, "C:\\dir\\CalcTest.cs": {"calctest.cs", "calctest"}} + for name, want in cases.items(): + self.assertTrue(want <= tr.class_keys(name), (name, want, tr.class_keys(name))) + self.assertEqual(tr.class_keys(None), set()) + self.assertLessEqual(len(tr.class_keys("a." * 10000 + "b")), 4) + + def test_run_evidence_reads_only_tests_that_passed(self): + res = {"tests": {"CalcTest#RULE_001_a": "PASS", "CalcTest#RULE_002_a": "FAIL", "CalcTest#RULE_003_a": "SKIP", "Other#testRule004": "PASS", "Other#x~1": "PASS"}, + "classes": {"CalcTest": {"pass": 1, "fail": 1, "error": 0, "skip": 1, "executed": 2}, "Ghost": {"pass": 0, "fail": 0, "error": 0, "skip": 3, "executed": 0}, "Other": {"pass": 2}}} + ev = tr.run_evidence([res]) + self.assertEqual((ev["known"], ev["ids"], ev["keys"]), (True, {1, 4}, {"calctest", "other"})) + self.assertEqual(tr.run_evidence([]), {"known": False, "ids": set(), "keys": set()}) + self.assertEqual(tr.run_evidence([None, {"tests": {}, "classes": {}}]), {"known": False, "ids": set(), "keys": set()}) + more = tr.run_evidence([res, {"tests": {"Later#RULE_009_a": "PASS"}, "classes": {"Later": {"pass": 1}}}]) + self.assertEqual((more["ids"], more["keys"]), ({1, 4, 9}, {"calctest", "other", "later"})) + + def test_line_marks_and_the_window(self): + body = "a\nb @Disabled\nc\nd\ne\nf\ng" + starts, flags = tr.line_marks(body) + self.assertEqual(flags, [False, True, False, False, False, False, False]) + live = [tr.is_live((starts, flags), starts[i]) for i in range(7)] + self.assertEqual(live, [True, False, False, False, False, True, True]) # the marker's line and the 3 after it are marked + self.assertEqual(tr.line_marks("")[1], [False]) + + def test_the_command_line_needs_a_module_for_results_and_reports_unreadable_ones(self): + root = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, root, True) + put(root, "analysis/s/BUSINESS_RULES.md", RULES_MD) + put(root, "modernized/s/mod/src/test/CalcTest.java", "// RULE-001 RULE-002\n") + put(root, "res/TEST-bad.xml", "<testsuite><testcase") + put(root, "res/TEST-ok.xml", junit(passing(2, "CalcTest"))) + self.assertEqual(run_main(tr.main, ["s", "--workspace", root, "--results", os.path.join(root, "res")])[0], 2) + code, out, _ = run_main(tr.main, ["s", "--workspace", root, "--module", "mod", "--results", os.path.join(root, "res"), "--results", os.path.join(root, "nope")]) + self.assertEqual(code, 0) + self.assertIn("result file not used: TEST-bad.xml", out) + self.assertIn("nope is not a file or folder that can be read", out) + code, out, _ = run_main(tr.main, ["s", "--workspace", root, "--module", "nope", "--results", os.path.join(root, "res")]) + self.assertEqual(code, 2) + code, out, _ = run_main(tr.main, ["s", "--workspace", root, "--module", "mod", "--results", os.path.join(root, "res"), "--json"]) + self.assertEqual(code, 0) + data = json.loads(out) + self.assertEqual({r["id"]: r["status"] for r in data["rules"]}["RULE-001"], "tested") + self.assertEqual(data["moduleView"]["rows"][0]["by"], "test file") + + +class HostileInput(unittest.TestCase): + """(viii) Everything here is untrusted text: nothing may crash, stall or reach the markdown as structure.""" + + def setUp(self): + self.ws = RuleWs(self) + + def test_odd_and_huge_test_names_and_class_names_never_crash_or_reach_the_markdown(self): + evil = ["RULE-001\n| RULE-999 | injected | x | tested | 9 | 9 | `x` |", "`RULE_002` <img src=x onerror=1> \x1b[31m", "RULE-001" + "x" * 5000, "\x00RULE-002\u202e\u2028", "RULE-1234567 RULE-0", "A" * 100000, + "RULE-001 | | | |", "rule-\u0660\u0660\u0661", "RULE\u2212001"] + cases = [(n, m, "PASS", "") for n in evil for m in evil] + [("CalcTest", "ok", "PASS", "")] + put(self.ws.root, "modernized/s/mod/target/surefire-reports/TEST-CalcTest.xml", junit([(re.sub(r'[<>&"\x00-\x08\x0b\x0c\x0e-\x1f]', "_", c), re.sub(r'[<>&"\x00-\x08\x0b\x0c\x0e-\x1f]', "_", n), s, m) for c, n, s, m in cases]), T0 + 30) + started = time.time() + code, out, _ = run_main(pp.main, ["s", "--workspace", self.ws.root]) + self.assertLess(time.time() - started, 20) + self.assertIn(code, (0, 1)) + md = read(os.path.join(self.ws.root, "analysis", "s", "VERIFICATION.md")) + self.assertNotIn("injected", md) + self.assertEqual(len([ln for ln in md.split("\n") if ln.startswith("| RULE-")]), 2) + self.assertNotIn("RULE-999", md) + self.assertNotRegex(md, r"[\x00\x1b\u202e\u2028]") + self.assertEqual(self.ws.module()["evidence"]["rules"]["p0"][0]["id"], "RULE-001") + + def test_hostile_file_names_and_lines_stay_inside_the_p0_table(self): + self.ws.test_file("Rule001|`x`Y.java", "// RULE-001 | RULE-002 |\n| a | b |\n") + self.ws.test_file("CalcTest.java", "@Disabled " + "RULE-001 " * 300000 + "x" * 3000000) + self.ws.keep_only(("Rule001|`x`Y", "a", "PASS", ""), ("CalcTest", "a", "PASS", "")) + started = time.time() + pack = self.ws.pack() + self.assertLess(time.time() - started, 20) + md = pp.render_md(pack) + for ln in md.split("\n"): + if ln.startswith("| RULE-"): + self.assertEqual(len(re.findall(r"(?<!\\)\|", ln)), 8, ln) + self.assertEqual(self.ws.statuses(), {"RULE-001": "tested", "RULE-002": "tested"}) + + def test_one_line_files_with_the_marker_after_the_mention_and_many_marked_lines_are_read_in_linear_time(self): + self.ws.test_file("CalcTest.java", "RULE-001 " * 100000 + "@Disabled") + self.ws.test_file("Lines.java", "".join("// RULE-002 skip\n" for _ in range(100000))) + self.ws.keep_only(("CalcTest", "a", "PASS", ""), ("Lines", "a", "PASS", "")) + started = time.time() + self.assertEqual(self.ws.statuses(), {"RULE-001": NOT_RUN, "RULE-002": NOT_RUN}) + self.assertLess(time.time() - started, 20) + + def test_many_passing_tests_naming_many_rules_are_read_quickly(self): + cards = "".join("### RULE-%03d: r\n**Priority:** P0\n\n" % n for n in range(1, 400)) + put(self.ws.root, "analysis/s/BUSINESS_RULES.md", cards, T0 + 10) + self.ws.test_file("CalcTest.java", "// nothing\n") + self.ws.keep_only(*[("Big", "test_RULE_%03d_x" % n, "PASS", "") for n in range(1, 400)] + [("Big", "u%d" % i, "PASS", "") for i in range(30000)]) + started = time.time() + p0 = self.ws.module()["evidence"]["rules"]["p0"] + self.assertLess(time.time() - started, 20) + self.assertEqual(len(p0), 100) # the pack keeps the first hundred rows, as before + self.assertTrue(all(r["status"] == "tested" and r["by"] == "test name" for r in p0)) + + def test_a_hostile_tooling_folder_name_stays_one_plain_list_item(self): + put(self.ws.root, "modernized/s/h`\n## Injected | x/pom.xml", "<project/>", T0 + 20) + put(self.ws.root, "modernized/s/h`\n## Injected | x/src/test/ATest.java", "class ATest {}\n", T0 + 20) + pack = self.ws.pack() + md = pp.render_md(pack) + self.assertEqual(len(pack["toolingOnly"]), 1) + self.assertNotRegex(md, r"(?m)^## Injected") + self.assertEqual(len([ln for ln in md.split("\n") if ln.startswith("- `modernized/s/h")]), 1) + self.assertNotIn("\n", pack["toolingOnly"][0]["name"]) + + def test_a_link_in_a_test_folder_and_binary_test_files_back_nothing(self): + outside = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, outside, True) + put(outside, "GhostTest.java", "// RULE-002\n") + try: + os.symlink(os.path.join(outside, "GhostTest.java"), os.path.join(self.ws.root, "modernized", "s", "mod", "src", "test", "GhostTest.java")) + except (OSError, NotImplementedError): + self.skipTest("symbolic links are not available here") + self.ws.test_file("CalcTest.java", "// RULE-001\n") + self.ws.test_file("BinTest.java", b"\x00\x01 RULE-002 \x00") + self.ws.keep_only(("CalcTest", "a", "PASS", ""), ("GhostTest", "a", "PASS", ""), ("BinTest", "a", "PASS", "")) + m = self.ws.module() + self.assertEqual({r["id"]: r["tests"] for r in m["evidence"]["rules"]["p0"]}["RULE-002"], 0) # code (Calc.java) still names RULE-002, no test file does + self.assertEqual(self.ws.statuses()["RULE-002"], "code only") + + +if __name__ == "__main__": + unittest.main() diff --git a/plugins/code-modernization/scripts/tests/test_proof_tools.py b/plugins/code-modernization/scripts/tests/test_proof_tools.py index 930670f8..1f72c366 100644 --- a/plugins/code-modernization/scripts/tests/test_proof_tools.py +++ b/plugins/code-modernization/scripts/tests/test_proof_tools.py @@ -110,15 +110,19 @@ RULES_MD = """# Business Rules """ +def ran(*classes, ids=(), mod="modernized/s/mod"): + """What ran for one module, as trace_rules.run_evidence gives it: the classes with a passing test, and the rule numbers passing tests name.""" + return {mod: {"known": True, "ids": set(ids), "keys": {c.lower() for c in classes}}} + + class TraceRules(unittest.TestCase): def setUp(self): self.root = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, self.root, True) put(self.root, "analysis/s/BUSINESS_RULES.md", RULES_MD) - def status(self, result=None): - result = result or tr.trace(self.root, "s") - return {r["id"]: r["status"] for r in result["rules"]} + def status(self, evidence=None): + return {r["id"]: r["status"] for r in tr.trace(self.root, "s", evidence)["rules"]} def test_tested_code_only_claimed_only_and_none(self): put(self.root, "modernized/s/mod/src/test/CalcTest.java", "// RULE-001 pinned here\nvoid rule002_rounds() {}\n") @@ -126,7 +130,9 @@ class TraceRules(unittest.TestCase): put(self.root, "modernized/s/mod/src/main/Fee.java", "class Fee {}\n") put(self.root, "modernized/s/mod/TRANSFORMATION_NOTES.md", "## Mapping\n\n| Behavior (rule) | Legacy | Target |\n|---|---|---|\n| Fee (RULE-004) | 30-39 | `src/main/Fee.java:1-5` |\n") - self.assertEqual(self.status(), {"RULE-001": "tested", "RULE-002": "tested", "RULE-003": "code only", "RULE-004": "claimed only"}) + self.assertEqual(self.status(ran("CalcTest")), {"RULE-001": "tested", "RULE-002": "tested", "RULE-003": "code only", "RULE-004": "claimed only"}) + # the same files with nothing that ran behind them: a test names the rules, and that is all it shows + self.assertEqual(self.status(), {"RULE-001": "named, not run", "RULE-002": "named, not run", "RULE-003": "code only", "RULE-004": "claimed only"}) def test_a_claim_needs_a_file_that_exists_and_notes_are_never_tests(self): put(self.root, "modernized/s/mod/src/main/Real.java", "class Real {}\n") @@ -141,14 +147,14 @@ class TraceRules(unittest.TestCase): put(self.root, "modernized/s/mod/src/test/ATest.java", "// RULE-002\n") put(self.root, "modernized/s/mod/TRANSFORMATION_NOTES.md", "## Not migrated\n\n| What | Why |\n|---|---|\n| Old fee RULE-004 | `src/main/A.java` dead code |\n\n## Mapping\n\n| Rule | Target |\n|---|---|\n| RULE-002 | `src/main/A.java` |\n") - self.assertEqual(self.status()["RULE-004"], "none") - self.assertEqual(self.status()["RULE-002"], "tested") + self.assertEqual(self.status(ran("ATest"))["RULE-004"], "none") + self.assertEqual(self.status(ran("ATest"))["RULE-002"], "tested") def test_only_exact_ids_count_and_neighbours_do_not(self): put(self.root, "modernized/s/mod/src/test/T.java", "RULE-0010 RULE-1001 XRULE-001 rulebook-2 the rule of thumb, schedule_2, ruler-3\n") self.assertEqual(set(self.status().values()), {"none"}) put(self.root, "modernized/s/mod/src/test/U.java", "// RULE_002 and testRule001 and rule-003\n") - self.assertEqual({k: v for k, v in self.status().items() if v == "tested"}, {"RULE-001": "tested", "RULE-002": "tested", "RULE-003": "tested"}) + self.assertEqual({k: v for k, v in self.status(ran("T", "U")).items() if v == "tested"}, {"RULE-001": "tested", "RULE-002": "tested", "RULE-003": "tested"}) def test_what_counts_as_a_test_file(self): for rel, kind in (("src/test/java/A.java", "test"), ("tests/x.py", "test"), ("web/__tests__/a.js", "test"), ("spec/a.rb", "test"), ("src/FooTest.java", "test"), @@ -164,14 +170,27 @@ class TraceRules(unittest.TestCase): def test_p0_without_a_test_is_the_important_list_and_sets_the_exit_code(self): put(self.root, "modernized/s/mod/src/test/CalcTest.java", "// RULE-001\n") - result = tr.trace(self.root, "s") + put(self.root, "results/TEST-CalcTest.xml", junit(passing(1, "CalcTest"))) + result = tr.trace(self.root, "s", ran("CalcTest")) self.assertEqual(result["p0NoTests"], ["RULE-002"]) - self.assertEqual(result["totals"]["P0"], {"rules": 2, "tested": 1, "code only": 0, "claimed only": 0, "none": 1}) + self.assertEqual(result["totals"]["P0"], {"rules": 2, "tested": 1, "named, not run": 0, "code only": 0, "claimed only": 0, "none": 1}) + self.assertEqual(tr.trace(self.root, "s")["p0NoTests"], ["RULE-001", "RULE-002"]) # nothing ran, as far as this trace knows code, out, _ = run_main(tr.main, ["s", "--workspace", self.root]) self.assertEqual(code, 1) - self.assertIn("P0 rules with no test that names them: RULE-002", out) + self.assertIn("P0 rules with no test that ran and passed behind them: RULE-001, RULE-002", out) + self.assertIn("No test results were given", out) + results = os.path.join(self.root, "results") + code, out, _ = run_main(tr.main, ["s", "--workspace", self.root, "--module", "mod", "--results", results]) + self.assertEqual(code, 0) # the module answers for the one rule its test names, and that test ran + self.assertIn("1 result file(s) read: 1 test(s), 1 passed", out) put(self.root, "modernized/s/mod/src/test/CalcTest.java", "// RULE-001 RULE-002\n") - self.assertEqual(run_main(tr.main, ["s", "--workspace", self.root])[0], 0) + code, out, _ = run_main(tr.main, ["s", "--workspace", self.root, "--module", "mod", "--results", results]) + self.assertEqual(code, 0) + self.assertIn("2 tested", out) + put(self.root, "results/TEST-CalcTest.xml", junit([("CalcTest", "a", "SKIP", "pending")])) # the same test file, skipped now + code, out, _ = run_main(tr.main, ["s", "--workspace", self.root, "--module", "mod", "--results", results]) + self.assertEqual(code, 1) + self.assertIn("named, not run", out) def test_module_view_counts_only_the_modules_rules_and_falls_back_to_all(self): put(self.root, "modernized/s/mod/src/test/CalcTest.java", "// RULE-001\n") @@ -196,9 +215,12 @@ class TraceRules(unittest.TestCase): def test_module_option_and_exit_codes(self): put(self.root, "modernized/s/mod/src/test/CalcTest.java", "// RULE-001 RULE-002\n") - code, out, _ = run_main(tr.main, ["s", "--workspace", self.root, "--module", "MOD"]) + put(self.root, "results/TEST-CalcTest.xml", junit(passing(2, "CalcTest"))) + code, out, _ = run_main(tr.main, ["s", "--workspace", self.root, "--module", "MOD", "--results", os.path.join(self.root, "results")]) self.assertEqual(code, 0) self.assertIn("module mod", out) + self.assertEqual(run_main(tr.main, ["s", "--workspace", self.root, "--module", "MOD"])[0], 1) # no results: named, not run + self.assertEqual(run_main(tr.main, ["s", "--workspace", self.root, "--results", os.path.join(self.root, "results")])[0], 2) # results need a module self.assertEqual(run_main(tr.main, ["s", "--workspace", self.root, "--module", "nope"])[0], 2) for bad in ("..", "a/b", ""): self.assertEqual(run_main(tr.main, [bad, "--workspace", self.root])[0], 2) @@ -220,16 +242,16 @@ class TraceRules(unittest.TestCase): put(self.root, "modernized/s/mod/src/test/Binary.java", b"\x00\x01\x02 RULE-002 \x00") put(self.root, "modernized/s/mod/src/test/Path.java", "// ../../RULE-002/../../etc/passwd and RULE-001/..\n") started = time.time() - result = tr.trace(self.root, "s") + result = tr.trace(self.root, "s", ran("Path", "Huge", "Line")) self.assertLess(time.time() - started, 20) - st = self.status(result) + st = {r["id"]: r["status"] for r in result["rules"]} self.assertEqual(st["RULE-001"], "tested") # by Path.java, which only names the id self.assertEqual(st["RULE-002"], "tested") # "../../RULE-002/.." is a mention, and nothing was opened for it self.assertEqual(result["scan"]["linksSkipped"], 2) self.assertEqual([m["name"] for m in result["modules"]], ["mod"]) # the linked module folder is not a module self.assertNotIn("secret.java", json.dumps(result)) os.remove(os.path.join(self.root, "modernized", "s", "mod", "src", "test", "Path.java")) - self.assertEqual(self.status()["RULE-002"], "none") # a NUL byte marks a file binary, and the links reached nothing + self.assertEqual(self.status(ran("Path", "Binary"))["RULE-002"], "none") # a NUL byte marks a file binary, and the links reached nothing def test_a_link_in_place_of_the_rules_file_is_refused(self): outside = tempfile.mkdtemp() @@ -576,8 +598,12 @@ class ProofVerdicts(unittest.TestCase): shutil.rmtree(os.path.join(self.ws.root, "modernized", "s", "mod", "target")) put(self.ws.root, "analysis/s/equivalence/unit.test-output.txt", "[INFO] Running X\n[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0\n[INFO] BUILD SUCCESS\n", T0 + 30) self.ws.runs(suites=[{"module": "mod", "name": "unit", "command": "mvn test", "log": ["analysis/s/equivalence/unit.test-output.txt"]}]) - m = self.check("PROVEN", tests="pass") + m = self.check("PARTLY PROVEN", tests="pass", rules="gap") # a log gives counts, not test names: no rule can be backed by it self.assertEqual((m["evidence"]["tests"]["suites"][0]["source"], m["evidence"]["tests"]["executed"]), ("runner log", 3)) + self.assertIn("no result file lists each test", m["checks"][1]["detail"]) + put(self.ws.root, "analysis/s/BUSINESS_RULES.md", "### RULE-001: x\n**Priority:** P1\n", T0 + 10) # with no P0 rule to back, the log is enough + self.check("PROVEN", tests="pass") + put(self.ws.root, "analysis/s/BUSINESS_RULES.md", RULES_MD, T0 + 10) put(self.ws.root, "analysis/s/equivalence/unit.test-output.txt", "3 tests were run, all fine, trust me\n", T0 + 30) m = self.check("PARTLY PROVEN", tests="gap") self.assertTrue(any("no summary line of a runner this script knows" in c for c in m["caveats"])) @@ -909,8 +935,9 @@ class ProofVerdicts(unittest.TestCase): def test_a_reimagined_service_is_judged_like_a_rewritten_module(self): shutil.rmtree(os.path.join(self.ws.root, "modernized", "s")) + put(self.ws.root, "modernized/s-reimagined/api/src/main/Api.java", "class Api {}\n", T0 + 20) put(self.ws.root, "modernized/s-reimagined/api/src/test/ApiTest.java", "// RULE-001 RULE-002\n", T0 + 20) - put(self.ws.root, "modernized/s-reimagined/api/target/surefire-reports/TEST-Api.xml", junit(passing(4, "Api")), T0 + 30) + put(self.ws.root, "modernized/s-reimagined/api/target/surefire-reports/TEST-Api.xml", junit(passing(4, "ApiTest")), T0 + 30) self.ws.runs(suites=[{"module": "api", "name": "acceptance", "executed": 4, "junit": ["modernized/s-reimagined/api/target/surefire-reports"]}]) pack = self.ws.pack() m = pack["modules"][0] @@ -1694,6 +1721,19 @@ class ProofReport(unittest.TestCase): self.assertEqual(pv["signoff"], {"name": "", "role": "", "date": "", "decision": ""}) self.assertEqual(pv["modules"][0]["people"][0]["text"], "A person accepts it") + def test_a_rule_named_only_by_tests_that_did_not_run_is_counted_and_tooling_folders_are_listed(self): + pack = good_pack() + pack["modules"][0]["evidence"]["rules"]["p0"].append({"id": "RULE-002", "name": "Skipped", "confidence": "High", "status": "named, not run", "tests": 1, "main": 0, "where": "T.java:3"}) + pack["toolingOnly"] = [{"name": "parity-harness", "path": "modernized/s/parity-harness"}, "not a dict", {"name": "x" * 500, "path": 5}] + html = self.report(pack) + _, pv = self.proof(html) + self.assertEqual(pv["modules"][0]["p0Counts"], {"tested": 1, "claimedOnly": 0, "notRun": 1, "none": 0}) + self.assertEqual(pv["modules"][0]["verdict"], "PARTLY PROVEN") # a pass cannot stand next to a rule that no test ran + self.assertEqual([t["name"] for t in pv["tooling"]][0], "parity-harness") + self.assertEqual(len(pv["tooling"]), 2) + self.assertLessEqual(len(pv["tooling"][1]["name"]), 120) + self.assertEqual(self.proof(self.report(good_pack()))[1]["tooling"], []) + def test_no_pack_means_no_section_and_the_older_reports_are_unchanged(self): code, _, _ = run_main(br.main, ["s", "--workspace", self.root, "--out", self.out]) data = page_data(read(self.out)) @@ -1804,7 +1844,7 @@ class ProofReport(unittest.TestCase): mod = data["glance"]["proof"]["modules"][0] self.assertEqual(mod, {"name": "mod", "verdict": "PARTLY PROVEN"}) pv = next(p["proof"] for s in data["sections"] if s["id"] == "proof" for p in s["parts"]) - self.assertEqual(pv["modules"][0]["p0Counts"], {"tested": 1, "claimedOnly": 0, "none": 1}) + self.assertEqual(pv["modules"][0]["p0Counts"], {"tested": 1, "claimedOnly": 0, "notRun": 0, "none": 1}) self.assertTrue(pv["modules"][0]["reasons"][0].startswith("Rules traced: 1 of 2 P0")) def test_hostile_values_stay_data_and_the_page_keeps_its_rules(self): @@ -1929,7 +1969,7 @@ class ProofScript(unittest.TestCase): def test_the_page_shows_the_matrix_what_is_not_proven_and_a_blank_sign_off(self): text = self.out[0]["text"] - for needle in ("What this does not prove", "It does not prove inputs nobody tried.", "P0 business rules: 1 tested, 0 claimed only, 0 with no test", "RULE-001", + for needle in ("What this does not prove", "It does not prove inputs nobody tried.", "P0 business rules: 1 tested, 0 named but not run, 0 claimed only, 0 with no test", "RULE-001", "Waiting for a person", "A person accepts it", "Sign-off", "________________", "accept / accept with conditions / reject", "How the verdict is computed", "Fresh inputs: 12 new input(s)", "tests executed: 5"): self.assertIn(needle, text) diff --git a/plugins/code-modernization/scripts/tests/test_report_tools.py b/plugins/code-modernization/scripts/tests/test_report_tools.py index 07c892bc..7d3acec4 100644 --- a/plugins/code-modernization/scripts/tests/test_report_tools.py +++ b/plugins/code-modernization/scripts/tests/test_report_tools.py @@ -293,6 +293,18 @@ class BuildFacts(unittest.TestCase): self.assertEqual(blocks[0]["k"], "md") self.assertEqual(br.parse_rules("just text\n\n## Heading")[0]["k"], "md") + def test_headings_and_fields_padded_with_thousands_of_spaces_are_parsed_in_a_moment(self): + import time + pad = " " * 6000 + text = "### RULE-001 - Title%s#%sx\n**Priority:** P0%s\n**Suspected defect:**%s\n\n### RULE-002: Closed ### \n**Priority:** P1 \n" % (pad, pad, pad, pad) + started = time.time() + cards = [c for c in br.parse_rules(text) if c["k"] == "rule"] + self.assertLess(time.time() - started, 2) + self.assertEqual([c["id"] for c in cards], ["RULE-001", "RULE-002"]) + self.assertEqual(cards[1]["title"], "Closed") + self.assertEqual(cards[1]["p"], "P1") + self.assertEqual(br.field("Priority: \nPriority: P2 ", "Priority"), "P2") + def test_rule_priority_falls_back_to_the_index_table(self): text = "| ID | Name | Priority |\n|---|---|---|\n| [RULE-007](#x) | Merged | P0 |\n\n### RULE-007: Merged\n**Merged into:** RULE-006\n\n### RULE-008: Real\n**Priority:** P1\n" cards = [b for b in br.parse_rules(text) if b["k"] == "rule"] diff --git a/plugins/code-modernization/scripts/trace_rules.py b/plugins/code-modernization/scripts/trace_rules.py index 5d9d4691..139e438c 100644 --- a/plugins/code-modernization/scripts/trace_rules.py +++ b/plugins/code-modernization/scripts/trace_rules.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 -"""Trace every business rule to the code and the tests that name it. +"""Trace every business rule to the code and the tests that name it, and to the tests that ran. - python3 trace_rules.py <system> [--workspace DIR] [--json] [--all] + python3 trace_rules.py <system> [--workspace DIR] [--json] [--all] [--module NAME --results PATH ...] Reads analysis/<system>/BUSINESS_RULES.md (rule cards: "### RULE-NNN: name" with **Priority:**, **Confidence:** and **Source:** lines), then scans the built code under modernized/<system>, @@ -10,26 +10,37 @@ build/, dist/, node_modules/, bin/, obj/, __pycache__/, or any folder starting w mentions of each rule id, and sorts every file into "test" or "main" code. One row per rule. Evidence, strongest first: - tested a test file names the rule - code only only main code names it - claimed only only the mapping table in TRANSFORMATION_NOTES.md or UPLIFT_NOTES.md names it, on a - row that also names a file that exists in the module - none nothing names it + tested executed evidence backs it, from the per-test results of that run (JUnit or TRX XML; --results + reads them here, the proof pack passes them in): a test that ran and passed names the rule in + its test or class name, or a test file names it on a line not marked skipped and that file's + name is the class or file of a test that ran and passed. Without per-test results nothing is + "tested" + named, not run a test file names it, but nothing that ran backs it: the test is skipped, pending or failing, + its class never ran, or no per-test results were given + code only only main code names it + claimed only only the mapping table in TRANSFORMATION_NOTES.md or UPLIFT_NOTES.md names it, on a + row that also names a file that exists in the module + none nothing names it A mention is RULE-017 (any case, or RULE_017), rule017 or Rule017 inside an identifier such as rule017_emptyInput or testRule017, and the shorthand RULE-002/003 and RULE-001, -018. Nothing is -guessed from words: a rule that no file names by id is not "tested", however well its behavior may -be covered. A mention shows that a test names the rule, not that the test is good. +guessed from words. A line is marked skipped when it, or one of the 3 lines above it, holds @Disabled, +@Ignore, [Ignore], #[ignore], xit(, xdescribe, skip (so also @Skip, t.Skip, it.skip, test.skip, +describe.skip and @pytest.mark.skip), pending or todo, in any case. A mention shows that a test names +the rule, not that the test is good. A test is a file under a folder called test, tests, __tests__, spec or specs, or named like FooTest.java, FooTests.cs, TestFoo.java, test_foo.py, foo_test.go, foo.spec.ts or foo.test.js. Documentation files (.md, .txt, .rst, .adoc) are never code. Symbolic links are never followed. +A built folder that holds only test files and the files that build them (pom.xml, mvnw, package.json, +...) is test tooling, not a module: tooling_only() says so. Everything read is untrusted text: it is never executed and only shortened, never trusted. -Exit 0 when every P0 rule has a test that names it, 1 when some do not, 2 when the rules file -cannot be read. Standard library only. +Exit 0 when every P0 rule is "tested", 1 when some are not, 2 when the rules file cannot be read. +Standard library only. """ import argparse +import bisect import collections import json import os @@ -51,6 +62,15 @@ NOT_A_CLAIM = re.compile(r"(?i)not migrated|not implemented|not ported|removed|r CARD = re.compile(r"#{2,5}[ \t]+[*`\[]*RULE[-_](\d{1,6})(?![A-Za-z0-9])", re.I) FENCE = re.compile(r"^ {0,3}(`{3,}|~{3,})") PATH = re.compile(r"[A-Za-z0-9_@][A-Za-z0-9_@./+-]{0,199}\.[A-Za-z][A-Za-z0-9]{0,7}(?![A-Za-z0-9_])") +SKIPPED_LINE = re.compile(r"@Disabled|@Ignore|\[Ignore\]|#\[ignore\]|xit\(|xdescribe|skip|pending|todo", re.I) # "skip" also covers @Skip, t.Skip, it.skip, test.skip, describe.skip, @pytest.mark.skip +MARK_LINES = 3 # a mention is skipped when its own line, or one of this many lines above it, holds a marker +NOT_RUN = "named, not run" +NO_RUN = {"known": False, "ids": frozenset(), "keys": frozenset()} +TOOLING_NAMES = {"pom.xml", "mvnw", "mvnw.cmd", "gradlew", "gradlew.bat", "build.gradle", "build.gradle.kts", "settings.gradle", "settings.gradle.kts", "gradle.properties", + "package.json", "package-lock.json", "yarn.lock", "pnpm-lock.yaml", "pytest.ini", "tox.ini", "setup.cfg", "pyproject.toml", "uv.lock", "poetry.lock", "conftest.py", + "cargo.toml", "cargo.lock", "go.mod", "go.sum", "composer.json", "composer.lock", "phpunit.xml", "phpunit.xml.dist", "cmakelists.txt", "makefile", "dockerfile"} +TOOLING_EXT = {".csproj", ".sln", ".props", ".targets", ".runsettings"} +TOOLING_PATTERN = re.compile(r"tsconfig[\w.-]*\.json|[\w-]+\.config\.(?:js|cjs|mjs|ts)|docker-compose[\w.-]*\.ya?ml") def clean(value, limit=200): @@ -83,6 +103,56 @@ def find_ids(text): return found +def class_keys(name): + """The lower-case names a test class goes by in a result file, for matching a test file's name (without its extension): the last two + parts of a dotted, slashed or $-nested name (a Python module and its class, a Java class), the outermost class of a nested one and, + for a file path, its file name with and without the extension.""" + text = str(name if name is not None else "")[:400] + parts = [p for p in re.split(r"[.$:/\\]+", text) if p] + outer = [p for p in re.split(r"[.:/\\]+", text.split("$")[0]) if p] + keys = {p.lower() for p in parts[-2:] + outer[-1:]} + if "/" in text or "\\" in text: + base = re.split(r"[/\\]", text)[-1] + keys.update((base.lower(), os.path.splitext(base)[0].lower())) + return keys + + +def run_evidence(results): + """What ran for one module, from its parsed results (baseline_diff.read_results, one per suite): {"known", "ids", "keys"}. + known: some result lists its tests one by one (a count, or a summary line of a log, names no test). + ids: the rule numbers named by the test name or class name of a test that ran and passed. + keys: class_keys of every class that has a test that ran and passed.""" + out = {"known": False, "ids": set(), "keys": set()} + for res in results: + if not res or not res.get("tests"): + continue + out["known"] = True + for tid, status in res["tests"].items(): + if status == "PASS" and "rule" in tid.lower(): + out["ids"].update(n for n, _ in find_ids(tid)) + for klass, c in (res.get("classes") or {}).items(): + if c.get("pass"): + out["keys"] |= class_keys(klass) + return out + + +def line_marks(body): + """([offset where each line starts], [whether the line holds a skip marker]) for one test file's text.""" + starts, flags, pos = [], [], 0 + for line in body.split("\n"): + starts.append(pos) + flags.append(SKIPPED_LINE.search(line) is not None) + pos += len(line) + 1 + return starts, flags + + +def is_live(marks, at): + """True when the mention at text offset `at` is not marked skipped: its own line and the 3 lines above hold no marker.""" + starts, flags = marks + i = bisect.bisect_right(starts, at) - 1 + return not any(flags[max(0, i - MARK_LINES):i + 1]) + + def field(lines, name): """The value of a "**Name:** value" line, or ''. Linear in the line length whatever the line holds.""" for line in lines: @@ -201,6 +271,26 @@ def walk_module(path, budget): return files, skipped, False +def is_tooling(name): + """A file that builds or runs code without being code: pom.xml, mvnw, package.json, conftest.py, *.csproj, ...""" + low = name.lower() + return low in TOOLING_NAMES or os.path.splitext(low)[1] in TOOLING_EXT or TOOLING_PATTERN.fullmatch(low) is not None + + +def tooling_only(path): + """True when a built folder holds test code and the files that build or run it, and nothing else that is not a document: at least + one test file, no main code. A file this does not recognise counts as main code, so a folder is only left out when it is clear.""" + files, _, cut = walk_module(path, MAX_FILES) + tests = 0 + for rel, _ in files: + kind = file_kind(rel) + if kind == "test": + tests += 1 + elif kind == "main" and not is_tooling(rel.rsplit("/", 1)[-1]): + return False + return tests > 0 and not cut + + def claims_of(notes, names): """(rule numbers claimed, rule rows naming no existing file, basenames of every file the notes name). A row claims a rule only when it names the rule AND a file that exists in the module.""" @@ -223,16 +313,20 @@ def claims_of(notes, names): return claimed, unresolved, named -def status_of(main, tests, claimed): - return "tested" if tests else "code only" if main else "claimed only" if claimed else "none" +def status_of(main, tests, claimed, ran=False): + """A rule's status. `ran`: executed evidence backs it. A test file that names it without that evidence is "named, not run".""" + return "tested" if ran else NOT_RUN if tests else "code only" if main else "claimed only" if claimed else "none" def blank(): - return {"main": 0, "tests": 0, "claimed": False, "named": False} + """`tests`: mentions in test files; `live`: those not marked skipped; `by`: how executed evidence backs the rule ("test name", "test file") or ''; `at`: the first + unskipped mention in a test file that ran (file:line), the one that backs it.""" + return {"main": 0, "tests": 0, "live": 0, "claimed": False, "named": False, "by": "", "at": ""} -def trace(workspace, system): - """-> the trace. Raises OSError when BUSINESS_RULES.md cannot be read.""" +def trace(workspace, system, ran=None): + """-> the trace. Raises OSError when BUSINESS_RULES.md cannot be read. + ran: {module folder (as "path" in the modules list): run_evidence(...)}: what ran, per module. Without it no rule is "tested".""" rules_path = os.path.join(workspace, "analysis", system, "BUSINESS_RULES.md") if os.path.islink(rules_path): raise OSError("analysis/%s/BUSINESS_RULES.md is a symbolic link" % system) @@ -257,6 +351,7 @@ def trace(workspace, system): ntext = read_text(os.path.join(mod["path"], notes_name), NOTES_CAP) if ntext is not None: claimed, unresolved, named = claims_of(ntext, names) + ev = (ran or {}).get(mod["rel"]) or NO_RUN test_files = 0 for rel, full in files: kind = file_kind(rel) @@ -267,13 +362,26 @@ def trace(workspace, system): body = read_text(full, FILE_CAP) scan["textFiles"] += body is not None hits = [(n, None) for n, _ in find_ids(os.path.basename(rel))] + [(n, at) for n, at in find_ids(body or "")] + # a test file backs the rules it names (on lines not marked skipped) when its name is the class or file of a test that ran and passed here + marks, backed = None, kind == "test" and bool(ev.get("known")) and os.path.splitext(os.path.basename(rel))[0].lower() in (ev.get("keys") or ()) for n, at in hits: if n not in by_n: continue - per[n].setdefault(mod["rel"], blank())[key] += 1 + slot = per[n].setdefault(mod["rel"], blank()) + slot[key] += 1 + if kind == "test": + if at is not None and marks is None: + marks = line_marks(body) + if at is None or is_live(marks, at): + slot["live"] += 1 + if backed and not slot["by"]: + slot["by"], slot["at"] = "test file", "%s/%s:%d" % (mod["rel"], rel, 0 if at is None else bisect.bisect_right(marks[0], at)) place = "%s/%s" % (mod["rel"], rel) if len(samples[n][key]) < SAMPLES and not any(s.rsplit(":", 1)[0] == place for s in samples[n][key]): samples[n][key].append("%s:%d" % (place, 0 if at is None else body.count("\n", 0, at) + 1)) + for n in (ev.get("ids") or ()): + if n in by_n: + per[n].setdefault(mod["rel"], blank())["by"] = "test name" for n in claimed & set(by_n): per[n].setdefault(mod["rel"], blank())["claimed"] = True for r in rules: @@ -290,7 +398,7 @@ def trace(workspace, system): main, tests_n = sum(s["main"] for s in slots.values()), sum(s["tests"] for s in slots.values()) claim = any(s["claimed"] for s in slots.values()) out.append({"id": r["id"], "name": r["name"], "priority": r["priority"], "confidence": r["confidence"], "source": r["source"], - "main": main, "tests": tests_n, "claimed": claim, "status": status_of(main, tests_n, claim), + "main": main, "tests": tests_n, "claimed": claim, "status": status_of(main, tests_n, claim, any(s["by"] for s in slots.values())), "perModule": slots, "samples": samples[r["n"]]}) if scan["cut"]: notes.append("More than %d files were found, so the scan stopped early." % MAX_FILES) @@ -304,30 +412,35 @@ def trace(workspace, system): def totals(rows): - """Per priority: rules, and how many are tested / code only / claimed only / none.""" + """Per priority: rules, and how many are tested / named, not run / code only / claimed only / none.""" out = {} for r in rows: - t = out.setdefault(r["priority"] or "unrated", {"rules": 0, "tested": 0, "code only": 0, "claimed only": 0, "none": 0}) + t = out.setdefault(r["priority"] or "unrated", {"rules": 0, "tested": 0, NOT_RUN: 0, "code only": 0, "claimed only": 0, "none": 0}) t["rules"] += 1 t[r["status"]] += 1 return dict(sorted(out.items())) +def module_row(r, slot): + """A rule as one module sees it: the module's own counts and the status they give.""" + return dict(r, main=slot["main"], tests=slot["tests"], live=slot["live"], claimed=slot["claimed"], by=slot["by"], at=slot["at"], + status=status_of(slot["main"], slot["tests"], slot["claimed"], bool(slot["by"]))) + + def module_view(result, rel): """The rules one module answers for, each with the module's own status. A rewrite answers for the rules its code, - tests or notes name, or whose legacy file its notes name; an uplift keeps the whole code, so it answers for all. - When nothing ties any rule to the module, every rule counts (`tied` is then False): an empty list must never pass.""" + tests or notes name, that a test of its run names, or whose legacy file its notes name; an uplift keeps the whole + code, so it answers for all. When nothing ties any rule to the module, every rule counts (`tied` is then False): + an empty list must never pass. `p0NoTests` lists the P0 rules that are not "tested": no executed test backs them.""" mod = next((m for m in result["modules"] if m["path"] == rel), None) rows, tied = [], True for r in result["rules"]: slot = r["perModule"].get(rel) or blank() - if mod and (mod["track"] == "uplift" or slot["main"] or slot["tests"] or slot["claimed"] or slot["named"]): - rows.append(dict(r, main=slot["main"], tests=slot["tests"], claimed=slot["claimed"], status=status_of(slot["main"], slot["tests"], slot["claimed"]))) + if mod and (mod["track"] == "uplift" or slot["main"] or slot["tests"] or slot["claimed"] or slot["named"] or slot["by"]): + rows.append(module_row(r, slot)) if mod and not rows and result["rules"]: tied = False - for r in result["rules"]: - slot = r["perModule"].get(rel) or blank() - rows.append(dict(r, main=slot["main"], tests=slot["tests"], claimed=slot["claimed"], status=status_of(slot["main"], slot["tests"], slot["claimed"]))) + rows = [module_row(r, r["perModule"].get(rel) or blank()) for r in result["rules"]] return {"rows": rows, "totals": totals(rows), "outOfScope": len(result["rules"]) - len(rows), "tied": tied, "p0NoTests": [r["id"] for r in rows if r["priority"] == "P0" and r["status"] != "tested"]} @@ -345,34 +458,50 @@ def render(result, everything=False, view=None, module=None): lines.append("Counted for this module: %d rule(s)%s" % (len(rows), "" if view["tied"] else " (nothing ties a rule to it by name, so every rule counts)")) lines.append("") for p, c in tot.items(): - lines.append("%-7s %3d rules: %d tested, %d code only, %d claimed only, %d none" % (p, c["rules"], c["tested"], c["code only"], c["claimed only"], c["none"])) + lines.append("%-7s %3d rules: %d tested, %d named not run, %d code only, %d claimed only, %d none" % (p, c["rules"], c["tested"], c[NOT_RUN], c["code only"], c["claimed only"], c["none"])) lines += ["", "%-9s %-4s %-7s %5s %5s %s" % ("Rule", "Pri", "Conf", "Code", "Tests", "Status")] shown = [r for r in rows if everything or r["priority"] == "P0"] + ([] if everything else [r for r in rows if r["priority"] != "P0"][:40]) for r in shown: lines.append("%-9s %-4s %-7s %5d %5d %s %s" % (r["id"], r["priority"] or "-", r["confidence"] or "-", r["main"], r["tests"], r["status"], clean(r["name"], 60))) if len(shown) < len(rows): lines.append("... %d more rule(s) not listed (use --all)" % (len(rows) - len(shown))) - lines += ["", "P0 rules with no test that names them: " + (", ".join(missing) if missing else "none")] + lines += ["", "P0 rules with no test that ran and passed behind them: " + (", ".join(missing) if missing else "none")] lines += ["Note: " + n for n in result["notes"]] return "\n".join(lines) def main(argv=None): - ap = argparse.ArgumentParser(description="Trace business rules to the code and tests that name them.") + ap = argparse.ArgumentParser(description="Trace business rules to the code and tests that name them, and to the tests that ran.") ap.add_argument("system", help="the system's folder name under analysis/") ap.add_argument("--workspace", default=".", help="the project root holding analysis/ and modernized/ (default: current folder)") ap.add_argument("--json", action="store_true", help="print the full trace as JSON") ap.add_argument("--all", action="store_true", help="list every rule, not just P0 and the first 40 others") ap.add_argument("--module", metavar="NAME", help="only the rules this built module answers for (a folder under modernized/<system>/)") + ap.add_argument("--results", action="append", default=[], metavar="PATH", + help="a JUnit or TRX result file, or a folder of them, from a run of the module named by --module (repeatable); only tests that ran and passed there make a rule 'tested'") args = ap.parse_args(argv) if not args.system or args.system in (".", "..") or re.search(r"[\\/\x00]", args.system): print("trace_rules.py: the system must be a folder name under analysis/, not a path", file=sys.stderr) return 2 + if args.results and not args.module: + print("trace_rules.py: --results goes with --module: say which module's run the results are from", file=sys.stderr) + return 2 + ran, read_notes = None, [] + if args.results: + found = next((m for m in discover_modules(args.workspace, args.system) if m["name"].lower() == args.module.lower()), None) + if found is not None: + sys.dont_write_bytecode = True # importing a sibling script must not leave __pycache__ in the plugin folder + import baseline_diff # only this command line reads result files itself; the proof pack passes them in + res = baseline_diff.read_results(args.results) + ran = {found["rel"]: run_evidence([res])} + read_notes = ["%d result file(s) read: %d test(s), %d passed." % (res["files"], len(res["tests"]), sum(1 for s in res["tests"].values() if s == "PASS"))] + read_notes += ["result file not used: " + u for u in res["unreadable"][:3]] + [clean(p, 200) for p in res["problems"][:3]] try: - result = trace(args.workspace, args.system) + result = trace(args.workspace, args.system, ran) except OSError as err: print("trace_rules.py: %s" % err, file=sys.stderr) return 2 + result["notes"] += read_notes or ["No test results were given, so no rule can be 'tested' here: the proof pack reads them from the result files (or add --module NAME --results PATH)."] view, mod = None, None if args.module: mod = next((m for m in result["modules"] if m["name"].lower() == args.module.lower()), None) |
