Datasets:
Download macos/codeeditapp-codeedit/tests/rb_testgen_kit.py from Qwen/RecreationBench: direct link, hf CLI and curl.
- Browser
- Download file 26.9 kB
-
https://huggingface.co/datasets/Qwen/RecreationBench/resolve/main/macos/codeeditapp-codeedit/tests/rb_testgen_kit.py
- Command line
-
hf download hf://datasets/Qwen/RecreationBench/macos/codeeditapp-codeedit/tests/rb_testgen_kit.py
-
curl -L -o rb_testgen_kit.py https://huggingface.co/datasets/Qwen/RecreationBench/resolve/main/macos/codeeditapp-codeedit/tests/rb_testgen_kit.py
26.9 kB
| #!/usr/bin/env python3 | |
| """RB TestGen Kit (macOS/AX port of the Linux v7.5 kit) — a test's NAVIGATION | |
| DEPTH and JUMP RIGOR are DECLARED (not inferred), uniformly recorded, and | |
| self-auditable. | |
| DIFFERENCE FROM LINUX: macOS tests are **pytest** (methods on Test* classes taking | |
| the `ax` fixture, plain asserts) — NOT standalone scripts calling R.record(). So the | |
| DECLARATION is a pytest marker on the test method: | |
| import rb_testgen_kit as kit | |
| @pytest.mark.rb(depth=1, jump_kind="reach", expect="Preferences window visible") | |
| def test_prefs_opens(self, ax_with_reset): | |
| before = kit.rb_showing(ax_with_reset) | |
| helpers.rb_reach_prefs(ax_with_reset) # a nav helper you name rb_reach_* / rb_enter_* | |
| after = kit.rb_showing(ax_with_reset) | |
| assert kit.rb_reach(before, after, target="Preferences", source="menu bar") | |
| conftest.py's pytest_runtest_makereport hook reads the marker + the test outcome and | |
| writes {name, passed, depth, jump_kind, tier, expect} so the runner can fold it into | |
| <module>_results.json. The audits below then read those records (+ the test SOURCE). | |
| jump_kind (verbatim strings — the audit/stats key off them): | |
| "none" no trigger; existence/structure only -> tier 0 | |
| "liveness" only "did not crash / still alive" -> tier 1 (weak; avoid) | |
| "reach" a real surface jump: the TARGET surface's element | |
| APPEARED and the SOURCE surface's element DISAPPEARED -> tier 2 | |
| "transition" a state flip (CHECKED/ENABLED/mode) before->after -> tier 2 | |
| "value" a specific expected value/content was asserted -> tier 3 | |
| DEPTH is the number of surfaces crossed before the assertion (0 = home/first screen, | |
| 1 = one dialog/panel/submenu, 2+ = deeper). A flat-tree read of a deep element is | |
| depth 0 — depth counts surfaces the test actually navigated through. | |
| REACH PROOF (so "reach" cannot be faked by reading a flat tree): | |
| before = rb_showing(ax) | |
| <trigger: click the menu item / status item> | |
| after = rb_showing(ax) | |
| ok = rb_reach(before, after, target="Preferences", source="menu bar") | |
| SELF-AUDIT (report-only — goals, NOT a hard gate on finalize): | |
| python3 -c "import rb_testgen_kit as k; k.rb_audit('<results_dir>')" | |
| python3 -c "import rb_testgen_kit as k; k.rb_lint('<results_dir>')" | |
| python3 -c "import rb_testgen_kit as k; k.rb_lint_sources('<testgen_dir>')" | |
| python3 -c "import rb_testgen_kit as k; k.rb_audit_depth('<testgen_dir>','<results_dir>')" | |
| """ | |
| from __future__ import annotations | |
| import ast | |
| import glob | |
| import json | |
| import os | |
| import re | |
| JUMP_KINDS = {"none": 0, "liveness": 1, "reach": 2, "transition": 2, "value": 3} | |
| # Double-axis quota TARGETS (fractions) — goals rb_audit REPORTS, NOT a hard gate. | |
| QUOTAS = { | |
| "existence_max": 0.30, # jump_kind=="none" share of ALL tests | |
| "interactive_min": 0.60, # reach|transition|value share of ALL tests | |
| "depth_ge1_min": 0.40, # depth>=1 share of INTERACTIVE tests | |
| "depth_ge2_min": 0.10, # depth>=2 share of INTERACTIVE tests | |
| "value_min": 0.25, # jump_kind=="value" share of INTERACTIVE tests | |
| } | |
| # Depth family: a test "crosses a surface" iff it calls a member of the depth family. | |
| # macOS accepts BOTH the naming convention rb_enter_*/rb_reach_* (write your own nav | |
| # helper and NAME it so) AND the existing verifier_helpers/ax_helpers navigation | |
| # functions (whitelist below) — so tests can reuse the mature reveal/navigate helpers. | |
| DEPTH_FWD_RE = re.compile(r"^rb_(enter|reach)[a-z0-9_]*$") | |
| DEPTH_BACK_RE = re.compile(r"^rb_back[a-z0-9_]*$") | |
| # verifier_helpers / ax_helpers navigation functions that OPEN or move to a new surface. | |
| FWD_WHITELIST = { | |
| "ensure_ui_visible", "ensure_panel_open", "open_actions_menu", "open_menu", | |
| "open_settings", "open_preferences", "open_dialog", "open_panel", "open_window", | |
| "navigate_month", "navigate", "switch_tab", "switch_mode", "switch_page", | |
| "select_tab", "reveal_window", "show_panel", "show_menu", | |
| } | |
| BACK_WHITELIST = { | |
| "dismiss_menus", "dismiss_panel", "dismiss_any_dialog", "close_panel", | |
| "close_window", "go_back", | |
| } | |
| # pytest fixtures that themselves navigate into a surface during setup (so a test taking | |
| # one legitimately has depth>=1 without a nav call in its own body). `ax` does NOT navigate. | |
| _NAV_FIXTURES = {"ax_with_reset", "open_panel"} | |
| # MEASURED-TIER verdict families (ported from keliang): a tier2/3 jump_kind must be BACKED | |
| # by its verdict function — transition->rb_flip*, value->rb_value*, reach->rb_reach* — whose | |
| # bool result is the test's assertion. Self-named wrappers count by prefix. | |
| TIER_FLIP_RE = re.compile(r"^rb_flip[a-z0-9_]*$") | |
| TIER_VALUE_RE = re.compile(r"^rb_value[a-z0-9_]*$") | |
| _JK_FAMILY = {"transition": "flip", "value": "value", "reach": "reach"} | |
| # normalize plural (v73prep) / singular module names so a JSON module ("button") and a | |
| # file stem ("buttons") join. | |
| _MODULE_ALIAS = {"menus": "menu", "buttons": "button", "states": "state", | |
| "structures": "structure", "texts": "text", | |
| "computations": "computation", "workflows": "workflow"} | |
| _DEPTH = 0 # module-global surface counter for rb_enter/rb_back | |
| def tier_of(jump_kind: str) -> int: | |
| return JUMP_KINDS.get(jump_kind, 2) | |
| def rb_reset_depth() -> None: | |
| global _DEPTH | |
| _DEPTH = 0 | |
| def rb_enter(_surface: str = "") -> int: | |
| """Call right after your test navigates into a new surface (dialog/panel/submenu).""" | |
| global _DEPTH | |
| _DEPTH += 1 | |
| return _DEPTH | |
| def rb_back() -> int: | |
| global _DEPTH | |
| _DEPTH = max(0, _DEPTH - 1) | |
| return _DEPTH | |
| def _walk_tree_nodes(node, out, seen): | |
| """Yield 'role|name' for a macOS AXHelper.tree() dict node (+children).""" | |
| if not isinstance(node, dict) or seen[0] >= 8000: | |
| return | |
| seen[0] += 1 | |
| role = str(node.get("role") or "") | |
| name = str(node.get("name") or node.get("value") or "") | |
| if role or name: | |
| out.add(f"{role}|{name}") | |
| for c in (node.get("children") or []): | |
| _walk_tree_nodes(c, out, seen) | |
| def rb_showing(ax, max_depth: int = 12) -> set: | |
| """Snapshot the currently-reachable AX subtree under the app as {"role|name"}. | |
| macOS AX has no AT-SPI SHOWING/VISIBLE state, so we approximate "showing" by the | |
| live AX tree (AXChildren) the app currently exposes — a new window/sheet/popover | |
| adds its elements; a dismissed one removes them. Feed before+after a trigger to | |
| rb_reach() so a 'reach' test proves a REAL surface change, not a flat-tree read. | |
| Safe no-op (empty set) if `ax` cannot produce a tree.""" | |
| out: set = set() | |
| try: | |
| tree = ax.tree(max_depth=max_depth) # AXHelper.tree() -> nested dict | |
| except Exception: | |
| return out | |
| _walk_tree_nodes(tree, out, [0]) | |
| return out | |
| def rb_reach(before, after, target: str, source: str | None = None) -> bool: | |
| """True-jump verdict: the TARGET surface's discriminating element newly APPEARED | |
| AND (if given) the SOURCE surface's discriminating element DISAPPEARED. This is | |
| what separates a real surface jump from reading an element that was always there.""" | |
| before = set(before or []) | |
| after = set(after or []) | |
| t = target.lower() | |
| appeared = any(t in k.lower() for k in (after - before)) | |
| if source is None: | |
| return appeared | |
| s = source.lower() | |
| src_before = any(s in k.lower() for k in before) | |
| src_after = any(s in k.lower() for k in after) | |
| return appeared and src_before and not src_after | |
| def rb_flip(before, after, expect: str = "") -> bool: | |
| """In-page STATE-FLIP verdict (tier2 `transition`): the observed state actually CHANGED | |
| before->after (a CHECKED/ENABLED/mode/selection value read the two times). Pass its bool | |
| as the test's assertion. Does NOT touch depth — an in-page flip is depth 0 unless you | |
| navigated a surface to reach the control. You MAY write your own `rb_flip_<what>()` wrapper.""" | |
| try: | |
| return before != after | |
| except Exception: | |
| return False | |
| def rb_value(observed, expected) -> bool: | |
| """VALUE verdict (tier3 `value`): a specific expected value/content matched what you | |
| OBSERVED on the reference. Pass its bool as the test's assertion. Tolerant: exact match, | |
| else the stringified `expected` appears in the stringified `observed` (mirrors rb_reach's | |
| tolerant match). Does NOT touch depth. You MAY write your own `rb_value_<what>()` wrapper.""" | |
| if observed is None: | |
| return False | |
| if observed == expected: | |
| return True | |
| try: | |
| return bool(str(expected)) and str(expected) in str(observed) | |
| except Exception: | |
| return False | |
| def rb_connect(app_name: str | None = None, wait_for_ready: bool = False): | |
| """PORTABLE app acquisition for STANDALONE use — attach BY NAME to the running app | |
| via AXHelper (never spawn, never hardcode the install path), so the SAME test drives | |
| the reference AND the recreation. In normal pytest runs the `ax` fixture already does | |
| this; use rb_connect only for a script run outside pytest. Returns an AXHelper or None.""" | |
| try: | |
| from ax_helpers import AXHelper | |
| except Exception: | |
| return None | |
| name = (app_name or os.environ.get("APP_NAME") or "").strip() | |
| if not name: | |
| return None | |
| try: | |
| return AXHelper(name, wait_for_ready=wait_for_ready) | |
| except Exception: | |
| return None | |
| class RBResults: | |
| """Optional standalone recorder (parity with the Linux kit). In pytest mode the | |
| conftest hook records depth/jump instead; keep this for scripts that self-run.""" | |
| def __init__(self, module: str, results_dir: str): | |
| self.module = module | |
| self.results_dir = results_dir | |
| self.tests: list[dict] = [] | |
| rb_reset_depth() | |
| def record(self, name: str, passed, *, depth: int | None = None, | |
| jump_kind: str = "none", expect: str = "", msg: str = "") -> None: | |
| if jump_kind not in JUMP_KINDS: | |
| jump_kind = "none" | |
| d = _DEPTH if depth is None else int(depth) | |
| p = bool(passed) | |
| self.tests.append({ | |
| "name": name, "passed": p, "status": "passed" if p else "failed", | |
| "depth": max(0, d), "jump_kind": jump_kind, "tier": tier_of(jump_kind), | |
| "expect": str(expect), "message": str(msg), | |
| }) | |
| self._flush() | |
| def _flush(self) -> None: | |
| payload = {"module": self.module, "tests": self.tests, | |
| "passed": sum(1 for t in self.tests if t["passed"]), | |
| "total": len(self.tests)} | |
| for p in (os.path.join(self.results_dir, self.module, f"{self.module}_results.json"), | |
| os.path.join(self.results_dir, f"{self.module}_results.json")): | |
| try: | |
| os.makedirs(os.path.dirname(p), exist_ok=True) | |
| with open(p, "w") as f: | |
| json.dump(payload, f, indent=2) | |
| except Exception: | |
| pass | |
| def _load_all(results_dir: str) -> list[dict]: | |
| """Every per-test record under results_dir (module subdirs included).""" | |
| recs: list[dict] = [] | |
| seen_files = set() | |
| for pat in (os.path.join(results_dir, "*_results.json"), | |
| os.path.join(results_dir, "*", "*_results.json"), | |
| os.path.join(results_dir, "results", "*_results.json")): | |
| for path in glob.glob(pat): | |
| key = os.path.relpath(path, results_dir) | |
| if key in seen_files or os.path.basename(path) == "baseline_results.json": | |
| continue | |
| seen_files.add(key) | |
| try: | |
| data = json.load(open(path)) | |
| except Exception: | |
| continue | |
| for t in (data.get("tests", []) if isinstance(data, dict) else []): | |
| if isinstance(t, dict) and "name" in t: | |
| recs.append(t) | |
| return recs | |
| def rb_audit(results_dir: str, quotas: dict | None = None) -> dict: | |
| """Aggregate declared depth/jump_kind and check the double-axis quotas. Prints | |
| PASS/GAP per quota so the orchestrator can target its Improve round. REPORT-ONLY.""" | |
| q = quotas or QUOTAS | |
| recs = _load_all(results_dir) | |
| n = len(recs) | |
| if not n: | |
| print(f"[rb_audit] no records under {results_dir}") | |
| return {"total": 0} | |
| kinds = [r.get("jump_kind", "none") for r in recs] | |
| none_n = sum(1 for k in kinds if k == "none") | |
| live_n = sum(1 for k in kinds if k == "liveness") | |
| inter = [r for r in recs if r.get("jump_kind") in ("reach", "transition", "value")] | |
| ni = len(inter) or 1 | |
| d1 = sum(1 for r in inter if int(r.get("depth", 0) or 0) >= 1) | |
| d2 = sum(1 for r in inter if int(r.get("depth", 0) or 0) >= 2) | |
| val = sum(1 for r in inter if r.get("jump_kind") == "value") | |
| def line(label, got, need, kind): | |
| ok = got >= need if kind == "min" else got <= need | |
| return (ok, f" [{'ok ' if ok else 'GAP'}] {label}: {got:.0%} " | |
| f"({'>=' if kind == 'min' else '<='} {need:.0%})") | |
| checks = [ | |
| line("existence(none)/all", none_n / n, q["existence_max"], "max"), | |
| line("interactive/all", len(inter) / n, q["interactive_min"], "min"), | |
| line("depth>=1 /interactive", d1 / ni, q["depth_ge1_min"], "min"), | |
| line("depth>=2 /interactive", d2 / ni, q["depth_ge2_min"], "min"), | |
| line("value(tier3)/interactive", val / ni, q["value_min"], "min"), | |
| ] | |
| print(f"[rb_audit] {results_dir} total={n} interactive={len(inter)} " | |
| f"none={none_n} liveness={live_n} depth>=1={d1} depth>=2={d2} value={val}") | |
| for _ok, msg in checks: | |
| print(msg) | |
| passed = all(ok for ok, _ in checks) | |
| print(f"[rb_audit] {'ALL TARGETS MET' if passed else 'some targets below — try a deeper reach/value test, or finalize (goals, NOT a hard gate)'}") | |
| return {"total": n, "interactive": len(inter), "none": none_n, "liveness": live_n, | |
| "depth_ge1": d1, "depth_ge2": d2, "value": val, "passed": passed} | |
| def rb_lint(results_dir: str) -> list: | |
| """Flag weak/inconsistent declarations: reach/transition/value with empty expect, | |
| liveness (tier1), unknown jump_kind, negative depth. Prints + returns the issues.""" | |
| recs = _load_all(results_dir) | |
| issues = [] | |
| for r in recs: | |
| jk = r.get("jump_kind", "none") | |
| nm = r.get("name", "?") | |
| if jk not in JUMP_KINDS: | |
| issues.append(f"{nm}: unknown jump_kind {jk!r}") | |
| if jk in ("reach", "transition", "value") and not str(r.get("expect", "")).strip(): | |
| issues.append(f"{nm}: jump_kind={jk} but empty expect (declare the specific observed target)") | |
| if jk == "liveness": | |
| issues.append(f"{nm}: liveness is tier1 — replace with the app-authored effect you can observe") | |
| if int(r.get("depth", 0) or 0) < 0: | |
| issues.append(f"{nm}: negative depth") | |
| if issues: | |
| print(f"[rb_lint] {len(issues)} issue(s):") | |
| for i in issues: | |
| print(" - " + i) | |
| else: | |
| print("[rb_lint] no issues") | |
| return issues | |
| # Non-portable source patterns: pass on the reference (testgen) but break on the | |
| # recreation (eval, app at a different path). Each is a hard portability defect on macOS. | |
| _BAD_SOURCE_PATTERNS = [ | |
| (r"\.pipeline_refapp|/pipeline_work/", | |
| "names a pipeline-internal reference path (gone/locked at eval) — attach via the ax fixture / rb_connect()"), | |
| (r"/workspace/output/recreation|/var/tmp/pipeline_results", | |
| "names an eval-only / pipeline path — a test must not know where the app is installed"), | |
| (r"defaults['\"\s,]+write", | |
| "seeds app state via `defaults write` — the recreation may use a different bundle id / defaults; drive state via the GUI"), | |
| (r"open\s+-a\s+[\"']?[A-Z]", | |
| "launches the app by a hardcoded name via `open -a` — use the ax fixture (host launches the app)"), | |
| (r"subprocess\.(?:Popen|run|call)\([^)]*[\"'][^\"']*/(?:Applications|Users|usr|bin|var)/", | |
| "spawns the app by an absolute path — attach to the launched instance via the ax fixture / rb_connect()"), | |
| (r"AXUIElementCreateApplication\(", | |
| "creates an AX app handle directly (usually a hardcoded pid/path) — use the ax fixture so the SAME test drives reference AND recreation"), | |
| ] | |
| def rb_lint_sources(testgen_dir: str) -> list: | |
| """Scan authored test/helper .py for NON-PORTABLE patterns (pipeline paths, defaults | |
| seeding, absolute-path spawn, direct AX app creation) — so the suite drives the | |
| recreation, not just the reference. REPORT-ONLY. Skips the kit/runner/helper libs.""" | |
| _SKIP = ("rb_testgen_kit.py", "run_ax_tests.py", "ax_test_runner.py", | |
| "ax_helpers.py", "verifier_helpers.py", "conftest.py", "verifier_template.py", | |
| "verifier_lint.py", "lint.py", "prune_failing_tests.py", "vlm_judge.py") | |
| py = [p for p in (glob.glob(os.path.join(testgen_dir, "*.py")) | |
| + glob.glob(os.path.join(testgen_dir, "tests", "*.py"))) | |
| if os.path.basename(p) not in _SKIP] | |
| issues = [] | |
| for p in py: | |
| base = os.path.basename(p) | |
| try: | |
| src = open(p, errors="replace").read() | |
| except Exception: | |
| continue | |
| for pat, why in _BAD_SOURCE_PATTERNS: | |
| if re.search(pat, src): | |
| issues.append(f"{base}: {why}") | |
| if issues: | |
| print(f"[rb_lint_sources] {len(issues)} portability issue(s):") | |
| for i in issues: | |
| print(" - " + i) | |
| else: | |
| print("[rb_lint_sources] no portability issues") | |
| return issues | |
| # ── MEASURED DEPTH cross-check (report-only): does the SOURCE back the DECLARED depth? ── | |
| # macOS tests are pytest: declaration is a `@pytest.mark.rb(depth=, jump_kind=)` decorator | |
| # on a Test* class method. A method with declared depth>=1 or jump_kind="reach" must call a | |
| # depth-family member (rb_enter*/rb_reach* OR a whitelisted nav helper) directly, in a | |
| # file-local helper it calls, or in an imported helper — else it is FAKE depth. | |
| def _ast_call_name(node) -> str: | |
| f = node.func | |
| if isinstance(f, ast.Attribute): | |
| return f.attr | |
| if isinstance(f, ast.Name): | |
| return f.id | |
| return "" | |
| def _is_fwd(cn: str) -> bool: | |
| return bool(DEPTH_FWD_RE.match(cn)) or cn in FWD_WHITELIST | |
| def _depth_calls(fn_node, local_funcs, budget: int = 2, seen=None): | |
| """(n_fwd, n_reach): depth-family forward calls in fn_node, descending up to `budget` | |
| levels into file-local functions it calls. Cycle-guarded. A LOWER BOUND on surfaces.""" | |
| seen = seen if seen is not None else set() | |
| n_fwd = n_reach = 0 | |
| for node in ast.walk(fn_node): | |
| if not isinstance(node, ast.Call): | |
| continue | |
| cn = _ast_call_name(node) | |
| if _is_fwd(cn): | |
| n_fwd += 1 | |
| if cn.startswith("rb_reach"): | |
| n_reach += 1 | |
| elif budget > 0 and cn in local_funcs and cn not in seen: | |
| seen.add(cn) | |
| f, r = _depth_calls(local_funcs[cn], local_funcs, budget - 1, seen) | |
| n_fwd += f | |
| n_reach += r | |
| return n_fwd, n_reach | |
| def _rb_marker(fn_node): | |
| """(depth, jump_kind) from a @pytest.mark.rb(...) decorator on a test method, else None.""" | |
| for dec in getattr(fn_node, "decorator_list", []): | |
| if not isinstance(dec, ast.Call): | |
| continue | |
| if _ast_call_name(dec) != "rb": | |
| continue | |
| depth, jk = 0, "none" | |
| for kw in dec.keywords: | |
| if kw.arg == "depth" and isinstance(kw.value, ast.Constant): | |
| try: | |
| depth = int(kw.value.value) | |
| except Exception: | |
| depth = 0 | |
| elif kw.arg == "jump_kind" and isinstance(kw.value, ast.Constant): | |
| jk = str(kw.value.value) | |
| return depth, jk | |
| return None | |
| def rb_audit_depth(testgen_dir: str, results_dir: str | None = None) -> list: | |
| """MEASURE navigation depth from the test SOURCE (AST) and cross-check the DECLARED | |
| depth/jump_kind in each @pytest.mark.rb(...) marker — so a test can't just TYPE depth=2. | |
| REPORT-ONLY: flags a declared depth>=1 or jump_kind="reach" whose method (and the local | |
| helpers it calls) has NO depth-family call (rb_enter*/rb_reach* or a whitelisted nav | |
| helper). Fix = add the nav helper you used (or name it rb_enter_*/rb_reach_*), or lower | |
| the declared depth. depth-only; jump verdicts are a later phase.""" | |
| issues = [] | |
| pys = sorted(glob.glob(os.path.join(testgen_dir, "test_ax_*.py")) | |
| + glob.glob(os.path.join(testgen_dir, "tests", "test_ax_*.py"))) | |
| for p in pys: | |
| try: | |
| src = open(p, errors="replace").read() | |
| tree = ast.parse(src) | |
| except Exception: | |
| continue | |
| mod = os.path.basename(p)[len("test_ax_"):-len(".py")] | |
| local_funcs = {n.name: n for n in ast.walk(tree) | |
| if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))} | |
| for node in ast.walk(tree): | |
| if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): | |
| continue | |
| if not node.name.startswith("test_"): | |
| continue | |
| marker = _rb_marker(node) | |
| if marker is None: | |
| continue | |
| depth, jk = marker | |
| if not (depth >= 1 or jk == "reach"): | |
| continue | |
| # A method is "backed" iff IT (or a file-local helper it calls) makes a | |
| # depth-family call, OR it takes a navigating fixture (ax_with_reset opens a | |
| # panel in its setup). We DELIBERATELY do NOT fall back to file-level backing | |
| # — that would let a fake-depth method ride on another test's nav call. | |
| params = {a.arg for a in node.args.args} | |
| fixture_nav = bool(params & _NAV_FIXTURES) | |
| n_fwd, n_reach = _depth_calls(node, local_funcs) | |
| if n_fwd == 0 and not fixture_nav: | |
| issues.append(f"{mod}:{node.name}: declared depth={depth}/jump_kind={jk} but NO " | |
| f"backing rb_enter*/rb_reach*/nav-helper call (fake depth)") | |
| elif jk == "reach" and n_reach == 0 and not fixture_nav: | |
| issues.append(f"{mod}:{node.name}: jump_kind=reach but no rb_reach* proof call " | |
| f"(use kit.rb_reach(before,after,...) to prove the surface jump)") | |
| if issues: | |
| print(f"[rb_audit_depth] {len(issues)} fake-depth issue(s) (REPORT-ONLY — add the " | |
| f"rb_reach/rb_enter/nav-helper you navigated with, or lower the declared depth):") | |
| for i in issues: | |
| print(" - " + i) | |
| else: | |
| print("[rb_audit_depth] no fake-depth issues (declared depth/reach backed by nav calls)") | |
| return issues | |
| def _tier_calls(fn_node, local_funcs, budget: int = 2, seen=None): | |
| """Set of verdict families {'flip','value','reach'} called in fn_node, descending up to | |
| `budget` levels into file-local helpers it calls. Cycle-guarded. Mirrors _depth_calls — | |
| self-named wrappers (rb_flip_*/rb_value_*/rb_reach_*) count by prefix.""" | |
| seen = seen if seen is not None else set() | |
| fams = set() | |
| for node in ast.walk(fn_node): | |
| if not isinstance(node, ast.Call): | |
| continue | |
| cn = _ast_call_name(node) | |
| if TIER_FLIP_RE.match(cn): | |
| fams.add("flip") | |
| elif TIER_VALUE_RE.match(cn): | |
| fams.add("value") | |
| elif cn.startswith("rb_reach"): | |
| fams.add("reach") | |
| elif budget > 0 and cn in local_funcs and cn not in seen: | |
| seen.add(cn) | |
| fams |= _tier_calls(local_funcs[cn], local_funcs, budget - 1, seen) | |
| return fams | |
| def rb_audit_tier(testgen_dir: str, results_dir: str | None = None) -> list: | |
| """MEASURE jump RIGOR from the test SOURCE (AST) and cross-check the DECLARED jump_kind in | |
| each @pytest.mark.rb(...) marker — so a test can't just TYPE jump_kind="value". REPORT-ONLY | |
| (NOT a finalize gate). A tier2/3 claim must be backed by its verdict call: transition->rb_flip*, | |
| value->rb_value* (reach->rb_reach* is already covered by rb_audit_depth). Flags a declared | |
| transition/value whose method (and the local helpers it calls) has NO such verdict call. | |
| Fix = add rb_flip(before,after)/rb_value(observed,expected) and pass its result as the assert, | |
| or drop to a weaker jump_kind you can prove. Pytest-marker form (mirrors rb_audit_depth), | |
| NOT keliang's record() form.""" | |
| issues = [] | |
| pys = sorted(glob.glob(os.path.join(testgen_dir, "test_ax_*.py")) | |
| + glob.glob(os.path.join(testgen_dir, "tests", "test_ax_*.py"))) | |
| for p in pys: | |
| try: | |
| src = open(p, errors="replace").read() | |
| tree = ast.parse(src) | |
| except Exception: | |
| continue | |
| mod = os.path.basename(p)[len("test_ax_"):-len(".py")] | |
| local_funcs = {n.name: n for n in ast.walk(tree) | |
| if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))} | |
| for node in ast.walk(tree): | |
| if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): | |
| continue | |
| if not node.name.startswith("test_"): | |
| continue | |
| marker = _rb_marker(node) | |
| if marker is None: | |
| continue | |
| _depth, jk = marker | |
| fam = _JK_FAMILY.get(jk) | |
| if fam is None or jk == "reach": # none/liveness need no verdict; reach->rb_audit_depth | |
| continue | |
| fams = _tier_calls(node, local_funcs) | |
| if fam not in fams: | |
| issues.append(f"{mod}:{node.name}: declared jump_kind={jk} (tier {tier_of(jk)}) but " | |
| f"NO backing rb_{fam}* verdict call — unbacked tier") | |
| if issues: | |
| print(f"[rb_audit_tier] {len(issues)} unbacked-tier issue(s) (REPORT-ONLY — back a " | |
| f"transition with rb_flip(before,after) and a value with rb_value(observed,expected), " | |
| f"passing its result as the assertion; or drop to a jump_kind you can prove):") | |
| for i in issues: | |
| print(" - " + i) | |
| else: | |
| print("[rb_audit_tier] no unbacked-tier issues (transition/value backed by verdict calls)") | |
| return issues | |
| if __name__ == "__main__": | |
| import sys | |
| _fns = {"audit": rb_audit, "lint": rb_lint, "lint_sources": rb_lint_sources} | |
| _fns2 = {"audit_depth": rb_audit_depth, "audit_tier": rb_audit_tier} | |
| if sys.argv[1:2] and sys.argv[1] in _fns2 and len(sys.argv) >= 3: | |
| _fns2[sys.argv[1]](sys.argv[2], sys.argv[3] if len(sys.argv) >= 4 else None) | |
| elif len(sys.argv) >= 3 and sys.argv[1] in _fns: | |
| _fns[sys.argv[1]](sys.argv[2]) | |
| else: | |
| print("usage: rb_testgen_kit.py {audit|lint|lint_sources <dir> | " | |
| "{audit_depth|audit_tier} <testgen_dir> [results_dir]}") | |