#!/usr/bin/env python3 """RB TestGen Kit — declare each test's NAVIGATION DEPTH and JUMP RIGOR so a suite's real interaction depth is measured (not inferred), uniformly recorded, and auditable. LOCATION ON THE VM: /workspace/output/rb_testgen_kit.py (READ-ONLY — never edit; `import rb_testgen_kit` from your tests and from audit commands). Two orthogonal properties decide whether a suite really exercises an app: * navigation DEPTH — surfaces crossed to reach the asserted state (0 = home, 1 = a dialog/page/submenu, 2+ = deeper). * jump RIGOR — what the assertion after the trigger actually checks. Every behavioral test DECLARES both via a pytest marker; conftest.py writes the superset _results.json (no RBResults class — pytest + the marker + the `rb` fixture record): @pytest.mark.rb(jump_kind=, expect="") def test_...(app, rb): ... 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 page/dialog jump: the target surface APPEARED and the source surface DISAPPEARED -> tier 2 "transition" a state flip (CHECKED/ENABLED/mode), before->after -> tier 2 "value" a specific expected value/content asserted -> tier 3 DEPTH is measured at runtime: call rb.enter("") on each real crossing; conftest records the MAX depth (a runtime count can't be faked, so no source audit). A flat-tree read of a deep element is NOT depth — depth counts surfaces you navigated. TRUE-JUMP HELPER (so "reach" cannot be faked by reading a flat tree): @pytest.mark.rb(jump_kind="reach", expect="Preferences dialog visible; toolbar gone") def test_prefs_opens(app, rb): before = rb_showing(app) rb.enter("prefs"); # real nav -> depth 1 after = rb_showing(app) check.is_true(rb_reach(before, after, target="Preferences", source="main toolbar")) PORTABLE APP ACQUISITION (so the SAME suite scores reference AND recreation, which live at DIFFERENT paths): the `app` fixture (conftest) attaches BY NAME via RB_APP_NAME — never spawn the binary, name /workspace/install, use a CLI flag, or seed GSettings. rb_lint_sources flags such non-portable code. SELF-AUDIT (REPORT-ONLY — goals, not a gate; conftest's terminal summary prints these at the end of run_baseline, or run them directly to target the next round): python3 -c "import rb_testgen_kit as k; k.rb_audit(''); \ k.rb_lint(''); k.rb_lint_sources('/workspace/output')" """ from __future__ import annotations 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 (structure gate) "interactive_min": 0.60, # reach|transition|value share of ALL tests "depth_ge1_min": 0.40, # depth>=1 share of INTERACTIVE tests (real navigation) "depth_ge2_min": 0.10, # depth>=2 share of INTERACTIVE tests (deep chains) "value_min": 0.25, # jump_kind=="value" share of INTERACTIVE tests (tier3 strength) } def tier_of(jump_kind: str) -> int: return JUMP_KINDS.get(jump_kind, 2) def rb_showing(root) -> set: """Snapshot the SHOWING+VISIBLE nodes under an AT-SPI root as {"role|name"}. Safe no-op ({}) if AT-SPI/gi is unavailable. Use before+after a trigger to feed rb_reach() so a 'reach' test proves a real surface change.""" out = set() try: import gi gi.require_version("Atspi", "2.0") from gi.repository import Atspi except Exception: return out stack = [root] seen = 0 while stack and seen < 6000: n = stack.pop() seen += 1 try: ss = n.get_state_set() if ss.contains(Atspi.StateType.SHOWING) and ss.contains( Atspi.StateType.VISIBLE ): out.add(f"{n.get_role_name()}|{n.get_name() or ''}") except Exception: pass try: for i in range(n.get_child_count()): c = n.get_child_at_index(i) if c is not None: stack.append(c) except Exception: pass 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 page jump from reading an element that was always present.""" 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 _load_all(results_dir: str) -> list[dict]: recs: list[dict] = [] seen_files = set() for pat in ( os.path.join(results_dir, "*_results.json"), os.path.join(results_dir, "results", "*_results.json"), ): for path in glob.glob(pat): base = os.path.basename(path) if base in seen_files: continue seen_files.add(base) try: data = json.load(open(path)) except Exception: continue for t in data.get("tests", []): 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 across a suite and check the double-axis quotas. Prints PASS/FAIL per quota with the concrete gap (how many tests to add), so the orchestrator can target its Improve round. Call BEFORE finalizing.""" 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)) >= 1) d2 = sum(1 for r in inter if int(r.get("depth", 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) if passed: print("[rb_audit] ALL TARGETS MET") else: print( "[rb_audit] some targets below — OPTIONALLY add a deeper reach/value " "test, or finalize if you've tried enough angles (goals, NOT a gate)" ) return { "total": n, "interactive": len(inter), "none": none_n, "liveness": live_n, "depth_ge1": d1, "depth_ge2": d2, "value": val, "passed": passed, "checks": [m for _o, m in checks], } def rb_lint(results_dir: str) -> list: """Flag weak/inconsistent declarations: missing expect on a value/transition/reach test, unknown jump_kind, or negative depth. Prints and 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 (name the observed target)" ) if jk == "liveness": issues.append( f"{nm}: liveness is tier1 — replace with an observable app effect" ) if int(r.get("depth", 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: each PASSES on the reference (app @ /workspace/install) # but BREAKS on the recreation (app elsewhere). The baseline pytest run can't catch them # (they pass on the reference), so this static scan is their only guard. _BAD_SOURCE_PATTERNS = [ ( r"/workspace/install", "names the reference install path /workspace/install (gone at eval) — " "attach to the running app via the `app` fixture (RB_APP_NAME)", ), ( r"/workspace/output/recreation", "names an eval-only path — a test must not know where the app is installed", ), ( r"[\"']gsettings[\"']|\bgsettings\s+set\b", "seeds state via gsettings — the recreation may not ship the reference schema; " "drive state through the GUI instead", ), ( r"subprocess\.(?:Popen|run|call)\([^)]*[\"'][^\"']*/(?:bin|usr|lib)/", "spawns the app by an absolute binary path — attach via the `app` fixture, " "do not launch the binary", ), ] def rb_lint_sources(testgen_dir: str) -> list: """Scan authored test/helper .py for NON-PORTABLE patterns (hardcoded install paths, self-spawn by absolute path, gsettings/schema seeding). Each PASSES on the reference but BREAKS on the recreation (different path) — the one defect class the baseline run can't surface. Run BEFORE finalize; a clean result means the suite will drive the recreation, not just the reference.""" 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 ("rb_testgen_kit.py", "run_atspi_tests.py", "rb_atspi.py", "conftest.py") ] issues = [] for p in py: base = os.path.basename(p) try: src = open(p).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 if __name__ == "__main__": import sys _fns = {"audit": rb_audit, "lint": rb_lint, "lint_sources": rb_lint_sources} if 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} ")