#!/usr/bin/env python3 """RB TestGen Kit — depth/jump audit, verdict helpers, and portability lint. LOCATION ON THE VM: deployed read-only to the testgen output dir. (NEVER edit; `import rb_testgen_kit` or `from rb_uia import rb_showing, rb_reach, ...`) Tests use pytest format with @pytest.mark.rb() markers. The conftest.py handles result collection automatically. This kit provides: - Verdict helpers: rb_showing, rb_reach, rb_flip, rb_value - Depth tracking: rb_enter, rb_back (used by the `rb` fixture) - Self-audit: rb_audit, rb_lint, rb_lint_sources, rb_audit_depth, rb_audit_tier PYTEST TEST FORMAT: @pytest.mark.rb(jump_kind="reach", expect="Preferences dialog visible") def test_prefs_opens(app, rb): rb.enter("prefs") before = rb_showing(app) # ... trigger ... after = rb_showing(app) assert rb_reach(before, after, target="Preferences", source="toolbar") VERDICT HELPERS (prove the jump kind — a bare `assert True` is unbacked): rb_reach(before, after, target, source) — tier2 reach (surface jump) rb_flip(before, after) — tier2 transition (state flip) rb_value(observed, expected) — tier3 value (specific content) SELF-AUDIT (report-only, NOT a hard gate): python -c "import rb_testgen_kit as k; k.rb_audit('')" python -c "import rb_testgen_kit as k; k.rb_audit_depth('','')" python -c "import rb_testgen_kit as k; k.rb_audit_tier('','')" """ 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. Tune here only. 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) } # Depth family (naming convention) — see rb_audit_depth. A test "crosses a surface" iff it # calls a member of the depth family; rb_back* pops one. Semantic aliases (rb_enter_dialog, # rb_reach_prefs) are matched BY PREFIX so the kit stays small and testcases stay diverse. DEPTH_FWD_RE = re.compile(r"^rb_(enter|reach)[a-z0-9_]*$") # forward crossing / proven jump DEPTH_BACK_RE = re.compile(r"^rb_back[a-z0-9_]*$") # pop a surface DEPTH_RESET_RE = re.compile(r"^rb_reset_depth$") # Verdict family (tier audit): a tier2/3 claim must be backed by its verdict function. # rb_reach* is counted by rb_audit_depth; rb_flip* and rb_value* are counted here. VERDICT_RE = re.compile(r"^rb_(reach|flip|value)[a-z0-9_]*$") _JK_FAMILY = {"reach": "reach", "transition": "flip", "value": "value"} # normalize plural (v73prep) / singular (kltg74) 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/page/submenu).""" global _DEPTH _DEPTH += 1 return _DEPTH def rb_back() -> int: global _DEPTH _DEPTH = max(0, _DEPTH - 1) return _DEPTH def rb_showing(root) -> set: """Snapshot visible UIA elements under root as {"control_type|name", ...}. Safe no-op ({}) if pywinauto is unavailable or root is None.""" out = set() if root is None: return out try: seen = 0 for el in root.descendants(): seen += 1 if seen > 6000: break try: if not el.is_visible(): continue ct = el.element_info.control_type or "" nm = el.element_info.name or "" out.add(f"{ct}|{nm}") except Exception: pass 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 in the tree.""" 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 return as record()'s `passed`. Does NOT touch depth — a flip is in-page (declare depth=0 unless you navigated a surface to reach the control). You MAY write your own `rb_flip_()` 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 return as record()'s `passed`. Tolerant: exact match, else the stringified `expected` appears in the stringified `observed` (substring/normalized), mirroring rb_reach's tolerant match. Does NOT touch depth. You MAY write your own `rb_value_()`.""" 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 # NOTE: rb_connect() and RBResults have been removed — replaced by: # - rb_uia.get_app() for app acquisition (used by conftest.py's `app` fixture) # - conftest.py's pytest hooks for automatic result collection # Tests now use pytest format: `def test_*(app, rb):` with `@pytest.mark.rb(...)` 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) print(f"[rb_audit] {'ALL TARGETS MET' if passed else 'some targets below — OPTIONALLY add a deeper reach/value test, or finalize if you have already tried enough angles (these are 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, "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 (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)) < 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, app launched by runner) # but break on the recreation (eval, app elsewhere). Each is a hard portability defect. _BAD_SOURCE_PATTERNS = [ (r"C:\\\\rb_pipeline|C:/rb_pipeline", "hardcodes the pipeline path (varies per task) — use the `app` fixture from conftest (backed by rb_uia.get_app())"), (r"\\\\workspace\\\\install|/workspace/install", "names a Linux-style install path — not applicable on Windows; use the `app` fixture from conftest"), (r"subprocess\.(?:Popen|run|call)\([^)]*[\"'][A-Z]:\\\\", "spawns the app by an absolute path — use the `app` fixture for portability"), (r"Application\([^)]*\)\.(?:start|connect)\([^)]*path\s*=", "uses pywinauto .start() or .connect(path=...) — use the `app` fixture for portability"), ] 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) and for helper/test API DRIFT (a test calls `H.()` that the imported helper module does not define — the hotspot connect_running/spawn_with_file class of bug). Returns + prints the issues. Run BEFORE finalize; a clean result means the suite will drive the recreation, not just the reference.""" import glob import re import ast 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_uia_tests.py")] defined: dict[str, set] = {} for p in py: mod = os.path.splitext(os.path.basename(p))[0] names: set = set() try: for node in ast.parse(open(p).read()).body: if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): names.add(node.name) elif isinstance(node, ast.Assign): for t in node.targets: if isinstance(t, ast.Name): names.add(t.id) except Exception: pass defined.setdefault(mod, set()).update(names) 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}") for m in re.finditer(r"import\s+(\w+)\s+as\s+(\w+)", src): mod, alias = m.group(1), m.group(2) if mod not in defined: continue for am in re.finditer(rf"\b{alias}\.(\w+)\s*\(", src): attr = am.group(1) if attr not in defined[mod]: issues.append( f"{base}: calls {alias}.{attr}() but {mod}.py never defines {attr} " f"(helper/test drift — the eval copy will AttributeError)") break 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 + TIER cross-check (report-only) ────────────────────────── 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 _verdict_family(cn: str) -> str: if cn.startswith("rb_reach"): return "reach" if cn.startswith("rb_flip"): return "flip" if cn.startswith("rb_value"): return "value" return "" def _scan(fn_node, local_funcs, budget: int = 2, seen=None): """Walk fn_node (+ up to `budget` levels of file-local functions it calls; cycle-guarded) and return (n_fwd, n_back, n_reach, verdicts, guarded): DEPTH axis — n_fwd/n_back = rb_enter*|rb_reach* / rb_back* counts; n_reach = the rb_reach* subset. TIER axis — verdicts = verdict families present among {reach, flip, value}; guarded = an assert/try gates the code.""" seen = seen if seen is not None else set() n_fwd = n_back = n_reach = 0 verdicts = set() guarded = False for node in ast.walk(fn_node): if isinstance(node, (ast.Assert, ast.Try)): guarded = True if not isinstance(node, ast.Call): continue cn = _ast_call_name(node) is_fwd = bool(DEPTH_FWD_RE.match(cn)) is_back = bool(DEPTH_BACK_RE.match(cn)) is_verdict = bool(VERDICT_RE.match(cn)) if is_fwd: n_fwd += 1 if cn.startswith("rb_reach"): n_reach += 1 elif is_back: n_back += 1 if is_verdict: verdicts.add(_verdict_family(cn)) if not (is_fwd or is_back or is_verdict) and budget > 0 and cn in local_funcs and cn not in seen: seen.add(cn) f, b, r, v, g = _scan(local_funcs[cn], local_funcs, budget - 1, seen) n_fwd += f n_back += b n_reach += r verdicts |= v guarded = guarded or g return n_fwd, n_back, n_reach, verdicts, guarded def _record_name_passed(call): """(name, passed_node) for a record() call: name = string-literal name arg (else None); passed_node = AST node of the `passed` argument.""" a = call.args if a and isinstance(a[0], ast.Constant) and isinstance(a[0].value, str): return a[0].value, (a[1] if len(a) >= 2 else None) if len(a) >= 2 and isinstance(a[1], ast.Constant) and isinstance(a[1].value, str): return a[1].value, (a[2] if len(a) >= 3 else None) return None, None def _passed_form(passed_node, guarded: bool) -> str: """Classify record()'s `passed`: 'bare_literal', 'guarded_literal', 'derived', or 'missing'.""" if passed_node is None: return "missing" if isinstance(passed_node, ast.Constant) and isinstance(passed_node.value, (bool, int)): return "guarded_literal" if guarded else "bare_literal" return "derived" def _enclosing_funcs(tree): spans = [] for n in ast.walk(tree): if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef)): end = max((getattr(c, "lineno", n.lineno) for c in ast.walk(n)), default=n.lineno) spans.append((n.lineno, end, n)) return spans def _scope_of(line, spans): best = None for s, e, node in spans: if s <= line <= e and (best is None or s > best[0]): best = (s, e, node) return best[2] if best else None def _has_depth_family(tree) -> bool: return any(isinstance(n, ast.Call) and DEPTH_FWD_RE.match(_ast_call_name(n)) for n in ast.walk(tree)) def _verdict_families_in(tree) -> set: return {_verdict_family(_ast_call_name(n)) for n in ast.walk(tree) if isinstance(n, ast.Call) and VERDICT_RE.match(_ast_call_name(n))} def _depth_backing_map(testgen_dir: str): """Parse the suite's test_uia_*.py (+ imported LOCAL helpers) and return (per_record, per_module) carrying BOTH axes' source evidence: per_record[(module,name)] = {measured_depth, measured_backing, n_reach, # DEPTH axis verdicts:set, passed_form:str} # TIER axis per_module[module] = {module_backing:bool, verdict_families:set, unmatched:int}.""" all_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_uia_tests.py")] trees = {} helper_depth = {} # stem -> bool (imported-helper DEPTH backing) helper_verdicts = {} # stem -> set (imported-helper TIER verdicts) for p in all_py: try: t = ast.parse(open(p, errors="replace").read()) except Exception: continue trees[p] = t stem = os.path.splitext(os.path.basename(p))[0] helper_depth[stem] = _has_depth_family(t) helper_verdicts[stem] = _verdict_families_in(t) per_record, per_module = {}, {} for p in [q for q in all_py if os.path.basename(q).startswith("test_uia_")]: t = trees.get(p) if t is None: continue stem = os.path.basename(p)[len("test_uia_"):-len(".py")] mod = _MODULE_ALIAS.get(stem, stem) local_funcs = {n.name: n for n in ast.walk(t) if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))} spans = _enclosing_funcs(t) imported = set() for n in ast.walk(t): if isinstance(n, ast.Import): for al in n.names: imported.add(al.name.split(".")[0]) elif isinstance(n, ast.ImportFrom) and n.module: imported.add(n.module.split(".")[0]) module_backing = _has_depth_family(t) or any(helper_depth.get(h) for h in imported) verdict_families = set(_verdict_families_in(t)) for h in imported: verdict_families |= helper_verdicts.get(h, set()) unmatched = 0 for n in ast.walk(t): if not (isinstance(n, ast.Call) and _ast_call_name(n) == "record"): continue nm, passed = _record_name_passed(n) fn = _scope_of(n.lineno, spans) if nm is not None else None if nm is None or fn is None: unmatched += 1 continue n_fwd, n_back, n_reach, verdicts, guarded = _scan(fn, local_funcs) measured_depth = max(0, max((n_fwd - n_reach) - n_back, 1 if n_reach >= 1 else 0)) per_record[(mod, nm)] = {"measured_depth": measured_depth, "measured_backing": n_fwd >= 1, "n_reach": n_reach, "verdicts": verdicts, "passed_form": _passed_form(passed, guarded)} per_module[mod] = {"module_backing": module_backing, "verdict_families": verdict_families, "unmatched": unmatched} return per_record, per_module def _load_declared_by_module(results_dir: str): """(module, name, depth:int, jump_kind) declared records — KEEPS the module (unlike _load_all, whose per-test dicts drop it).""" out, seen = [], 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 or base == "baseline_results.json": continue seen.add(base) try: data = json.load(open(path)) except Exception: continue m = data.get("module", "") if isinstance(data, dict) else "" mod = _MODULE_ALIAS.get(m, m) or base[: -len("_results.json")] for t in (data.get("tests", []) if isinstance(data, dict) else []): if not (isinstance(t, dict) and "name" in t): continue try: d = int(t.get("depth", 0) or 0) except Exception: d = 0 out.append((mod, t["name"], d, t.get("jump_kind", "none"))) return out 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 _results.json — so a test can't just TYPE depth=2. REPORT-ONLY (NOT a finalize gate): flags a declared depth>=1 or jump_kind="reach" that has NO backing call from the depth family rb_enter*/rb_reach* (directly, in a local wrapper it calls, or in an imported local helper). Variable-named records fall back to module-level backing so the wrapper/closure idiom is not false-flagged. depth-only; jump verdicts are a later phase.""" results_dir = results_dir or testgen_dir per_record, per_module = _depth_backing_map(testgen_dir) issues = [] for mod, name, depth, jk in _load_declared_by_module(results_dir): strong = depth >= 1 or jk == "reach" rec = per_record.get((mod, name)) if rec is not None: if strong and not rec["measured_backing"]: issues.append(f"{mod}:{name}: declared depth={depth}/jump_kind={jk} but NO " f"backing rb_enter*/rb_reach* call (fake depth)") elif jk == "reach" and rec["n_reach"] == 0: issues.append(f"{mod}:{name}: jump_kind=reach but no rb_reach* call in its code") elif strong and not per_module.get(mod, {}).get("module_backing", True): issues.append(f"{mod}:{name}: declared depth={depth}/jump_kind={jk} but the module " f"has NO rb_enter*/rb_reach* call anywhere (fake depth)") if issues: print(f"[rb_audit_depth] {len(issues)} fake-depth issue(s) (REPORT-ONLY — fix by adding " f"the rb_reach/rb_enter 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)") unm = sum(v.get("unmatched", 0) for v in per_module.values()) if unm: print(f"[rb_audit_depth] note: {unm} record(s) use non-literal names " f"(joined at module level, not per-test)") return issues 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. REPORT-ONLY (NOT a finalize gate). A tier2/3 claim must be backed by its verdict function — transition->rb_flip*, value->rb_value* — AND that verdict's bool result must be the record()'s `passed` (a bare-literal True is unbacked). reach's rb_reach* presence is already covered by rb_audit_depth, so here reach is only checked for a bare-literal pass.""" results_dir = results_dir or testgen_dir per_record, per_module = _depth_backing_map(testgen_dir) issues = [] for mod, name, _depth, jk in _load_declared_by_module(results_dir): fam = _JK_FAMILY.get(jk) if fam is None: continue rec = per_record.get((mod, name)) if rec is not None: has = fam in rec["verdicts"] if jk == "reach": if has and rec["passed_form"] == "bare_literal": issues.append(f"{mod}:{name}: jump_kind=reach — rb_reach* present but the " f"pass is a bare literal True (verdict not used as the result)") elif not has: issues.append(f"{mod}:{name}: declared jump_kind={jk} (tier {tier_of(jk)}) but no " f"rb_{fam}* verdict call — the tier is unbacked") elif rec["passed_form"] == "bare_literal": issues.append(f"{mod}:{name}: declared jump_kind={jk} — rb_{fam}* present but the " f"pass is a bare literal True (verdict not used as the result)") elif jk != "reach" and fam not in per_module.get(mod, {}).get("verdict_families", set()): issues.append(f"{mod}:{name}: declared jump_kind={jk} but the module has no " f"rb_{fam}* verdict anywhere") if issues: print(f"[rb_audit_tier] {len(issues)} unbacked-tier issue(s) (REPORT-ONLY — back a " f"transition with rb_flip(), a value with rb_value(), and pass its result as the " f"test's `passed`; or drop to a weaker jump_kind you can actually 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 | " "{audit_depth|audit_tier} [results_dir]}")