Datasets:
Upload folder using huggingface_hub (part 6)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- macos/shuang886-terminader/tests/fixtures/rbtest/gamma.txtAdded+1
- macos/shuang886-terminader/tests/fixtures/rbtest/readme.mdAdded+3
- macos/shuang886-terminader/tests/fixtures/rbtest/subdir/nested.txtAdded+1
- macos/shuang886-terminader/tests/rb_testgen_kit.pyAdded+575
- macos/shuang886-terminader/tests/requirements.txtAdded+3
- macos/shuang886-terminader/tests/terminader_helpers.pyAdded+671
- macos/shuang886-terminader/tests/test_ax_buttons.pyAdded+579
- macos/shuang886-terminader/tests/test_ax_computation.pyAdded+702
- macos/shuang886-terminader/tests/test_ax_menus.pyAdded+409
- macos/shuang886-terminader/tests/test_ax_states.pyAdded+605
- macos/shuang886-terminader/tests/test_ax_structure.pyAdded+705
- macos/shuang886-terminader/tests/test_ax_text.pyAdded+561
- macos/shuang886-terminader/tests/testcase_counts.jsonAdded+48
- macos/shuang886-terminader/tests/verifier_helpers.pyAdded+753
- macos/shuang886-terminader/vlm_assertions.jsonAdded+309
- macos/sn4k3-uvtools/LICENSEAdded+661
- macos/sn4k3-uvtools/instance.jsonAdded+10
- macos/sn4k3-uvtools/reference/build.shAdded+234
- macos/sn4k3-uvtools/reference/launch.shAdded+53
- macos/sn4k3-uvtools/tests/ax_helpers.pyAdded+849
- macos/sn4k3-uvtools/tests/conftest.pyAdded+584
- macos/sn4k3-uvtools/tests/rb_testgen_kit.pyAdded+575
- macos/sn4k3-uvtools/tests/requirements.txtAdded+3
- macos/sn4k3-uvtools/tests/test_ax_buttons.pyAdded+681
- macos/sn4k3-uvtools/tests/test_ax_computation.pyAdded+667
- macos/sn4k3-uvtools/tests/test_ax_menus.pyAdded+604
- macos/sn4k3-uvtools/tests/test_ax_states.pyAdded+855
- macos/sn4k3-uvtools/tests/test_ax_structure.pyAdded+421
- macos/sn4k3-uvtools/tests/test_ax_text.pyAdded+695
- macos/sn4k3-uvtools/tests/testcase_counts.jsonAdded+37
- macos/sn4k3-uvtools/tests/uv_helpers.pyAdded+615
- macos/sn4k3-uvtools/tests/verifier_helpers.pyAdded+753
- macos/sn4k3-uvtools/vlm_assertions.jsonAdded+205
- macos/sokoloffa-radiola/LICENSEAdded+21
- macos/sokoloffa-radiola/instance.jsonAdded+10
- macos/sokoloffa-radiola/reference/build.shAdded+102
- macos/sokoloffa-radiola/reference/launch.shAdded+48
- macos/sokoloffa-radiola/tests/ax_helpers.pyAdded+849
- macos/sokoloffa-radiola/tests/conftest.pyAdded+584
- macos/sokoloffa-radiola/tests/rb_radiola.pyAdded+789
- macos/sokoloffa-radiola/tests/rb_testgen_kit.pyAdded+575
- macos/sokoloffa-radiola/tests/requirements.txtAdded+3
- macos/sokoloffa-radiola/tests/test_ax_buttons.pyAdded+621
- macos/sokoloffa-radiola/tests/test_ax_computation.pyAdded+629
- macos/sokoloffa-radiola/tests/test_ax_states.pyAdded+799
- macos/sokoloffa-radiola/tests/test_ax_structure.pyAdded+563
- macos/sokoloffa-radiola/tests/test_ax_text.pyAdded+685
- macos/sokoloffa-radiola/tests/testcase_counts.jsonAdded+36
- macos/sokoloffa-radiola/tests/verifier_helpers.pyAdded
- macos/sokoloffa-radiola/vlm_assertions.jsonAdded
1gamma-content123# Heading One
Some *markdown* body text.1nested123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575#!/usr/bin/env python3"""RB TestGen Kit (macOS/AX port of the Linux v7.5 kit) — a test's NAVIGATIONDEPTH and JUMP RIGOR are DECLARED (not inferred), uniformly recorded, andself-auditable.
DIFFERENCE FROM LINUX: macOS tests are **pytest** (methods on Test* classes takingthe `ax` fixture, plain asserts) — NOT standalone scripts calling R.record(). So theDECLARATION 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 andwrites {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 isdepth 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 astimport globimport jsonimport osimport 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]}")123pytestpytest-checkpyobjc123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671"""terminader_helpers.py — shared, PORTABLE drivers for the Terminader AX test suite.
Every function here attaches to the ALREADY-RUNNING app through the `ax` AXHelper thepytest fixture hands the test. Nothing in this module knows where the app is installed,spawns it, or seeds defaults — so the SAME tests drive the reference app and a recreation.
Naming convention matters: navigation helpers are named `rb_enter_*` / `rb_reach_*` sorb_testgen_kit.rb_audit_depth() can see that a test declaring depth>=1 / jump_kind="reach"really crossed a surface.
Terminader is a Finder/Terminal hybrid: * GUI ("Finder") mode -> icon grid + status bar + icon-size slider * CLI ("Terminal") mode -> Console/Errors panes + search filter + command promptThe toolbar button on the trailing edge toggles between the two; its accessibility nameis the SF Symbol description ("terminal" in GUI mode, "Window" in CLI mode) and itsAXHelp is "Switch to Terminal" / "Switch to graphical interface"."""
from __future__ import annotations
import jsonimport osimport reimport subprocessimport timefrom collections import Counter
import Quartz
# ── constants observed on the reference app ────────────────────────────────────SIDEBAR_FAVORITES = ["Desktop", "Documents", "Downloads", "Movies", "Music", "Pictures"]SIDEBAR_HEADINGS = ["Favorites", "iCloud", "Locations"]SIDEBAR_STATIC = ["iCloud Drive", "Network"]
# Toolbar / CLI accessibility names (SF Symbol descriptions) and their help strings.TOGGLE_NAME_GUI = "terminal" # shown while in GUI mode -> press to get CLITOGGLE_NAME_CLI = "Window" # shown while in CLI mode -> press to get GUITOGGLE_HELP_GUI = "Switch to Terminal"TOGGLE_HELP_CLI = "Switch to graphical interface"BACK_HELP = "See folders you viewed previously"PASTE_NAME = "Next Page" # arrow.down.docPASTE_HELP = "Paste selected items"POPOUT_NAME = "rectangle.portrait.and.arrow.forward"FOLDER_ICON_NAME = "Move" # folder.fillFILE_ICON_NAME = "Document" # doc
CLI_PANES = ["Console", "Errors"]SEARCH_PLACEHOLDER = "\U0001f50d Search" # "🔍 Search"PROMPT_SUFFIX = "Arrow Right Circle " # Image(systemName: "arrow.right.circle")
# Fixture directory contents (created by the verifier; see fixtures/rbtest).RBTEST_NAME = "rbtest"RBTEST_ENTRIES = ["alpha.txt", "beta.txt", "gamma.txt", "readme.md", "subdir"]RBTEST_FILES = ["alpha.txt", "beta.txt", "gamma.txt", "readme.md"]RBTEST_DIRS = ["subdir"]RBTEST_TXT = ["alpha.txt", "beta.txt", "gamma.txt"]ALPHA_TEXT_JOINED = "alpha-content-line1 alpha-content-line2"README_HEADING = "Heading One"README_BODY = "Some markdown body text."LS_TABLE_HEADERS = ["Permissions", "Links", "Owner", "Group", "Size", "Date", "Name"]
KC_RETURN = 36KC_DELETE = 51KC_ESCAPE = 53
# ── fixtures ──────────────────────────────────────────────────────────────────def fixtures_root() -> str: """FIXTURES_DIR when the runner sets it, else a `fixtures/` dir next to this file.""" d = os.environ.get("FIXTURES_DIR", "").strip() if d and os.path.isdir(d): return d return os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures")
def rbtest_dir() -> str: """Absolute path of the sample directory the CLI tests `cd` into. Materialised on demand so the suite is self-contained even if fixtures/ was not shipped.""" root = os.path.join(fixtures_root(), RBTEST_NAME) try: os.makedirs(os.path.join(root, "subdir"), exist_ok=True) payload = { "alpha.txt": "alpha-content-line1\nalpha-content-line2\n", "beta.txt": "beta-content\n", "gamma.txt": "gamma-content\n", "readme.md": "# Heading One\n\nSome *markdown* body text.\n", } for name, body in payload.items(): p = os.path.join(root, name) if not os.path.exists(p): with open(p, "w") as f: f.write(body) nested = os.path.join(root, "subdir", "nested.txt") if not os.path.exists(nested): with open(nested, "w") as f: f.write("nested\n") except OSError: pass return root
def rbtest_parent_name() -> str: """Name of the directory that contains the sample dir (the fixtures folder itself). Used as a discriminating path-picker component without hardcoding any path.""" return os.path.basename(os.path.dirname(rbtest_dir().rstrip("/")))
def home_dir_name() -> str: """Leaf name of the user's home directory — the app's start-up location.""" return os.path.basename(os.path.expanduser("~").rstrip("/"))
# ── low-level input ───────────────────────────────���───────────────────────────def activate(ax) -> None: """Bring the app under test frontmost (by pid) so synthetic keystrokes land in it.""" try: from AppKit import NSRunningApplication app = NSRunningApplication.runningApplicationWithProcessIdentifier_( int(ax.get_pid())) if app is not None: app.activateWithOptions_(1 << 1) time.sleep(0.4) except Exception: pass
def cg_key(keycode: int, repeat: int = 1, pause: float = 0.06) -> None: src = Quartz.CGEventSourceCreate(Quartz.kCGEventSourceStateHIDSystemState) for _ in range(max(1, repeat)): for down in (True, False): Quartz.CGEventPost( Quartz.kCGHIDEventTap, Quartz.CGEventCreateKeyboardEvent(src, keycode, down)) time.sleep(pause)
def cg_type(text: str, delay: float = 0.012) -> None: """Type `text` as real unicode key events into the frontmost app.""" src = Quartz.CGEventSourceCreate(Quartz.kCGEventSourceStateHIDSystemState) for ch in text: for down in (True, False): ev = Quartz.CGEventCreateKeyboardEvent(src, 0, down) Quartz.CGEventKeyboardSetUnicodeString(ev, len(ch), ch) Quartz.CGEventPost(Quartz.kCGHIDEventTap, ev) time.sleep(delay)
def _frame(ax, el): pos = ax.get(el.id, ["AXPosition"]).get("AXPosition") siz = ax.get(el.id, ["AXSize"]).get("AXSize") p = [float(v) for v in re.findall(r"[-\d.]+", str(pos))[-2:]] if pos else [] s = [float(v) for v in re.findall(r"[-\d.]+", str(siz))[-2:]] if siz else [] if len(p) < 2 or len(s) < 2: return None return p[0], p[1], s[0], s[1]
def element_size(ax, el): f = _frame(ax, el) return (f[2], f[3]) if f else (0.0, 0.0)
def cg_click_element(ax, el, clicks: int = 1) -> bool: """Real mouse click at an element's centre; `clicks=2` sends a proper double click (clickState 1 then 2) which is what the icon grid needs to open a directory.""" f = _frame(ax, el) if f is None: return False pt = Quartz.CGPointMake(f[0] + f[2] / 2.0, f[1] + f[3] / 2.0) for i in range(1, max(1, clicks) + 1): for kind in (Quartz.kCGEventLeftMouseDown, Quartz.kCGEventLeftMouseUp): ev = Quartz.CGEventCreateMouseEvent(None, kind, pt, Quartz.kCGMouseButtonLeft) Quartz.CGEventSetIntegerValueField(ev, Quartz.kCGMouseEventClickState, i) Quartz.CGEventPost(Quartz.kCGHIDEventTap, ev) time.sleep(0.06) time.sleep(0.5) return True
# ── generic AX lookups ────────────────────────────────────────────────────────def find_buttons(ax, name): return ax.find(role="button", name=name, max_results=6, max_depth=20)
def button_state(ax, name): """(found, enabled, help) for the first button called `name`. The toolbar wraps each item in an outer button + inner button; the inner one carries AXHelp.""" els = find_buttons(ax, name) if not els: return False, False, None helps = [ax.get(e.id, ["AXHelp"]).get("AXHelp") for e in els] help_txt = next((h for h in helps if h), None) return True, any(e.enabled for e in els), help_txt
def press_button(ax, name) -> bool: for el in find_buttons(ax, name): if not el.enabled: continue if "AXPress" in el.actions and ax.action(el.id, "AXPress"): return True return False
def all_texts(ax): """Every non-empty AXValue/AXTitle text in the app, in tree order.""" out = [] for el in ax.find(role="label", max_results=400, max_depth=24): v = el.value if el.value else el.name if v: out.append(str(v)) return out
def text_snapshot(ax): return Counter(all_texts(ax))
def window_titles(ax): out = [] for w in ax.find(role="window", max_results=12, max_depth=1): out.append(str(ax.get(w.id, ["AXTitle"]).get("AXTitle") or "")) return out
def close_extra_windows(ax) -> int: """Close every window except the main ContentView window (title == "").""" closed = 0 for w in ax.find(role="window", max_results=12, max_depth=1): title = str(ax.get(w.id, ["AXTitle"]).get("AXTitle") or "") if not title: continue for b in ax.find(role="button", root_id=w.id, max_results=20): if ax.get(b.id, ["AXSubrole"]).get("AXSubrole") == "AXCloseButton": ax.action(b.id, "AXPress") closed += 1 time.sleep(0.6) break return closed
def dismiss_menus(ax) -> None: cg_key(KC_ESCAPE) cg_key(KC_ESCAPE) time.sleep(0.2)
# ── mode (GUI / CLI) ──────────────────────────────────────────────────────────def is_cli_mode(ax) -> bool: return bool(ax.find(role="radio", name="Console", max_results=1, max_depth=20))
def is_gui_mode(ax) -> bool: return bool(ax.find(role="slider", max_results=1, max_depth=20)) and not is_cli_mode(ax)
def toggle_mode(ax) -> bool: """Press the GUI/CLI toolbar toggle whichever face it currently shows.""" return press_button(ax, TOGGLE_NAME_GUI) or press_button(ax, TOGGLE_NAME_CLI)
def rb_enter_cli(ax) -> bool: """Cross into the Terminal (CLI) surface. Idempotent.""" if is_cli_mode(ax): activate(ax) return True toggle_mode(ax) time.sleep(1.2) activate(ax) return is_cli_mode(ax)
def rb_enter_gui(ax) -> bool: """Cross into the graphical (Finder) surface. Idempotent.""" if not is_cli_mode(ax): return True toggle_mode(ax) time.sleep(1.2) return not is_cli_mode(ax)
# ── CLI: command prompt ───────────────────────────────────────────────────────def prompt_label_value(ax): """The green "<dir> ➜ " prompt text left of the command line, or None.""" for t in all_texts(ax): if t.endswith(PROMPT_SUFFIX): return t return None
def command_line_text(ax) -> str: """Text currently typed at the command prompt (includes the 1-char block cursor).""" texts = all_texts(ax) for i, t in enumerate(texts): if t.endswith(PROMPT_SUFFIX) and i + 1 < len(texts): return texts[i + 1] return ""
def clear_command_line(ax) -> None: activate(ax) cg_key(KC_DELETE, repeat=60, pause=0.008) time.sleep(0.2)
def run_command(ax, command: str, wait: float = 2.6) -> None: """Type `command` at the CLI prompt and press Return. Requires CLI mode.""" activate(ax) cg_type(command) time.sleep(0.25) cg_key(KC_RETURN) time.sleep(wait)
def command_output(ax, command: str) -> str: """The output text of the console entry whose command label == `command`. Console entries render as: prompt, command, relative-date, [status], output.""" texts = all_texts(ax) for i in range(len(texts) - 1, -1, -1): if texts[i] == command: for j in range(i + 1, min(i + 5, len(texts))): cand = texts[j] if _is_relative_date(cand) or cand.isdigit(): continue return cand return ""
_REL_DATE = re.compile(r"^\d+\s+(sec|min|hr|hour|day|week|month|year)")
def _is_relative_date(t: str) -> bool: return bool(_REL_DATE.match(t.strip()))
def console_commands(ax): """Command strings of the console entries currently displayed (filter-aware).""" out = [] texts = all_texts(ax) for i, t in enumerate(texts): if t.endswith(" % ") and i + 1 < len(texts): out.append(texts[i + 1]) return out
# ── CLI: panes + search filter ────────────────────────────────────────────────def pane_states(ax): """{"Console": 1/0, "Errors": 1/0} from the segmented control's radio values.""" out = {} for el in ax.find(role="radio", max_results=6, max_depth=20): if el.name in CLI_PANES: try: out[el.name] = int(el.value or 0) except (TypeError, ValueError): out[el.name] = 0 return out
def rb_enter_pane(ax, name: str) -> bool: """Select the "Console" or "Errors" pane of the CLI surface.""" for el in ax.find(role="radio", name=name, max_results=3, max_depth=20): if "AXPress" in el.actions and ax.action(el.id, "AXPress"): time.sleep(1.0) return True return False
def search_field(ax): els = ax.find(role="text_field", max_results=3, max_depth=20) return els[0] if els else None
def type_in_search(ax, text: str) -> bool: """Focus the console filter field with a real click, then type. A plain AXValue write is accepted by the text field but never reaches the SwiftUI binding, so the console would not filter — the click+type path is the one that works.""" tf = search_field(ax) if tf is None: return False activate(ax) cg_click_element(ax, tf) cg_type(text) time.sleep(1.2) return True
# ── GUI: grid, status bar, slider ─────────────────────────────────────────────def status_text(ax) -> str: """The GUI status-bar line: "N items, X available" / "N of M selected, X available".""" for t in all_texts(ax): if ("item" in t or "selected" in t) and "available" in t: return t return ""
def status_counts(ax): """(selected, total) parsed from the status bar; selected is None when nothing is.""" t = status_text(ax) m = re.match(r"^(\d+) of (\d+) selected", t) if m: return int(m.group(1)), int(m.group(2)) m = re.match(r"^(\d+) items?,", t) if m: return None, int(m.group(1)) return None, None
def path_popup(ax): els = ax.find(role="popup", max_results=3, max_depth=20) return els[0] if els else None
def path_popup_value(ax) -> str: el = path_popup(ax) if el is None: return "" return str(ax.get(el.id, ["AXValue"]).get("AXValue") or "")
def current_dir_name(ax) -> str: return path_popup_value(ax).strip()
def sidebar_outline(ax): els = ax.find(role="outline", name="Sidebar", max_results=2, max_depth=20) if els: return els[0] els = ax.find(role="outline", max_results=2, max_depth=20) return els[0] if els else None
def _sidebar_text_set(ax): out = set(SIDEBAR_STATIC) | set(SIDEBAR_HEADINGS) return out
def grid_names(ax): """File/directory names shown in the GUI icon grid (sidebar + status bar removed).""" skip = _sidebar_text_set(ax) out = [] for t in all_texts(ax): if t in skip: continue if "available" in t: continue if t.endswith(PROMPT_SUFFIX): continue out.append(t) return out
def grid_icons(ax): """Icon AXImage elements of the grid: AXDescription "Move" (folder) / "Document".""" return [e for e in ax.find(role="image", max_results=60, max_depth=22) if e.name in (FOLDER_ICON_NAME, FILE_ICON_NAME)]
def icon_named(ax, file_name: str): """The grid icon that belongs to `file_name`, matched by column position: the icon and its label share a horizontal centre.""" label = None for el in ax.find(role="label", max_results=400, max_depth=22): if str(el.value or "") == file_name: label = el break if label is None: return None lf = _frame(ax, label) if lf is None: return None lcx = lf[0] + lf[2] / 2.0 best, best_dx = None, 1e9 for ic in grid_icons(ax): f = _frame(ax, ic) if f is None: continue dx = abs((f[0] + f[2] / 2.0) - lcx) if f[1] < lf[1] and dx < best_dx: best, best_dx = ic, dx return best if best_dx < 60 else best
def click_file(ax, file_name: str) -> bool: """Single-click a grid item -> it becomes the selection.""" ic = icon_named(ax, file_name) if ic is None: return False activate(ax) return cg_click_element(ax, ic, clicks=1)
def rb_enter_directory(ax, dir_name: str) -> bool: """Double-click a directory in the grid to descend into it (a new surface).""" ic = icon_named(ax, dir_name) if ic is None: return False activate(ax) cg_click_element(ax, ic, clicks=2) time.sleep(1.4) return current_dir_name(ax) == dir_name
def icon_slider(ax): els = ax.find(role="slider", max_results=3, max_depth=22) return els[0] if els else None
def set_icon_slider(ax, value: float) -> bool: s = icon_slider(ax) if s is None: return False ok = ax.set_value(s.id, float(value)) time.sleep(0.9) return ok
def icon_slider_value(ax): s = icon_slider(ax) if s is None: return None v = ax.get(s.id, ["AXValue"]).get("AXValue") try: return float(v) except (TypeError, ValueError): return None
def largest_icon_extent(ax): """Longest side of the biggest grid icon — tracks the icon-size slider (32...512).""" best = 0.0 for ic in grid_icons(ax): w, h = element_size(ax, ic) best = max(best, w, h) return best
# ── navigation into other surfaces ────────────────────────────────────────────def rb_enter_fixtures(ax) -> bool: """CLI `cd` into the fixture sample directory. Leaves the app in CLI mode.""" if not rb_enter_cli(ax): return False run_command(ax, "cd " + rbtest_dir(), wait=1.8) return current_dir_name(ax) == RBTEST_NAME
def rb_enter_fixtures_gui(ax) -> bool: """`cd` into the fixture directory and come back to the graphical grid.""" if not rb_enter_fixtures(ax): return False return rb_enter_gui(ax) and current_dir_name(ax) == RBTEST_NAME
def rb_reach_context_menu(ax, file_name: str): """AXShowMenu on a grid item -> the context-menu item names that appear.""" ic = icon_named(ax, file_name) if ic is None: return [] ax.action(ic.id, "AXShowMenu") # returns kAXErrorFailure yet does open the menu time.sleep(1.2) return [e.name for e in ax.find(role="menu_item", max_results=250, max_depth=8) if e.name in ("Open", "Get Info")]
def rb_reach_get_info(ax, file_name: str) -> bool: """Grid item -> context menu -> "Get Info" -> the "<name> Info" window.""" if "Get Info" not in rb_reach_context_menu(ax, file_name): return False for e in ax.find(role="menu_item", name="Get Info", max_results=3, max_depth=8): if ax.action(e.id, "AXPress"): time.sleep(1.8) return True return False
def rb_reach_path_menu(ax): """Press the toolbar path picker -> the path-component item names that appear (de-duplicated: the picker's menu shows up twice in the AX tree).""" el = path_popup(ax) if el is None: return [] ax.action(el.id, "AXPress") time.sleep(1.2) out = [] for e in ax.find(role="menu_item", max_results=250, max_depth=6): if e.name and str(e.name).endswith(" "): name = str(e.name).strip() if name and name not in out: out.append(name) return out
def rb_reach_path_component(ax, name: str) -> bool: """Pick a component out of the open path-picker menu (call rb_reach_path_menu first).""" for e in ax.find(role="menu_item", max_results=250, max_depth=6): if str(e.name or "").strip() == name: ok = ax.action(e.id, "AXPress") time.sleep(1.4) return ok return False
def rb_reach_popout(ax) -> bool: """Press the pop-out button of the newest console entry -> its own window.""" els = ax.find(role="button", name=POPOUT_NAME, max_results=10, max_depth=24) if not els: return False ok = ax.action(els[-1].id, "AXPress") time.sleep(1.8) return ok
def menu_bar_titles(ax): return [e.name for e in ax.find(role="menu_bar_item", max_results=12, max_depth=3) if e.name]
def menu_items(ax, menu_title: str): """Item names of an app menu, read straight from the static AX menu hierarchy.""" for mbi in ax.find(role="menu_bar_item", name=menu_title, max_results=2, max_depth=3): return [e.name for e in ax.find(role="menu_item", root_id=mbi.id, max_results=60, max_depth=2) if e.name] return []
def rb_enter_menu(ax, menu_title: str): """Open an app menu for real (AXPress the menu-bar item) and return its item names.""" for mbi in ax.find(role="menu_bar_item", name=menu_title, max_results=2, max_depth=3): ax.action(mbi.id, "AXPress") time.sleep(0.8) return [e.name for e in ax.find(role="menu_item", root_id=mbi.id, max_results=60, max_depth=2) if e.name] return []
def rb_reach_menu_item(ax, menu_title: str, item_name: str) -> bool: """Activate <menu> > <item>.""" for mbi in ax.find(role="menu_bar_item", name=menu_title, max_results=2, max_depth=3): for e in ax.find(role="menu_item", root_id=mbi.id, max_results=60, max_depth=2): if e.name == item_name: ok = ax.action(e.id, "AXPress") time.sleep(1.8) return ok return False
# ── screenshots for the VLM judge ─────────────────────────────────────────────def results_dir() -> str: return os.environ.get("RESULTS_DIR", os.path.join( os.path.dirname(os.path.abspath(__file__)), "baseline_results"))
def screenshot_assert(test_name, description, results_dir): """Take screenshot and record visual assertion for VLM evaluation.""" ss_dir = os.path.join(results_dir, "screenshots") os.makedirs(ss_dir, exist_ok=True) ss_path = os.path.join(ss_dir, f"{test_name}.png") try: subprocess.run(["screencapture", "-x", ss_path], timeout=5) except Exception: pass assertions_file = os.path.join(ss_dir, "assertions.json") assertions = {} if os.path.exists(assertions_file): try: with open(assertions_file) as f: assertions = json.load(f) except Exception: assertions = {} assertions[f"{test_name}.png"] = description with open(assertions_file, "w") as f: json.dump(assertions, f, indent=2)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579"""AX BUTTON interaction tests for Terminader — the BUTTONS lane (recon rows B1-B11).
Every test PRESSES something and proves what the press PRODUCED (a surface jump, a stateflip, or a concrete value). There are deliberately no "button exists" / "did not crash"tests here — the structure lane owns existence.
Portable by construction: the app is reached only through the `ax` fixture from thedeployed conftest.py, and every interaction goes through the shared driver module`terminader_helpers` (alias `th`). No absolute app paths, no `open -a`, noAXUIElementCreateApplication, no user-defaults seeding.
Covered buttons (locator = role=button + AXDescription): B1/B2 mode toggle 'terminal' <-> 'Window' (toolbar, trailing edge) B3/B4 sidebar favourites 'Documents' / 'Desktop' / 'Downloads' / 'Pictures' B5 sidebar home-directory favourite (th.home_dir_name()) B6/B7 toolbar 'Back' / 'Forward' B8 CLI paste button 'Next Page' (AXHelp 'Paste selected items') + count badge B9 console-entry pop-out 'rectangle.portrait.and.arrow.forward' B10 toolbar 'Hide Sidebar' / 'Show Sidebar' B11 toolbar path picker (AXPopUpButton) -> path-chain menu
NEVER pressed here: the window close/minimise/full-screen buttons, Quit/Close/Close All,Delete — see the recon NEVER-PRESS list."""
from __future__ import annotations
import osimport reimport sysimport time
import pytest
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import terminader_helpers as th # noqa: E402 (shared portable driver)import rb_testgen_kit as kit # noqa: E402 (depth / jump verdicts)
RESULTS_DIR = os.environ.get("RESULTS_DIR", ".")
EM_DASH = "—" # pop-out title separator, U+2014STATUS_RE = re.compile(r"^\d+ items?, .* available$")
# ── navigation helpers (named rb_enter_* / rb_reach_* so the depth audit can see them) ──def rb_enter_sidebar_favourite(ax, name: str) -> bool: """Press a sidebar favourite button -> the app navigates into that directory.""" ok = th.press_button(ax, name) time.sleep(1.4) return bool(ok) and th.current_dir_name(ax) == name
def rb_enter_previous_directory(ax) -> bool: """Press the toolbar `Back` button -> cross back into the previously viewed directory.""" ok = th.press_button(ax, "Back") time.sleep(1.4) return bool(ok)
def rb_enter_next_directory(ax) -> bool: """Press the toolbar `Forward` button -> cross forward into the later directory again.""" ok = th.press_button(ax, "Forward") time.sleep(1.4) return bool(ok)
def rb_reach_hidden_sidebar(ax) -> bool: """Press the toolbar `Hide Sidebar` button -> the sidebar surface goes away.""" ok = th.press_button(ax, "Hide Sidebar") time.sleep(1.2) return bool(ok)
def rb_reach_shown_sidebar(ax) -> bool: """Press the toolbar `Show Sidebar` button -> the sidebar surface comes back.""" ok = th.press_button(ax, "Show Sidebar") time.sleep(1.2) return bool(ok)
# ── read-only observers ───────────────────────────────────────────────────────def toggle_face(ax): """(name, AXHelp) of whichever face the GUI/CLI mode-toggle toolbar button shows.""" for name in (th.TOGGLE_NAME_GUI, th.TOGGLE_NAME_CLI): found, _enabled, help_txt = th.button_state(ax, name) if found: return (name, help_txt) return (None, None)
def badge_image_names(ax): """AXDescriptions of the paste button's selection-count badge images ('<n>.circle.fill').""" return sorted(str(e.name) for e in ax.find(role="image", max_results=80, max_depth=24) if str(e.name or "").endswith("circle.fill"))
def visible_button_names(ax): """Set of every button AXDescription currently in the tree.""" return {str(e.name) for e in ax.find(role="button", max_results=80, max_depth=20) if e.name}
# ══════════════════════════════════════════════════════════════════════════════# B1 / B2 — the trailing toolbar button that swaps the two detail surfaces# ══════════════════════════════════════════════════════════════════════════════class TestModeToggleButton:
@pytest.mark.rb(depth=1, jump_kind="reach", expect="pressing toolbar 'terminal' makes radio 'Console' appear and the " "GUI status bar 'items,' disappear") def test_terminal_button_reaches_cli_surface(self, ax): found, enabled, help_txt = th.button_state(ax, th.TOGGLE_NAME_GUI) assert found and enabled, ( f"toolbar mode toggle {th.TOGGLE_NAME_GUI!r} not pressable: " f"found={found} enabled={enabled}") assert help_txt == th.TOGGLE_HELP_GUI, ( f"mode toggle AXHelp was {help_txt!r}, expected {th.TOGGLE_HELP_GUI!r}")
before = kit.rb_showing(ax) assert th.rb_enter_cli(ax), "pressing the 'terminal' toggle did not reach CLI mode" after = kit.rb_showing(ax) assert kit.rb_reach(before, after, target="Console", source="items,"), ( "CLI surface did not replace the GUI surface: " f"appeared={sorted(k for k in (after - before) if 'Console' in k)!r} " f"status_text now {th.status_text(ax)!r}")
assert th.pane_states(ax) == {"Console": 1, "Errors": 0}, ( f"CLI pane picker state was {th.pane_states(ax)!r}, expected " "{'Console': 1, 'Errors': 0}") th.screenshot_assert( "buttons_mode_toggle_cli", "Terminader is in Terminal mode after pressing the toolbar terminal button: a " "paste-document button, a Console/Errors segmented control with Console " "selected, a '\U0001f50d Search' field, an empty console area, and a green " "'<dir> ➜' prompt with a yellow block cursor. The icon grid, status bar and " "icon-size slider are gone; the sidebar and toolbar are still there.", RESULTS_DIR)
@pytest.mark.rb(depth=2, jump_kind="reach", expect="pressing toolbar 'Window' makes the GUI status bar 'items,' " "reappear and radio 'Console' disappear") def test_window_button_reaches_graphical_surface(self, ax): assert th.rb_enter_cli(ax), "could not reach CLI mode to press the 'Window' toggle" face = toggle_face(ax) assert face == (th.TOGGLE_NAME_CLI, th.TOGGLE_HELP_CLI), ( f"in CLI mode the toggle showed {face!r}, expected " f"{(th.TOGGLE_NAME_CLI, th.TOGGLE_HELP_CLI)!r}")
before = kit.rb_showing(ax) assert th.rb_enter_gui(ax), "pressing the 'Window' toggle did not restore GUI mode" after = kit.rb_showing(ax) assert kit.rb_reach(before, after, target="items,", source="Console"), ( "graphical surface did not replace the CLI surface: " f"status_text now {th.status_text(ax)!r}, panes {th.pane_states(ax)!r}")
assert th.icon_slider(ax) is not None, "icon-size slider missing after 'Window' press" assert STATUS_RE.match(th.status_text(ax) or ""), ( f"GUI status bar was {th.status_text(ax)!r}, expected '<n> items, … available'") assert toggle_face(ax) == (th.TOGGLE_NAME_GUI, th.TOGGLE_HELP_GUI), ( f"toggle face after returning to GUI was {toggle_face(ax)!r}")
@pytest.mark.rb(depth=1, jump_kind="transition", expect="mode toggle flips ('terminal','Switch to Terminal') -> " "('Window','Switch to graphical interface')") def test_mode_toggle_name_and_help_flip(self, ax): before = toggle_face(ax) assert before == (th.TOGGLE_NAME_GUI, th.TOGGLE_HELP_GUI), ( f"launch toggle face was {before!r}, expected " f"{(th.TOGGLE_NAME_GUI, th.TOGGLE_HELP_GUI)!r}")
assert th.rb_enter_cli(ax), "could not press the mode toggle into CLI mode" after = toggle_face(ax)
assert kit.rb_flip(before, after), ( f"mode toggle did not change identity: {before!r} -> {after!r}") assert after == (th.TOGGLE_NAME_CLI, th.TOGGLE_HELP_CLI), ( f"toggle face after the press was {after!r}, expected " f"{(th.TOGGLE_NAME_CLI, th.TOGGLE_HELP_CLI)!r}") assert not th.button_state(ax, th.TOGGLE_NAME_GUI)[0], ( f"the {th.TOGGLE_NAME_GUI!r} face still exists in CLI mode: " f"{th.button_state(ax, th.TOGGLE_NAME_GUI)!r}")
# ══════════════════════════════════════════════════════════════════════════════# B3 / B4 / B5 — the seven sidebar favourite buttons# ══════════════════════════════════════════════════════════════════════════════class TestSidebarFavouriteButtons:
@pytest.mark.rb(depth=1, jump_kind="value", expect="path picker value 'Documents ' after pressing sidebar Documents") def test_documents_button_sets_path_picker_value(self, ax): home_value = th.path_popup_value(ax) assert home_value == th.home_dir_name() + " ", ( f"launch path picker value was {home_value!r}, expected " f"{th.home_dir_name() + ' '!r}") back_before = th.button_state(ax, "Back") assert back_before[0], "toolbar 'Back' button not found" assert not back_before[1], f"'Back' was already enabled at launch: {back_before!r}"
assert rb_enter_sidebar_favourite(ax, "Documents"), ( "pressing the sidebar 'Documents' button did not navigate there; path picker " f"is {th.path_popup_value(ax)!r}")
observed = th.path_popup_value(ax) assert kit.rb_value(observed, "Documents "), ( f"path picker value was {observed!r}, expected 'Documents ' " "(trailing space is part of the value)") assert STATUS_RE.match(th.status_text(ax) or ""), ( f"status bar was not recomputed for Documents: {th.status_text(ax)!r}")
back_after = th.button_state(ax, "Back") assert kit.rb_flip(back_before[1], back_after[1]), ( f"'Back' enabled state did not flip: {back_before[1]!r} -> {back_after[1]!r}") assert back_after[2] == th.BACK_HELP, ( f"'Back' AXHelp was {back_after[2]!r}, expected {th.BACK_HELP!r}")
@pytest.mark.rb(depth=1, jump_kind="value", expect="path picker values 'Desktop ', 'Downloads ', 'Pictures ' after " "pressing each of those sidebar favourite buttons") def test_each_favourite_button_opens_its_own_directory(self, ax): wanted = ["Desktop", "Downloads", "Pictures"] observed = [] for name in wanted: assert rb_enter_sidebar_favourite(ax, name), ( f"pressing the sidebar {name!r} button did not navigate there; path picker " f"is {th.path_popup_value(ax)!r}") observed.append(th.path_popup_value(ax))
expected = [n + " " for n in wanted] assert kit.rb_value(observed, expected), ( f"path picker values after the three presses were {observed!r}, expected {expected!r}")
@pytest.mark.rb(depth=2, jump_kind="value", expect="path picker value back to '<home dir name> ' after pressing the " "home sidebar button from the rbtest fixture directory") def test_home_button_returns_to_home_directory(self, ax): assert th.rb_enter_fixtures_gui(ax), ( "could not reach the fixture directory in GUI mode; path picker is " f"{th.path_popup_value(ax)!r}") assert th.path_popup_value(ax) == th.RBTEST_NAME + " ", ( f"path picker before pressing home was {th.path_popup_value(ax)!r}, expected " f"{th.RBTEST_NAME + ' '!r}")
home = th.home_dir_name() assert rb_enter_sidebar_favourite(ax, home), ( f"pressing the sidebar home button {home!r} did not return home; path picker is " f"{th.path_popup_value(ax)!r}")
observed = th.path_popup_value(ax) assert kit.rb_value(observed, home + " "), ( f"path picker value was {observed!r}, expected {home + ' '!r}") status = th.status_text(ax) assert STATUS_RE.match(status or ""), ( f"home-directory status bar was {status!r}, expected '<n> items, … available'") sel, total = th.status_counts(ax) assert sel is None and isinstance(total, int) and total > 0, ( f"home-directory status counts were {(sel, total)!r}, expected (None, <n>0)")
# ══════════════════════════════════════════════════════════════════════════════# B6 / B7 — the toolbar Back / Forward navigation buttons# ══════════════════════════════════════════════════════════════════════════════class TestNavigationButtons:
@pytest.mark.rb(depth=2, jump_kind="value", expect="current directory reverts to the home dir name and 'Forward' " "becomes enabled after pressing 'Back'") def test_back_button_reverts_to_previous_directory(self, ax): home = th.home_dir_name() assert rb_enter_sidebar_favourite(ax, "Documents"), ( f"could not navigate to Documents first; path picker is {th.path_popup_value(ax)!r}") fwd_before = th.button_state(ax, "Forward") assert fwd_before[0], "toolbar 'Forward' button not found" assert not fwd_before[1], ( f"'Forward' was enabled before any Back press: {fwd_before!r}")
assert rb_enter_previous_directory(ax), ( "the 'Back' button was not pressable after navigating to Documents: " f"{th.button_state(ax, 'Back')!r}")
observed = th.current_dir_name(ax) assert kit.rb_value(observed, home), ( f"'Back' left the app in {observed!r}, expected the previous directory {home!r}") fwd_after = th.button_state(ax, "Forward") assert kit.rb_flip(fwd_before[1], fwd_after[1]), ( f"'Forward' enabled state did not flip after 'Back': " f"{fwd_before[1]!r} -> {fwd_after[1]!r}")
@pytest.mark.rb(depth=2, jump_kind="value", expect="current directory returns to 'Documents' and 'Forward' becomes " "disabled again after pressing 'Forward'") def test_forward_button_re_advances_to_later_directory(self, ax): assert rb_enter_sidebar_favourite(ax, "Documents"), ( f"could not navigate to Documents first; path picker is {th.path_popup_value(ax)!r}") assert rb_enter_previous_directory(ax), ( f"'Back' was not pressable: {th.button_state(ax, 'Back')!r}") assert th.current_dir_name(ax) == th.home_dir_name(), ( f"after 'Back' the directory was {th.current_dir_name(ax)!r}, expected " f"{th.home_dir_name()!r}") fwd_before = th.button_state(ax, "Forward") assert fwd_before[1], f"'Forward' was not enabled after a 'Back': {fwd_before!r}"
assert rb_enter_next_directory(ax), ( f"the 'Forward' button was not pressable: {th.button_state(ax, 'Forward')!r}")
observed = th.current_dir_name(ax) assert kit.rb_value(observed, "Documents"), ( f"'Forward' left the app in {observed!r}, expected 'Documents'") assert kit.rb_value(th.path_popup_value(ax), "Documents "), ( f"path picker value was {th.path_popup_value(ax)!r}, expected 'Documents '") fwd_after = th.button_state(ax, "Forward") assert kit.rb_flip(fwd_before[1], fwd_after[1]), ( f"'Forward' enabled state did not flip back after re-advancing: " f"{fwd_before[1]!r} -> {fwd_after[1]!r}") assert th.button_state(ax, "Back")[1], ( f"'Back' should stay enabled at the forward end of the history: " f"{th.button_state(ax, 'Back')!r}")
# ══════════════════════════════════════════════════════════════════════════════# B8 — the CLI paste button 'Next Page' (AXHelp 'Paste selected items') + its badge# ══════════════════════════════════════════════════════════════════════════════class TestPasteButton:
@pytest.mark.rb(depth=2, jump_kind="value", expect="command line contains the rbtest fixture path and ends with " "'/beta.txt' after pressing the paste button with beta.txt selected") def test_paste_button_appends_selected_file_path(self, ax): assert th.rb_enter_fixtures(ax), ( f"could not cd into the fixture directory; prompt is {th.prompt_label_value(ax)!r}") found, enabled_empty, help_txt = th.button_state(ax, th.PASTE_NAME) assert found, f"CLI paste button {th.PASTE_NAME!r} not found" assert help_txt == th.PASTE_HELP, ( f"paste button AXHelp was {help_txt!r}, expected {th.PASTE_HELP!r}") assert not enabled_empty, ( f"paste button was enabled with nothing selected: enabled={enabled_empty!r}")
assert th.rb_enter_gui(ax), "could not return to the icon grid to make a selection" target = "beta.txt" assert target in th.grid_names(ax), ( f"{target!r} missing from the fixture grid: {th.grid_names(ax)!r}") assert th.click_file(ax, target), f"could not click the grid item {target!r}" assert th.status_counts(ax) == (1, len(th.RBTEST_ENTRIES)), ( f"selection status counts were {th.status_counts(ax)!r}, expected " f"{(1, len(th.RBTEST_ENTRIES))!r}") assert th.rb_enter_cli(ax), "could not return to the CLI surface after selecting"
enabled_sel = th.button_state(ax, th.PASTE_NAME)[1] assert kit.rb_flip(enabled_empty, enabled_sel), ( f"paste button enabled state did not flip with a selection: " f"{enabled_empty!r} -> {enabled_sel!r}") assert kit.rb_value(badge_image_names(ax), "1.circle.fill"), ( f"paste button badge images were {badge_image_names(ax)!r}, expected " "a '1.circle.fill' count badge")
assert th.press_button(ax, th.PASTE_NAME), ( f"could not AXPress the paste button: {th.button_state(ax, th.PASTE_NAME)!r}") time.sleep(0.8)
line = th.command_line_text(ax) expected_path = os.path.join(th.rbtest_dir(), target) assert kit.rb_value(line, th.rbtest_dir()), ( f"command line was {line!r}, expected it to contain the fixture directory " f"{th.rbtest_dir()!r}") assert line.strip().endswith(os.sep + target), ( f"command line was {line!r}, expected it to end with {os.sep + target!r} " f"(full pasted path {expected_path!r})")
@pytest.mark.rb(depth=1, jump_kind="value", expect="paste button badge image named '3.circle.fill' after " "'select *.txt' selects the three fixture .txt files") def test_paste_button_selection_count_badge(self, ax): assert th.rb_enter_fixtures(ax), ( f"could not cd into the fixture directory; prompt is {th.prompt_label_value(ax)!r}") badges_empty = badge_image_names(ax) assert badges_empty == [], ( f"count badge present with nothing selected: {badges_empty!r}")
th.run_command(ax, "select *.txt")
badges_three = badge_image_names(ax) expected_badge = "%d.circle.fill" % len(th.RBTEST_TXT) assert kit.rb_value(badges_three, expected_badge), ( f"paste button badge images were {badges_three!r}, expected {expected_badge!r} " f"for the {len(th.RBTEST_TXT)} selected files {th.RBTEST_TXT!r}") assert kit.rb_flip(badges_empty, badges_three), ( f"badge images did not change: {badges_empty!r} -> {badges_three!r}") assert th.button_state(ax, th.PASTE_NAME)[1], ( f"paste button still disabled with 3 files selected: " f"{th.button_state(ax, th.PASTE_NAME)!r}")
th.screenshot_assert( "buttons_paste_selection_badge", "Terminader is in Terminal mode inside the rbtest fixture directory: the " "paste-document button at the top left of the console area now carries a small " "circled '3' count badge, the Console/Errors segmented control shows Console " "selected and a '\U0001f50d Search' field sits to its right. One console block " "shows the 'select *.txt' command with a green header, above the green " "'rbtest ➜' prompt with a yellow block cursor.", RESULTS_DIR)
# ══════════════════════════════════════════════════════════════════════════════# B9 — the per-console-entry pop-out button# ══════════════════════════════════════════════════════════════════════════════class TestPopOutButton:
@pytest.mark.rb(depth=2, jump_kind="reach", expect="a second window whose AXTitle == 'echo popme' after pressing the " "console entry pop-out button") def test_popout_button_opens_window_titled_after_command(self, ax): assert th.rb_enter_cli(ax), "could not reach the CLI surface" th.run_command(ax, "echo popme") assert "echo popme" in th.console_commands(ax), ( f"console entries were {th.console_commands(ax)!r}, expected 'echo popme'") titles_before = th.window_titles(ax) assert titles_before == [""], ( f"expected exactly one untitled main window before the pop-out, got " f"{titles_before!r}")
before = kit.rb_showing(ax) assert th.rb_reach_popout(ax), ( f"could not AXPress the pop-out button {th.POPOUT_NAME!r}") after = kit.rb_showing(ax)
assert kit.rb_reach(before, after, target="echo popme"), ( "no new 'echo popme' surface appeared; window titles are " f"{th.window_titles(ax)!r}") titles_after = th.window_titles(ax) assert "echo popme" in titles_after, ( f"window titles after the pop-out were {titles_after!r}, expected one titled " "'echo popme'") assert len(titles_after) == len(titles_before) + 1, ( f"window count went {titles_before!r} -> {titles_after!r}, expected exactly one more")
th.screenshot_assert( "buttons_popout_window", "A separate, smaller Terminader window titled 'echo popme' is open in front of " "the main window; it shows a relative timestamp and the command output text " "'popme'. The main window behind it is still in Terminal mode with its console " "block for 'echo popme'.", RESULTS_DIR)
@pytest.mark.rb(depth=2, jump_kind="value", expect="pop-out window title of a failing command contains an em dash " "(U+2014) and the exit status 3, e.g. 'test_out 3 — 3'") def test_popout_window_title_carries_failing_status(self, ax): assert th.rb_enter_cli(ax), "could not reach the CLI surface" th.run_command(ax, "test_out 3") assert th.rb_reach_popout(ax), ( f"could not AXPress the pop-out button {th.POPOUT_NAME!r}")
titles = [t for t in th.window_titles(ax) if t] assert titles, ( f"no titled pop-out window appeared; window titles are {th.window_titles(ax)!r}") matching = [t for t in titles if "test_out" in t] assert matching, ( f"no pop-out window title mentions the command; titles were {titles!r}") title = matching[0]
assert kit.rb_value(title, EM_DASH), ( f"pop-out title was {title!r}, expected it to contain the em dash " f"{EM_DASH!r} separating command and exit status") tail = title.split(EM_DASH)[-1].strip() assert kit.rb_value(tail, "3"), ( f"pop-out title status part was {tail!r} (full title {title!r}), expected the " "exit status '3'")
# ══════════════════════════════════════════════════════════════════════════════# B10 — the leading toolbar sidebar toggle# ══════════════════════════════════════════════════════════════════════════════class TestSidebarToggleButton:
@pytest.mark.rb(depth=1, jump_kind="reach", expect="the Sidebar outline disappears and the toolbar button is renamed " "'Show Sidebar' after pressing 'Hide Sidebar'") def test_hide_sidebar_button_removes_sidebar_surface(self, ax): found, enabled, help_txt = th.button_state(ax, "Hide Sidebar") assert found and enabled, ( f"'Hide Sidebar' toolbar button not pressable: found={found} enabled={enabled}") assert help_txt == "Hide Sidebar", ( f"'Hide Sidebar' AXHelp was {help_txt!r}, expected 'Hide Sidebar'") assert th.sidebar_outline(ax) is not None, "no Sidebar outline before hiding it"
before = kit.rb_showing(ax) assert rb_reach_hidden_sidebar(ax), "could not AXPress 'Hide Sidebar'" after = kit.rb_showing(ax)
# source is the role-qualified key so it cannot substring-match the renamed # `button|Show Sidebar` that takes the hidden sidebar's place. assert kit.rb_reach(before, after, target="Show Sidebar", source="outline|Sidebar"), ( "the sidebar surface did not go away: sidebar_outline=" f"{th.sidebar_outline(ax)!r}, buttons now include " f"{sorted(n for n in visible_button_names(ax) if 'Sidebar' in n)!r}") assert th.sidebar_outline(ax) is None, ( f"th.sidebar_outline is still {th.sidebar_outline(ax)!r} after hiding") assert th.button_state(ax, "Show Sidebar")[0:2] == (True, True), ( f"'Show Sidebar' button state was {th.button_state(ax, 'Show Sidebar')!r}, " "expected (found=True, enabled=True, …)") gone = {"Desktop", "Documents", "Pictures"} & visible_button_names(ax) assert not gone, f"sidebar favourite buttons still present after hiding: {sorted(gone)!r}"
th.screenshot_assert( "buttons_sidebar_hidden", "The sidebar is gone: no Favorites / iCloud / Locations list on the left. The " "icon grid now fills the whole window width, the status bar and icon-size slider " "are still along the bottom, and the toolbar's leftmost button shows the " "'show sidebar' icon.", RESULTS_DIR)
@pytest.mark.rb(depth=2, jump_kind="reach", expect="the Sidebar outline and all 7 favourite buttons return after " "pressing 'Show Sidebar'") def test_show_sidebar_button_restores_favourite_buttons(self, ax): assert rb_reach_hidden_sidebar(ax), "could not AXPress 'Hide Sidebar' first" assert th.sidebar_outline(ax) is None, ( f"sidebar was not hidden: {th.sidebar_outline(ax)!r}")
before = kit.rb_showing(ax) assert rb_reach_shown_sidebar(ax), ( f"could not AXPress 'Show Sidebar': {th.button_state(ax, 'Show Sidebar')!r}") after = kit.rb_showing(ax)
assert kit.rb_reach(before, after, target="outline|Sidebar", source="Show Sidebar"), ( "the sidebar surface did not come back: sidebar_outline=" f"{th.sidebar_outline(ax)!r}, sidebar buttons " f"{sorted(n for n in visible_button_names(ax) if 'Sidebar' in n)!r}") assert th.sidebar_outline(ax) is not None, ( "th.sidebar_outline is still None after pressing 'Show Sidebar'")
expected = set(th.SIDEBAR_FAVORITES) | {th.home_dir_name()} names = visible_button_names(ax) missing = expected - names assert not missing, ( f"{len(missing)} favourite button(s) did not come back: {sorted(missing)!r} " f"(buttons present: {sorted(names)!r})") assert len(expected & names) == 7, ( f"expected 7 pressable sidebar favourites, found " f"{sorted(expected & names)!r}") assert th.button_state(ax, "Hide Sidebar")[0], ( "the toolbar button did not go back to 'Hide Sidebar': " f"{sorted(n for n in names if 'Sidebar' in n)!r}")
# ══════════════════════════════════════════════════════════════════════════════# B11 — the toolbar path picker (AXPopUpButton driven by AXPress)# ══════════════════════════════════════════════════════════════════════════════class TestPathPickerButton:
@pytest.mark.rb(depth=2, jump_kind="reach", expect="path-picker menu items are the path chain 'rbtest' -> fixtures " "parent -> … -> 'Users'") def test_path_picker_button_opens_path_chain_menu(self, ax): assert th.rb_enter_fixtures_gui(ax), ( f"could not reach the fixture directory in GUI mode; path picker is " f"{th.path_popup_value(ax)!r}") picker = th.path_popup(ax) assert picker is not None, "toolbar path picker (AXPopUpButton) not found"
before = kit.rb_showing(ax) items = th.rb_reach_path_menu(ax) after = kit.rb_showing(ax)
parent = th.rbtest_parent_name() assert kit.rb_reach(before, after, target="menu_item|" + parent), ( f"no path-chain menu item for {parent!r} appeared after pressing the picker; " f"items read were {items!r}") assert items and items[0] == th.RBTEST_NAME, ( f"path menu items were {items!r}, expected the current directory " f"{th.RBTEST_NAME!r} first") assert parent in items, ( f"path menu items were {items!r}, expected the fixture parent {parent!r}") assert "Users" in items, ( f"path menu items were {items!r}, expected the chain to reach 'Users'") assert th.home_dir_name() in items, ( f"path menu items were {items!r}, expected the home directory " f"{th.home_dir_name()!r} in the chain") th.dismiss_menus(ax)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702"""COMPUTATION lane — Terminader.
Terminader's CLI surface is a REAL command engine, so this lane is a genuineinput -> output computation suite:
* input widgets : the command prompt (`th.run_command`, real key events), the console filter text field (`th.type_in_search`), the icon-size slider (`th.set_icon_slider`), grid clicks (`th.click_file`). * output widgets: the console entry output label (`th.command_output`), the console entry exit-status label, the GUI status bar (`th.status_text`/`status_counts`), the path picker (`th.current_dir_name`), the grid name labels (`th.grid_names`), the grid icon frames (`th.largest_icon_extent`), the paste-button badge image name. * modes : GUI vs CLI, and the Console vs Errors pane inside CLI.
Every expected value below is the value OBSERVED on the reference app (recon.md rowsC1-C24) or is computed here from first principles (`os.path.expanduser("~")`,`th.rbtest_dir()`, `32 + value*480`, the `history` `'%5d %s'` layout) — never read out ofthe app under test.
Portability: nothing here knows where the app is installed. The `ax` fixture launches it andhands over an AXHelper; all driving goes through the shared `terminader_helpers` module."""
from __future__ import annotations
import jsonimport osimport subprocessimport sysimport timefrom collections import Counter
import pytest
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import terminader_helpers as th # noqa: E402 shared portable driverimport rb_testgen_kit as kit # noqa: E402 depth/jump declaration kit
RESULTS_DIR = os.environ.get("RESULTS_DIR", ".")
# ── screenshot assertion (delegates to the shared driver's identical implementation) ──def screenshot_assert(test_name, description, results_dir): """Capture the screen and record a VLM assertion describing what it must show.""" try: th.screenshot_assert(test_name, description, results_dir) return except Exception: pass ss_dir = os.path.join(results_dir, "screenshots") os.makedirs(ss_dir, exist_ok=True) ss_path = os.path.join(ss_dir, f"{test_name}.png") try: subprocess.run(["screencapture", "-x", ss_path], timeout=5) except Exception: pass assertions_file = os.path.join(ss_dir, "assertions.json") assertions = {} if os.path.exists(assertions_file): try: with open(assertions_file) as f: assertions = json.load(f) except Exception: assertions = {} assertions[f"{test_name}.png"] = description with open(assertions_file, "w") as f: json.dump(assertions, f, indent=2)
# ── tier-3 value verdicts (kit wrappers — rb_value* prefix keeps rb_audit_tier happy) ──def rb_value_exact(observed, expected): """VALUE verdict that is exact apart from surrounding whitespace.
`kit.rb_value` is deliberately tolerant (substring); for a computed answer such as a path, an exit status or a shell message we want the whole string, so the kit verdict is AND-ed with a stripped equality check.""" ok = kit.rb_value(observed, expected) if not ok: return False return str(observed).strip() == str(expected).strip()
def rb_value_close(observed, expected, tol=0.6): """VALUE verdict for a measured geometry number (icon extent in points).""" if observed is None: return False try: near = abs(float(observed) - float(expected)) <= float(tol) except (TypeError, ValueError): return False return near and kit.rb_value(round(float(observed)), round(float(expected)))
# ── small read-only helpers (no navigation — they must never back a depth claim) ──def _ensure_frontmost(ax): """Terminader is a regular (non-LSUIElement) app: recon records REVEAL_STEPS = none, the main window is on screen immediately after launch. So there is no reveal path to guess — we only make the app frontmost by pid so synthetic key events land in it.""" try: th.activate(ax) except Exception: pass
def _entry_status(ax, command): """The exit-status label of the newest console entry for `command`, or None.
A console entry renders as: prompt, command, relative-date, [status], output. The status label is the first digit-only text right after the command label (the relative-date label such as '3 sec' is never digit-only, and it is skipped).""" texts = th.all_texts(ax) for i in range(len(texts) - 1, -1, -1): if texts[i] == command: for j in range(i + 1, min(i + 5, len(texts))): t = str(texts[j]).strip() if t.isdigit(): return t return None return None
def _paste_badge_name(ax): """AXDescription of the selection badge drawn on the CLI paste button ('3.circle.fill' while three files are selected), or None when no badge is present.""" for el in ax.find(role="image", max_results=60, max_depth=24): name = str(el.name or "") if name.endswith(".circle.fill"): return name return None
def _candidates_message(names): """The exact 'select'/'deselect' candidate listing observed on the reference.""" return "Candidates:\n" + "\n".join(names)
def _history_line(index, command): """The `history` layout observed on the reference: index right-aligned to width 5, then two spaces, then the command (' 0 pwd').""" return "{:>5} {}".format(index, command)
# ══════════════════════════════════════════════════════════════════════════════════# C1-C6, C24 — the shell command engine# ══════════════════════════════════════════════════════════════════════════════════class TestCLIShellCommands:
@pytest.mark.rb(depth=1, jump_kind="value", expect="`pwd` in the CLI prints the user's home directory path") def test_pwd_prints_home_directory(self, ax): """C1: fresh launch starts in the home directory, so `pwd` computes it.""" _ensure_frontmost(ax) assert th.rb_enter_cli(ax), "could not switch to the CLI (Terminal) surface" th.run_command(ax, "pwd") observed = th.command_output(ax, "pwd") expected = os.path.expanduser("~") assert rb_value_exact(observed, expected), ( f"`pwd` printed {observed!r}, expected the home directory {expected!r}")
@pytest.mark.rb(depth=2, jump_kind="value", expect="`pwd` after cd prints the rbtest fixture directory path") def test_pwd_prints_fixture_directory(self, ax): """C2: `cd <fixtures>/rbtest` then `pwd` prints that absolute path.""" _ensure_frontmost(ax) assert th.rb_enter_fixtures(ax), ( "could not cd into the fixture directory " + th.rbtest_dir()) th.run_command(ax, "pwd") observed = th.command_output(ax, "pwd") expected = th.rbtest_dir() assert rb_value_exact(observed, expected), ( f"`pwd` printed {observed!r}, expected the fixture directory {expected!r}")
@pytest.mark.rb(depth=1, jump_kind="value", expect="`echo hello-terminader` -> 'hello-terminader'; " "`echo smoke-value` -> 'smoke-value'") def test_echo_literals_verbatim(self, ax): """C3 + C4: any literal is echoed back verbatim, one console block each.""" _ensure_frontmost(ax) assert th.rb_enter_cli(ax), "could not switch to the CLI (Terminal) surface" th.run_command(ax, "echo hello-terminader") first = th.command_output(ax, "echo hello-terminader") assert rb_value_exact(first, "hello-terminader"), ( f"`echo hello-terminader` printed {first!r}, expected 'hello-terminader'") th.run_command(ax, "echo smoke-value") second = th.command_output(ax, "echo smoke-value") assert rb_value_exact(second, "smoke-value"), ( f"`echo smoke-value` printed {second!r}, expected 'smoke-value'") screenshot_assert( "computation_echo_command_results", "Terminader is in CLI/Terminal mode with two stacked console blocks, each " "carrying a green header of the form '<dir> % <command>' with a relative time " "on its right: the first block's command is 'echo hello-terminader' and its " "monospace output line below reads 'hello-terminader'; the second block's " "command is 'echo smoke-value' and its output reads 'smoke-value'. A " "Console/Errors segmented control (Console selected) and a '\U0001f50d Search' " "field sit above the blocks, and a green '<dir> ➜' prompt with a yellow " "block cursor sits below them.", RESULTS_DIR)
@pytest.mark.rb(depth=1, jump_kind="value", expect="`history` after one command prints ' 0 pwd'") def test_history_lists_previous_command(self, ax): """C5: index right-aligned to width 5, two spaces, then the command.""" _ensure_frontmost(ax) assert th.rb_enter_cli(ax), "could not switch to the CLI (Terminal) surface" th.run_command(ax, "pwd") th.run_command(ax, "history") observed = th.command_output(ax, "history") expected = _history_line(0, "pwd") assert rb_value_exact(observed, expected), ( f"`history` printed {observed!r}, expected {expected!r} " "(index right-aligned to width 5 + two spaces + the command)")
@pytest.mark.rb(depth=1, jump_kind="value", expect="`history` with no earlier command prints 'no history' " "and the entry's status label is '1'") def test_history_with_no_prior_command_reports_no_history(self, ax): """C24: the empty-history message plus its non-zero exit status.""" _ensure_frontmost(ax) assert th.rb_enter_cli(ax), "could not switch to the CLI (Terminal) surface" th.run_command(ax, "history") observed = th.command_output(ax, "history") assert rb_value_exact(observed, "no history"), ( f"`history` on a fresh session printed {observed!r}, expected 'no history'") status = _entry_status(ax, "history") assert rb_value_exact(status, "1"), ( f"the 'history' console entry showed exit status {status!r}, expected '1'")
@pytest.mark.rb(depth=1, jump_kind="value", expect="unknown command -> 'zsh:1: command not found: " "nosuchcommandxyz' with status label '127'") def test_unknown_command_reports_not_found_and_status_127(self, ax): """C6: the error text AND the 127 exit status are both computed by the engine.""" _ensure_frontmost(ax) assert th.rb_enter_cli(ax), "could not switch to the CLI (Terminal) surface" th.run_command(ax, "nosuchcommandxyz") observed = th.command_output(ax, "nosuchcommandxyz") expected = "zsh:1: command not found: nosuchcommandxyz" assert rb_value_exact(observed, expected), ( f"unknown command printed {observed!r}, expected {expected!r}") status = _entry_status(ax, "nosuchcommandxyz") assert rb_value_exact(status, "127"), ( f"the failing console entry showed exit status {status!r}, expected '127'") screenshot_assert( "computation_failed_command_status", "Terminader's console shows a single command block whose header is RED (not " "green), reading '<dir> % nosuchcommandxyz' with a '↳ 127' exit status on " "the right-hand side of that header; the monospace body underneath reads " "'zsh:1: command not found: nosuchcommandxyz'.", RESULTS_DIR)
# ══════════════════════════════════════════════════════════════════════════════════# C7 — stdout / stderr routing and the exit status, across the two CLI panes# ══════════════════════════════════════════════════════════════════════════════════class TestExitStatusAndPanes:
@pytest.mark.rb(depth=1, jump_kind="value", expect="`test_out 3` Console output starts with 'This is stdout' and " "the entry's status label is '3'") def test_test_out_stdout_and_exit_status_three(self, ax): """C7 (Console half): stdout lands in the Console pane, status echoes the argument.""" _ensure_frontmost(ax) assert th.rb_enter_cli(ax), "could not switch to the CLI (Terminal) surface" th.run_command(ax, "test_out 3") observed = th.command_output(ax, "test_out 3") assert kit.rb_value(observed, "This is stdout"), ( f"Console output for `test_out 3` was {observed!r}, expected it to start with " "'This is stdout'") status = _entry_status(ax, "test_out 3") assert rb_value_exact(status, "3"), ( f"`test_out 3` console entry showed exit status {status!r}, expected '3'")
@pytest.mark.rb(depth=2, jump_kind="value", expect="Errors pane output for `test_out 3` is exactly 'This is stderr'") def test_test_out_errors_pane_shows_stderr(self, ax): """C7 (Errors half): switching pane recomputes which stream is displayed.""" _ensure_frontmost(ax) assert th.rb_enter_cli(ax), "could not switch to the CLI (Terminal) surface" th.run_command(ax, "test_out 3") assert th.rb_enter_pane(ax, "Errors"), "could not select the Errors pane" panes = th.pane_states(ax) assert panes.get("Errors") == 1 and panes.get("Console") == 0, ( f"pane states after selecting Errors were {panes!r}, expected " "{'Console': 0, 'Errors': 1}") observed = th.command_output(ax, "test_out 3") assert rb_value_exact(observed, "This is stderr"), ( f"Errors pane output for `test_out 3` was {observed!r}, expected " "'This is stderr'") screenshot_assert( "computation_errors_pane_stderr", "Terminader is in CLI/Terminal mode with the 'Errors' segment of the " "Console/Errors segmented control selected (highlighted) instead of 'Console'. " "A single command block for 'test_out 3' is shown and its body text is exactly " "'This is stderr' — the 'This is stdout' text is not visible.", RESULTS_DIR)
# ══════════════════════════════════════════════════════════════════════════════════# C8-C10 — commands whose output is computed from the fixture files# ══════════════════════════════════════════════════════════════════════════════════class TestFileContentCommands:
@pytest.mark.rb(depth=2, jump_kind="value", expect="`cat alpha.txt` -> 'alpha-content-line1 alpha-content-line2'") def test_cat_alpha_txt_joins_two_lines(self, ax): """C8: the two file lines render as one markdown paragraph.""" _ensure_frontmost(ax) assert th.rb_enter_fixtures(ax), ( "could not cd into the fixture directory " + th.rbtest_dir()) th.run_command(ax, "cat alpha.txt") observed = th.command_output(ax, "cat alpha.txt") assert rb_value_exact(observed, th.ALPHA_TEXT_JOINED), ( f"`cat alpha.txt` printed {observed!r}, expected {th.ALPHA_TEXT_JOINED!r}")
@pytest.mark.rb(depth=2, jump_kind="value", expect="`cat readme.md` renders 'Heading One' + " "'Some markdown body text.'") def test_cat_readme_renders_markdown(self, ax): """C9: markdown MIME output is RENDERED, so the '#' source never appears.""" _ensure_frontmost(ax) assert th.rb_enter_fixtures(ax), ( "could not cd into the fixture directory " + th.rbtest_dir()) th.run_command(ax, "cat readme.md") texts = th.all_texts(ax) expected = [th.README_HEADING, th.README_BODY] observed = [t for t in expected if t in texts] assert rb_value_exact(observed, expected), ( f"rendered markdown texts were {observed!r}, expected {expected!r}; " f"all texts = {texts[:40]!r}") screenshot_assert( "computation_markdown_file_render", "Terminader's console shows the output of 'cat readme.md' rendered as real " "markdown: a large bold title 'Heading One' above the sentence 'Some markdown " "body text.' with the single word 'markdown' in italics. The raw source " "('# Heading One' with a hash, or asterisks around markdown) is NOT shown.", RESULTS_DIR)
@pytest.mark.rb(depth=2, jump_kind="value", expect="`ls` renders a 7-column markdown table listing the 5 fixture " "entries with the directory as 'subdir/'") def test_ls_renders_markdown_table(self, ax): """C10: `ls` output is computed into a markdown table (headers + one row/entry).""" _ensure_frontmost(ax) assert th.rb_enter_fixtures(ax), ( "could not cd into the fixture directory " + th.rbtest_dir()) th.run_command(ax, "ls", wait=3.2) texts = th.all_texts(ax) headers = [h for h in th.LS_TABLE_HEADERS if h in texts] assert rb_value_exact(headers, th.LS_TABLE_HEADERS), ( f"`ls` table headers present were {headers!r}, expected " f"{th.LS_TABLE_HEADERS!r}; all texts = {texts[:60]!r}") expected_names = list(th.RBTEST_FILES) + [d + "/" for d in th.RBTEST_DIRS] names = [n for n in expected_names if n in texts] assert rb_value_exact(names, expected_names), ( f"`ls` listed {names!r}, expected {expected_names!r} (directories are " f"rendered with a trailing slash); all texts = {texts[:60]!r}") screenshot_assert( "computation_ls_markdown_table", "Terminader's console shows the output of 'ls' in the rbtest fixture directory " "as a rendered markdown table with visible borders: the header row reads " "Permissions / Links / Owner / Group / Size / Date / Name, and there is one " "row per fixture entry — alpha.txt, beta.txt, gamma.txt, readme.md and " "subdir/ — with the file names drawn as underlined links.", RESULTS_DIR)
# ══════════════════════════════════════════════════════════════════════════════════# C11-C14 — the internal select / deselect commands and their four exact messages# ═════════════════════════════════════════════════════════════════════════��════════class TestSelectionCommands:
@pytest.mark.rb(depth=2, jump_kind="value", expect="`select` with no args lists all 5 fixture entries after " "'Candidates:'") def test_select_without_args_lists_all_candidates(self, ax): """C11: the candidate list is computed from the not-yet-selected entries.""" _ensure_frontmost(ax) assert th.rb_enter_fixtures(ax), ( "could not cd into the fixture directory " + th.rbtest_dir()) th.run_command(ax, "select") observed = th.command_output(ax, "select") expected = _candidates_message(th.RBTEST_ENTRIES) assert rb_value_exact(observed, expected), ( f"`select` printed {observed!r}, expected {expected!r}")
@pytest.mark.rb(depth=2, jump_kind="value", expect="`select *.txt` badges the paste button '3.circle.fill' and " "`deselect` then lists only the 3 .txt files") def test_select_txt_glob_badge_and_deselect_candidates(self, ax): """C12: the glob selects exactly 3 files — read back twice, from the paste-button badge image name and from the `deselect` candidate list.""" _ensure_frontmost(ax) assert th.rb_enter_fixtures(ax), ( "could not cd into the fixture directory " + th.rbtest_dir()) th.run_command(ax, "select *.txt") badge = _paste_badge_name(ax) expected_badge = "{}.circle.fill".format(len(th.RBTEST_TXT)) assert rb_value_exact(badge, expected_badge), ( f"paste-button badge image was {badge!r} after `select *.txt`, expected " f"{expected_badge!r}") th.run_command(ax, "deselect") observed = th.command_output(ax, "deselect") expected = _candidates_message(th.RBTEST_TXT) assert rb_value_exact(observed, expected), ( f"`deselect` printed {observed!r}, expected {expected!r}")
@pytest.mark.rb(depth=2, jump_kind="value", expect="`select *` then `select` -> 'All items already selected.'") def test_select_all_then_select_reports_already_selected(self, ax): """C13: with an empty candidate set the engine computes a different message.""" _ensure_frontmost(ax) assert th.rb_enter_fixtures(ax), ( "could not cd into the fixture directory " + th.rbtest_dir()) th.run_command(ax, "select *") th.run_command(ax, "select") observed = th.command_output(ax, "select") assert rb_value_exact(observed, "All items already selected."), ( f"`select` after `select *` printed {observed!r}, expected " "'All items already selected.'")
@pytest.mark.rb(depth=1, jump_kind="value", expect="`deselect` with an empty selection -> 'No items selected.'") def test_deselect_without_selection_reports_none(self, ax): """C14: the fresh-launch selection is empty, so `deselect` has nothing to offer.""" _ensure_frontmost(ax) assert th.rb_enter_cli(ax), "could not switch to the CLI (Terminal) surface" th.run_command(ax, "deselect") observed = th.command_output(ax, "deselect") assert rb_value_exact(observed, "No items selected."), ( f"`deselect` on a fresh session printed {observed!r}, expected " "'No items selected.'")
# ══════════════════════════════════════════════════════════════════════════════════# C15-C19 — values the GUI surface computes: grid, status bar, icon geometry# ══════════════════════════════════════════════════════════════════════════════════class TestGuiGridComputation:
@pytest.mark.rb(depth=2, jump_kind="value", expect="fixture grid lists the 5 rbtest entries and the status bar " "reads '5 items, … available'") def test_fixture_grid_names_and_status_counts(self, ax): """C15 + C16: the grid labels and the status-bar count are both derived from the fixture directory listing (never the home dir, whose count is not deterministic).""" _ensure_frontmost(ax) assert th.rb_enter_fixtures_gui(ax), ( "could not reach the graphical grid of " + th.rbtest_dir()) names = th.grid_names(ax) assert rb_value_exact(names, list(th.RBTEST_ENTRIES)), ( f"grid names were {names!r}, expected {list(th.RBTEST_ENTRIES)!r}") counts = th.status_counts(ax) expected_counts = (None, len(th.RBTEST_ENTRIES)) assert rb_value_exact(counts, expected_counts), ( f"status counts were {counts!r}, expected {expected_counts!r}") status = th.status_text(ax) prefix = "{} items,".format(len(th.RBTEST_ENTRIES)) assert status.startswith(prefix) and status.endswith(" available"), ( f"status bar read {status!r}, expected it to start with {prefix!r} and end " "with ' available'")
@pytest.mark.rb(depth=2, jump_kind="value", expect="fixture grid icons split 4 'Document' + 1 'Move'") def test_fixture_icon_roles_split_by_type(self, ax): """C17: one icon per entry, the symbol chosen by file-vs-directory.""" _ensure_frontmost(ax) assert th.rb_enter_fixtures_gui(ax), ( "could not reach the graphical grid of " + th.rbtest_dir()) tally = Counter(str(e.name) for e in th.grid_icons(ax)) observed = (tally.get(th.FILE_ICON_NAME, 0), tally.get(th.FOLDER_ICON_NAME, 0)) expected = (len(th.RBTEST_FILES), len(th.RBTEST_DIRS)) assert rb_value_exact(observed, expected), ( f"(#{th.FILE_ICON_NAME}, #{th.FOLDER_ICON_NAME}) icons were {observed!r}, " f"expected {expected!r}; full tally = {dict(tally)!r}")
@pytest.mark.rb(depth=3, jump_kind="value", expect="subdir grid lists only 'nested.txt' and the status bar reads " "'1 item, …' (singular)") def test_subdir_shows_single_nested_file_singular_status(self, ax): """C18: descending recomputes both the listing and the singular/plural word.""" _ensure_frontmost(ax) assert th.rb_enter_fixtures_gui(ax), ( "could not reach the graphical grid of " + th.rbtest_dir()) assert th.rb_enter_directory(ax, th.RBTEST_DIRS[0]), ( "could not descend into the '%s' folder" % th.RBTEST_DIRS[0]) names = th.grid_names(ax) assert rb_value_exact(names, ["nested.txt"]), ( f"grid names inside subdir were {names!r}, expected ['nested.txt']") status = th.status_text(ax) assert kit.rb_value(status, "1 item,") and status.startswith("1 item,"), ( f"status bar inside subdir read {status!r}, expected it to start with " "'1 item,' (singular)")
@pytest.mark.rb(depth=2, jump_kind="value", expect="icon extent == 32 + slider*480 -> 272.0 pt at 0.5 and " "152.0 pt at 0.25") def test_icon_slider_extent_is_linear(self, ax): """C19: the icon-size slider is a real linear computation; the expected point size is computed here (32 + value*480) and compared with the measured icon frame.""" _ensure_frontmost(ax) assert th.rb_enter_fixtures_gui(ax), ( "could not reach the graphical grid of " + th.rbtest_dir())
assert th.set_icon_slider(ax, 0.5), "could not set the icon-size slider to 0.5" value = th.icon_slider_value(ax) assert rb_value_close(value, 0.5, tol=0.01), ( f"icon slider AXValue was {value!r} after setting 0.5") extent = th.largest_icon_extent(ax) expected = 32.0 + 0.5 * 480.0 assert rb_value_close(extent, expected), ( f"largest icon extent was {extent!r} at slider 0.5, expected {expected!r} " "(32 + 0.5*480)") screenshot_assert( "computation_large_icons", "Terminader shows the rbtest fixture directory as an icon grid drawn with very " "LARGE icons (about 272 points): four big grey document icons labelled " "alpha.txt, beta.txt, gamma.txt and readme.md plus one big cyan folder icon " "labelled subdir. The icon-size slider at the bottom right has its knob near " "the middle of its track and the status bar reads '5 items, … available'.", RESULTS_DIR)
assert th.set_icon_slider(ax, 0.25), "could not set the icon-size slider to 0.25" extent = th.largest_icon_extent(ax) expected = 32.0 + 0.25 * 480.0 assert rb_value_close(extent, expected), ( f"largest icon extent was {extent!r} at slider 0.25, expected {expected!r} " "(32 + 0.25*480)")
# ══════════════════════════════════════════════════════════════════════════════════# C20-C21 — the console filter and the paste button (selection -> command line)# ══════════════════════════════════════════════════════════════════════════════════class TestFilterAndPaste:
@pytest.mark.rb(depth=1, jump_kind="value", expect="typing 'pwd' in the console filter narrows the entries from " "['echo aaa','pwd'] to ['pwd']") def test_console_filter_narrows_to_matching_command(self, ax): """C20: the filter computes which console entries stay displayed.""" _ensure_frontmost(ax) assert th.rb_enter_cli(ax), "could not switch to the CLI (Terminal) surface" th.run_command(ax, "echo aaa") th.run_command(ax, "pwd") before = th.console_commands(ax) assert set(before) == {"echo aaa", "pwd"}, ( f"console listed {before!r} before filtering, expected 'echo aaa' and 'pwd'") assert th.type_in_search(ax, "pwd"), "could not type into the console filter field" after = th.console_commands(ax) assert rb_value_exact(after, ["pwd"]), ( f"console listed {after!r} after filtering on 'pwd', expected ['pwd'] " f"(was {before!r})")
@pytest.mark.rb(depth=1, jump_kind="value", expect="filtering on 'CANDIDATES' keeps only the 'select' entry, whose " "OUTPUT (not its command) carries the word, proving the filter " "matches output text case-insensitively") def test_console_filter_matches_output_text_case_insensitively(self, ax): """C20 (second angle): the filter is computed over the entry's command AND its output text, case-insensitively. 'Candidates:' appears only in `select`'s OUTPUT, and is typed here in upper case, so a command-only or case-sensitive filter would drop the entry.""" _ensure_frontmost(ax) assert th.rb_enter_fixtures(ax), ( "could not cd into the fixture directory " + th.rbtest_dir()) th.run_command(ax, "echo beacon") th.run_command(ax, "select") before = th.console_commands(ax) assert set(before) == {"echo beacon", "select"}, ( f"console listed {before!r} before filtering, expected 'echo beacon' and 'select'") assert th.type_in_search(ax, "CANDIDATES"), ( "could not type into the console filter field") after = th.console_commands(ax) assert rb_value_exact(after, ["select"]), ( f"console listed {after!r} after filtering on 'CANDIDATES', expected " f"['select'] — the word only occurs in that entry's output (was {before!r})")
@pytest.mark.rb(depth=1, jump_kind="value", expect="`cd /no/such/dir/zzz` leaves the directory at 'rbtest' and adds " "no console entry") def test_cd_to_missing_directory_is_a_noop(self, ax): """Edge case: `cd` validates its destination — a non-existent path changes nothing and, like every `cd`, produces no console entry of its own.""" _ensure_frontmost(ax) assert th.rb_enter_fixtures(ax), ( "could not cd into the fixture directory " + th.rbtest_dir()) th.run_command(ax, "pwd") entries_before = th.console_commands(ax) assert rb_value_exact(entries_before, ["pwd"]), ( f"console listed {entries_before!r} before the bad cd, expected ['pwd']") th.run_command(ax, "cd /no/such/dir/zzz", wait=2.0) assert rb_value_exact(th.current_dir_name(ax), th.RBTEST_NAME), ( f"a cd to a missing path moved the directory to " f"{th.current_dir_name(ax)!r}, expected it to stay {th.RBTEST_NAME!r}") entries_after = th.console_commands(ax) assert rb_value_exact(entries_after, ["pwd"]), ( f"console listed {entries_after!r} after the bad cd, expected the unchanged " f"['pwd'] — cd must not add an entry")
@pytest.mark.rb(depth=1, jump_kind="value", expect="a bare Return on an empty command line leaves the console at " "one entry ('pwd')") def test_empty_command_adds_no_console_entry(self, ax): """Edge case: submitting an empty command is ignored — the entry count is unchanged and the command line returns to the bare block cursor.""" _ensure_frontmost(ax) assert th.rb_enter_cli(ax), "could not switch to the CLI (Terminal) surface" th.run_command(ax, "pwd") before = th.console_commands(ax) assert rb_value_exact(before, ["pwd"]), ( f"console listed {before!r} before the empty Return, expected ['pwd']") th.activate(ax) th.cg_key(th.KC_RETURN) time.sleep(1.5) after = th.console_commands(ax) assert rb_value_exact(after, ["pwd"]), ( f"console listed {after!r} after a bare Return, expected the unchanged " f"['pwd'] — an empty command must be ignored") assert rb_value_exact(th.command_line_text(ax), " "), ( f"command line held {th.command_line_text(ax)!r} after a bare Return, " "expected the single-space block cursor")
@pytest.mark.rb(depth=2, jump_kind="value", expect="paste button inserts '<rbtest>/beta.txt' into the command line") def test_paste_button_inserts_selected_absolute_path(self, ax): """C21: the paste button computes the selected file's absolute path and appends it to the command line.""" _ensure_frontmost(ax) assert th.rb_enter_fixtures_gui(ax), ( "could not reach the graphical grid of " + th.rbtest_dir()) assert th.click_file(ax, "beta.txt"), "could not click the beta.txt grid item" assert th.rb_enter_cli(ax), "could not switch to the CLI (Terminal) surface" found, enabled, help_txt = th.button_state(ax, th.PASTE_NAME) assert found and enabled, ( f"paste button state with one file selected was found={found} " f"enabled={enabled} help={help_txt!r}, expected found+enabled") assert th.press_button(ax, th.PASTE_NAME), "could not press the paste button" expected = os.path.join(th.rbtest_dir(), "beta.txt") # the command line is re-rendered asynchronously, so give it a moment to settle typed = "" deadline = time.time() + 4.0 while time.time() < deadline: typed = th.command_line_text(ax) if expected in typed: break time.sleep(0.3) assert kit.rb_value(typed, expected), ( f"command line held {typed!r} after pressing paste, expected it to contain " f"the absolute path {expected!r}") assert typed.strip().endswith(os.sep + "beta.txt"), ( f"command line {typed!r} does not end with {os.sep + 'beta.txt'!r}")
# ══════════════════════════════════════════════════════════════════════════════════# C22-C23 — path arithmetic: navigation history vs relative cd# ══════════════════════════════════════════════════════════════════════════════════class TestDirectoryNavigationComputation:
@pytest.mark.rb(depth=2, jump_kind="value", expect="`pwd b` prints the home directory (navigation history, not the " "parent) and `pwd f` prints the fixture directory again") def test_pwd_back_and_forward_walk_navigation_history(self, ax): """C22: history is [home, rbtest], so `pwd b` computes home — NOT the fixtures parent directory — and `pwd f` returns to rbtest.""" _ensure_frontmost(ax) assert th.rb_enter_fixtures(ax), ( "could not cd into the fixture directory " + th.rbtest_dir()) th.run_command(ax, "pwd b") back_out = th.command_output(ax, "pwd b") home = os.path.expanduser("~") assert rb_value_exact(back_out, home), ( f"`pwd b` printed {back_out!r}, expected the previously visited directory " f"{home!r} (navigation history, not the parent of {th.rbtest_dir()!r})") assert rb_value_exact(th.current_dir_name(ax), th.home_dir_name()), ( f"after `pwd b` the path picker showed {th.current_dir_name(ax)!r}, expected " f"{th.home_dir_name()!r}") th.run_command(ax, "pwd f") fwd_out = th.command_output(ax, "pwd f") assert rb_value_exact(fwd_out, th.rbtest_dir()), ( f"`pwd f` printed {fwd_out!r}, expected {th.rbtest_dir()!r}") assert rb_value_exact(th.current_dir_name(ax), th.RBTEST_NAME), ( f"after `pwd f` the path picker showed {th.current_dir_name(ax)!r}, expected " f"{th.RBTEST_NAME!r}")
@pytest.mark.rb(depth=3, jump_kind="value", expect="relative `cd subdir` then `pwd` prints '<rbtest>/subdir'") def test_relative_cd_subdir_then_pwd(self, ax): """C23: a relative path is resolved against the current directory.""" _ensure_frontmost(ax) assert th.rb_enter_fixtures(ax), ( "could not cd into the fixture directory " + th.rbtest_dir()) th.run_command(ax, "cd " + th.RBTEST_DIRS[0], wait=1.8) observed_dir = th.current_dir_name(ax) assert rb_value_exact(observed_dir, th.RBTEST_DIRS[0]), ( f"path picker showed {observed_dir!r} after relative `cd " f"{th.RBTEST_DIRS[0]}`, expected {th.RBTEST_DIRS[0]!r}") th.run_command(ax, "pwd") observed = th.command_output(ax, "pwd") expected = os.path.join(th.rbtest_dir(), th.RBTEST_DIRS[0]) assert rb_value_exact(observed, expected), ( f"`pwd` printed {observed!r}, expected {expected!r}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409"""test_ax_menus.py — MENUS lane for Terminader (Finder <-> Terminal hybrid file browser).
Every expectation below is a fact OBSERVED on the reference app and recorded inrecon.md (`## MENUS`, `## AX_TREE`, `## VISUAL`). Nothing here knows where the app isinstalled: the `ax` / `ax_with_reset` fixtures from conftest.py hand each test anAXHelper bound to the freshly launched process, and all driving goes through the shared`terminader_helpers` module, so the SAME file scores the reference and a recreation.
Locators are semantic only (AXRole + visible AXTitle/AXDescription, or a named parentcontainer via `root_id`) — never a child index, tree path or internal identifier.
NEVER activated here (names are only READ): Quit Terminader, Quit and Keep Windows,Close, Close All, Minimize*, Zoom*, Tile/Move Window*, Enter Full Screen, Delete,Start Dictation…, Emoji & Symbols, Hide Terminader, Hide Others, Show All, Services,About Terminader, and every Apple-menu item."""
import osimport sysimport time
import pytest
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import terminader_helpers as th # noqa: E402 shared portable driverimport rb_testgen_kit as kit # noqa: E402 depth / jump verdicts
RESULTS_DIR = os.environ.get("RESULTS_DIR", ".")
# ── menu contents observed on the reference (recon ## MENUS) ───────────────────# macOS injects ALTERNATE items whose presence varies between launches# ('Quit and Keep Windows', 'Enter Full Screen', 'Tile Window to …'), so every menu is# asserted as a required SUBSET (+ a length sanity bound), never as exact equality.APP_MENUS = ["Terminader", "File", "Edit", "View", "Window", "Help"]
TERMINADER_ITEMS = ["About Terminader", "Services", "Hide Terminader", "Hide Others", "Show All", "Quit Terminader"]FILE_ITEMS = ["New Window", "Close", "Close All"]EDIT_ITEMS = ["Undo", "Redo", "Cut", "Copy", "Paste", "Delete", "Select All", "AutoFill", "Start Dictation…", "Emoji & Symbols"]VIEW_ITEMS = ["Show Tab Bar", "Show All Tabs"]WINDOW_ITEMS = ["Minimize", "Minimize All", "Zoom", "Zoom All", "Move Window to Left Side of Screen", "Move Window to Right Side of Screen", "Replace Tiled Window", "Remove Window from Set", "Show Previous Tab", "Show Next Tab", "Move Tab to New Window", "Merge All Windows", "Bring All to Front", "Arrange in Front"]HELP_ITEMS = ["Terminader Help"]AUTOFILL_ITEMS = ["Contact…", "Passwords…"]
CONTEXT_ITEMS = ["Get Info", "Open"] # sorted; observed order ['Open','Get Info']NESTED_ENTRIES = ["nested.txt"] # contents of <fixtures>/rbtest/subdir
# ── lane-local navigation helper (named rb_reach_* so the depth audit sees it) ──def rb_reach_open_menu_item(ax, item_name, settle=1.8): """Activate an item of an ALREADY-OPEN pop-up menu (a grid context menu / the toolbar path menu) by its VISIBLE NAME — semantic locator `role=menu_item` + AXTitle, never a child index. Returns True when the AXPress landed.
Split out of `th.rb_reach_get_info` on purpose: the reach verdict needs the `rb_showing` snapshot taken while the context menu is still up, so that the SOURCE surface ('Get Info' / 'Open' menu item) can be proven to DISAPPEAR afterwards. """ for el in ax.find(role="menu_item", name=item_name, max_results=4, max_depth=8): if ax.action(el.id, "AXPress"): time.sleep(settle) return True return False
def _expected_path_chain(): """Component names of the fixture directory's path — current directory first, up to 'Users' — computed from the live fixture path so no absolute path is hardcoded.""" out = [] p = th.rbtest_dir().rstrip(os.sep) while True: base = os.path.basename(p) if not base: break out.append(base) if base == "Users": break parent = os.path.dirname(p) if parent == p: break p = parent return out
class TestMenuBarShape: """The menu-bar node itself: which menus the app publishes."""
@pytest.mark.rb(depth=0, jump_kind="none", expect="menu bar carries the system 'Apple' menu plus exactly the app " "menus Terminader, File, Edit, View, Window, Help") def test_menu_bar_titles(self, ax): titles = th.menu_bar_titles(ax) assert titles, "the app published no AXMenuBarItem titles at all (menu bar empty)" assert "Apple" in titles, f"system 'Apple' menu missing; menu bar titles = {titles}" app_menus = [t for t in titles if t != "Apple"] assert app_menus == APP_MENUS, ( f"app menus = {app_menus}, expected {APP_MENUS} " f"(full menu bar = {titles})")
class TestMenuContents: """One test per app menu: open it for real and read back its item names."""
@pytest.mark.rb(depth=1, jump_kind="value", expect="opened 'Terminader' menu lists About Terminader, Services, " "Hide Terminader, Hide Others, Show All, Quit Terminader") def test_terminader_menu_items(self, ax_with_reset): ax = ax_with_reset items = th.rb_enter_menu(ax, "Terminader") # real AXPress -> menu surface th.dismiss_menus(ax) joined = " | ".join(items) missing = [r for r in TERMINADER_ITEMS if not kit.rb_value(joined, r)] assert not missing, ( f"'Terminader' menu is missing {missing}; observed items = {items}") assert set(TERMINADER_ITEMS) <= set(items), ( f"'Terminader' menu items = {items}, required subset {TERMINADER_ITEMS}") assert len(items) <= len(TERMINADER_ITEMS) + 3, ( f"'Terminader' menu has {len(items)} items, expected at most " f"{len(TERMINADER_ITEMS) + 3}: {items}")
@pytest.mark.rb(depth=1, jump_kind="value", expect="opened 'File' menu lists exactly ['New Window','Close','Close All']") def test_file_menu_items(self, ax_with_reset): ax = ax_with_reset items = th.rb_enter_menu(ax, "File") # real AXPress -> menu surface th.dismiss_menus(ax) joined = " | ".join(items) missing = [r for r in FILE_ITEMS if not kit.rb_value(joined, r)] assert not missing, f"'File' menu is missing {missing}; observed items = {items}" assert set(FILE_ITEMS) <= set(items), ( f"'File' menu items = {items}, required subset {FILE_ITEMS}") assert len(FILE_ITEMS) <= len(items) <= len(FILE_ITEMS) + 2, ( f"'File' menu has {len(items)} items ({items}), expected 3 " f"(+ at most 2 injected alternates)")
@pytest.mark.rb(depth=1, jump_kind="value", expect="opened 'Edit' menu lists Undo, Redo, Cut, Copy, Paste, Delete, " "Select All, AutoFill, Start Dictation…, Emoji & Symbols") def test_edit_menu_items(self, ax_with_reset): ax = ax_with_reset items = th.rb_enter_menu(ax, "Edit") # real AXPress -> menu surface th.dismiss_menus(ax) joined = " | ".join(items) missing = [r for r in EDIT_ITEMS if not kit.rb_value(joined, r)] assert not missing, f"'Edit' menu is missing {missing}; observed items = {items}" assert set(EDIT_ITEMS) <= set(items), ( f"'Edit' menu items = {items}, required subset {EDIT_ITEMS}") assert len(items) >= len(EDIT_ITEMS), ( f"'Edit' menu has only {len(items)} items: {items}")
@pytest.mark.rb(depth=1, jump_kind="value", expect="opened 'View' menu lists Show Tab Bar and Show All Tabs " "(Enter Full Screen appears intermittently)") def test_view_menu_items(self, ax_with_reset): ax = ax_with_reset items = th.rb_enter_menu(ax, "View") # real AXPress -> menu surface th.dismiss_menus(ax) joined = " | ".join(items) missing = [r for r in VIEW_ITEMS if not kit.rb_value(joined, r)] assert not missing, f"'View' menu is missing {missing}; observed items = {items}" assert set(VIEW_ITEMS) <= set(items), ( f"'View' menu items = {items}, required subset {VIEW_ITEMS}") assert len(items) >= len(VIEW_ITEMS), ( f"'View' menu has only {len(items)} items: {items}")
@pytest.mark.rb(depth=1, jump_kind="value", expect="opened 'Window' menu lists all 14 items Minimize … Arrange in " "Front (Tile Window to … appears intermittently)") def test_window_menu_items(self, ax_with_reset): ax = ax_with_reset items = th.rb_enter_menu(ax, "Window") # real AXPress -> menu surface th.dismiss_menus(ax) joined = " | ".join(items) missing = [r for r in WINDOW_ITEMS if not kit.rb_value(joined, r)] assert not missing, f"'Window' menu is missing {missing}; observed items = {items}" assert set(WINDOW_ITEMS) <= set(items), ( f"'Window' menu items = {items}, required subset {WINDOW_ITEMS}") assert len(items) >= len(WINDOW_ITEMS), ( f"'Window' menu has only {len(items)} items, expected >= " f"{len(WINDOW_ITEMS)}: {items}")
@pytest.mark.rb(depth=0, jump_kind="value", expect="'Help' menu lists exactly ['Terminader Help']") def test_help_menu_items(self, ax): # Static AX read (macOS keeps the whole app-menu hierarchy in the tree), so this # one is honestly depth 0 — the Help menu is never opened. items = th.menu_items(ax, "Help") joined = " | ".join(items) missing = [r for r in HELP_ITEMS if not kit.rb_value(joined, r)] assert not missing, f"'Help' menu is missing {missing}; observed items = {items}" assert set(HELP_ITEMS) <= set(items), ( f"'Help' menu items = {items}, required subset {HELP_ITEMS}") assert len(HELP_ITEMS) <= len(items) <= len(HELP_ITEMS) + 2, ( f"'Help' menu has {len(items)} items ({items}), expected 1 " f"(+ at most 2 injected alternates)")
class TestSubmenuStructure: """A menu inside a menu: Edit ▸ AutoFill."""
@pytest.mark.rb(depth=2, jump_kind="value", expect="Edit ▸ AutoFill submenu lists exactly ['Contact…', 'Passwords…']") def test_edit_autofill_submenu(self, ax_with_reset): ax = ax_with_reset items = th.rb_enter_menu(ax, "Edit") # surface 1: the Edit menu assert "AutoFill" in items, ( f"'Edit' menu exposes no 'AutoFill' submenu; items = {items}") # surface 2: the submenu hanging off the AutoFill item, read through the named # parent container (root_id) — the scan returns the parent 'AutoFill' first, drop it. sub = [] for mbi in ax.find(role="menu_bar_item", name="Edit", max_results=2, max_depth=3): for parent in ax.find(role="menu_item", name="AutoFill", root_id=mbi.id, max_results=3, max_depth=2): sub = [e.name for e in ax.find(role="menu_item", root_id=parent.id, max_results=20, max_depth=2) if e.name and e.name != "AutoFill"] if sub: break if sub: break th.dismiss_menus(ax) assert sub, ("Edit ▸ AutoFill exposes no submenu items at all " f"(expected {AUTOFILL_ITEMS}); Edit items = {items}") assert kit.rb_value(sorted(set(sub)), sorted(AUTOFILL_ITEMS)), ( f"Edit ▸ AutoFill submenu = {sub}, expected {AUTOFILL_ITEMS}") assert set(AUTOFILL_ITEMS) <= set(sub), ( f"Edit ▸ AutoFill submenu = {sub}, missing " f"{[i for i in AUTOFILL_ITEMS if i not in sub]}")
class TestMenuActivations: """The SAFE activations measured on the reference (recon M1–M6)."""
@pytest.mark.rb(depth=1, jump_kind="reach", expect="File ▸ New Window opens a second main AXWindow: window count " "1 -> 2, both titles '' (…AppWindow-1 + …AppWindow-2)") def test_file_new_window_opens_second_window(self, ax): before_titles = th.window_titles(ax) before_n = len(ax.find(role="window", max_depth=1, max_results=12)) assert before_n == 1, ( f"expected exactly 1 window at launch, got {before_n}: {before_titles}") assert th.rb_reach_menu_item(ax, "File", "New Window"), ( "File > New Window could not be activated (menu item not found / AXPress failed)") after_titles = th.window_titles(ax) after_n = len(ax.find(role="window", max_depth=1, max_results=12)) assert after_n == 2, ( f"File > New Window did not open a second window: window count {before_n} -> " f"{after_n}; titles before {before_titles} -> after {after_titles}") # both windows are main windows — the observed titles were '' and '' (recon M1) main_title = before_titles[0] assert after_titles.count(main_title) == 2, ( f"the new window is not a second MAIN window: titles after = {after_titles}, " f"main-window title was {main_title!r}") th.screenshot_assert( "menus_two_windows", "Two overlapping Terminader windows, each with its own sidebar (Favorites / " "iCloud / Locations), its own toolbar with back/forward chevrons, a path " "pop-up and a terminal icon, and its own icon grid.", RESULTS_DIR)
@pytest.mark.rb(depth=1, jump_kind="reach", expect="AXShowMenu on the grid item alpha.txt pops a context menu whose " "items are exactly 'Open' and 'Get Info'") def test_grid_item_context_menu(self, ax): assert th.rb_enter_fixtures_gui(ax), ( f"could not reach the fixture directory in GUI mode; current dir = " f"{th.current_dir_name(ax)!r}") before = kit.rb_showing(ax) items = th.rb_reach_context_menu(ax, "alpha.txt") # surface: the context menu after = kit.rb_showing(ax) assert kit.rb_reach(before, after, target="Get Info"), ( f"no context menu appeared for alpha.txt: menu items read back = {items}") assert sorted(set(items)) == CONTEXT_ITEMS, ( f"context menu items = {items}, expected exactly ['Open', 'Get Info']") # recon M2: BOTH 'Open' and 'Get Info' are absent before the AXShowMenu and # present after it — read straight out of the showing delta (no extra AX cost). # Matched on the visible NAME half of the "role|name" key so a recreation that # publishes the pop-up with a different container role still passes. appeared = {k.split("|", 1)[1] for k in (after - before) if "|" in k} for want in CONTEXT_ITEMS: assert want in appeared, ( f"'{want}' did not newly appear when the context menu opened; newly " f"showing nodes = {sorted(n for n in appeared if n)}") th.screenshot_assert( "menus_context_menu", "A small pop-up menu over the icon grid containing exactly two items, " "'Open' and 'Get Info'.", RESULTS_DIR) th.dismiss_menus(ax)
@pytest.mark.rb(depth=2, jump_kind="reach", expect="context menu ▸ Get Info opens the window titled " "'gamma.txt Info' containing the label 'Info pane'") def test_context_menu_get_info_opens_info_window(self, ax): assert th.rb_enter_fixtures_gui(ax), ( f"could not reach the fixture directory in GUI mode; current dir = " f"{th.current_dir_name(ax)!r}") items = th.rb_reach_context_menu(ax, "gamma.txt") # surface 1: context menu assert "Get Info" in items, ( f"context menu for gamma.txt has no 'Get Info' item; items = {items}") before = kit.rb_showing(ax) # 'Get Info' is showing here assert rb_reach_open_menu_item(ax, "Get Info"), ( "AXPress on the context menu's 'Get Info' item failed") after = kit.rb_showing(ax) # surface 2: the Info window assert kit.rb_reach(before, after, target="Info pane", source="Get Info"), ( f"'Get Info' did not reach an Info window: window titles now " f"{th.window_titles(ax)}") assert "gamma.txt Info" in th.window_titles(ax), ( f"no window titled 'gamma.txt Info'; window titles = {th.window_titles(ax)}") th.screenshot_assert( "menus_get_info_window", "A second, small window titled 'gamma.txt Info' whose only content is the " "text 'Info pane', in front of the main Terminader window.", RESULTS_DIR)
@pytest.mark.rb(depth=2, jump_kind="value", expect="context menu ▸ Open on the 'subdir' directory descends into it: " "grid_names == ['nested.txt'] and current dir 'subdir'") def test_context_menu_open_descends_into_directory(self, ax): assert th.rb_enter_fixtures_gui(ax), ( f"could not reach the fixture directory in GUI mode; current dir = " f"{th.current_dir_name(ax)!r}") assert "subdir" in th.grid_names(ax), ( f"the fixture grid does not show 'subdir'; grid names = {th.grid_names(ax)}") items = th.rb_reach_context_menu(ax, "subdir") # surface 1: context menu assert "Open" in items, ( f"context menu for subdir has no 'Open' item; items = {items}") assert rb_reach_open_menu_item(ax, "Open"), ( # surface 2: subdir listing "AXPress on the context menu's 'Open' item failed") names = th.grid_names(ax) assert kit.rb_value(names, NESTED_ENTRIES), ( f"after context-menu Open the grid shows {names}, expected {NESTED_ENTRIES}") assert kit.rb_value(th.current_dir_name(ax), "subdir"), ( f"current directory is {th.current_dir_name(ax)!r} after opening 'subdir'")
@pytest.mark.rb(depth=1, jump_kind="reach", expect="toolbar path picker pops a menu listing the current directory " "'rbtest' and every ancestor up to 'Users'") def test_toolbar_path_menu_lists_ancestors(self, ax): assert th.rb_enter_fixtures_gui(ax), ( f"could not reach the fixture directory in GUI mode; current dir = " f"{th.current_dir_name(ax)!r}") expected = _expected_path_chain() before = kit.rb_showing(ax) comps = th.rb_reach_path_menu(ax) # surface: the path menu after = kit.rb_showing(ax) assert kit.rb_reach(before, after, target="menu_item|" + th.rbtest_parent_name()), ( f"the path-picker menu did not open: components read back = {comps}") assert comps, "the path-picker menu exposed no path components" assert comps[0] == th.RBTEST_NAME, ( f"first path-menu component = {comps[0]!r}, expected the current directory " f"{th.RBTEST_NAME!r} (components = {comps})") assert th.rbtest_parent_name() in comps, ( f"path-menu components = {comps}, missing the parent folder " f"{th.rbtest_parent_name()!r}") if "Users" in expected: # the observed reference chain ends at /Users assert comps[-1] == "Users", ( f"last path-menu component = {comps[-1]!r}, expected 'Users' " f"(components = {comps})") missing = [c for c in expected if c not in comps] assert not missing, ( f"path-menu components = {comps}, missing {missing} of the real path " f"chain {expected}") assert len(comps) >= min(3, len(expected)), ( f"path-menu listed only {len(comps)} component(s) ({comps}); the chain from " f"{th.RBTEST_NAME!r} upwards has {len(expected)}: {expected}") th.screenshot_assert( "menus_path_menu", "An open pop-up menu below the toolbar path control listing the current " "directory 'rbtest' and each of its ancestor folders up to 'Users'.", RESULTS_DIR) th.dismiss_menus(ax)
@pytest.mark.rb(depth=2, jump_kind="value", expect="path picker ▸ ancestor 'rbtest' navigates out of subdir: " "current dir 'subdir' -> 'rbtest', status bar '1 item, …' -> " "'5 items, … available'") def test_path_menu_component_navigates_to_ancestor(self, ax): assert th.rb_enter_fixtures_gui(ax), ( f"could not reach the fixture directory in GUI mode; current dir = " f"{th.current_dir_name(ax)!r}") assert th.rb_enter_directory(ax, "subdir"), ( # surface 1: subdir listing f"could not descend into 'subdir'; current dir = {th.current_dir_name(ax)!r}") before_dir = th.current_dir_name(ax) assert before_dir == "subdir", ( f"precondition failed: current dir = {before_dir!r}, expected 'subdir'") assert th.rb_reach_path_menu(ax), ( # surface 2: the path menu "the toolbar path picker did not list any components while in 'subdir'") assert th.rb_reach_path_component(ax, th.RBTEST_NAME), ( f"could not pick the ancestor {th.RBTEST_NAME!r} from the path menu") after_dir = th.current_dir_name(ax) status = th.status_text(ax) assert kit.rb_value(after_dir, th.RBTEST_NAME), ( f"current directory = {after_dir!r} after picking {th.RBTEST_NAME!r} " f"from the path menu (was {before_dir!r})") assert kit.rb_value(status, f"{len(th.RBTEST_ENTRIES)} items,"), ( f"status bar = {status!r} after navigating from 'subdir' to " f"{th.RBTEST_NAME!r}, expected it to start with " f"'{len(th.RBTEST_ENTRIES)} items,' (was '1 item, … available')") assert status.endswith(" available"), ( f"status bar = {status!r}, expected it to end with ' available'")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605"""test_ax_states.py — STATE lane for Terminader (Finder <-> Terminal hybrid).
Owns enabled / checked / selected / focus / settability assertions (recon rows S1–S13).Every interactive row is proved as a BEFORE -> AFTER flip plus the consequence thereference app was observed to produce.
pytest only: Test* classes, methods taking the `ax` fixture, plain asserts, and a@pytest.mark.rb(...) declaration per test (rb_testgen_kit records depth/jump/tier).All app driving goes through the deployed, portable `terminader_helpers` module — noabsolute app paths, no `open -a`, no AXUIElementCreateApplication, no preference seeding."""
from __future__ import annotations
import osimport reimport sysimport time
import pytest
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import terminader_helpers as th # noqa: E402import rb_testgen_kit as kit # noqa: E402
RESULTS_DIR = os.environ.get("RESULTS_DIR", ".")
# ── observed constants (recon ## STATE / ## COMPUTATION) ──────────────────────SLIDER_LAUNCH_VALUE = 1.0 / 12.0 # 0.08333333333333333SLIDER_INCREMENT = 0.1 # AXIncrement stepICON_BASE, ICON_SPAN = 32.0, 480.0 # largest icon extent == 32 + value * 480SPLITTER_VALUE = 140.0 # sidebar widthBADGE_RE = re.compile(r"^(\d+|plus)\.circle\.fill$")STDOUT_PREFIX = "This is stdout"STDERR_TEXT = "This is stderr"
# ── local drivers ─────────────────────────────────────────────────────────────def rb_enter_favorite(ax, name, pause=1.5): """Cross into another directory surface by pressing a sidebar favourite button.
Named rb_enter_* because it really moves the browser to a new directory surface (the path pop-up value changes to `name`).""" ok = th.press_button(ax, name) time.sleep(pause) return bool(ok) and th.current_dir_name(ax) == name
def press_and_settle(ax, name, pause=1.5): """Press a toolbar/sidebar button by its accessibility name and let SwiftUI settle.""" ok = th.press_button(ax, name) time.sleep(pause) return bool(ok)
def label_elements(ax): """[(text, element)] for every non-empty label, in the same tree order as th.all_texts() (identical find call + filter).""" out = [] for el in ax.find(role="label", max_results=400, max_depth=24): v = el.value if el.value else el.name if v: out.append((str(v), el)) return out
def command_line_element(ax): """The CLI command-line label (the one right after the '<dir> ➜ ' prompt).""" labels = label_elements(ax) for i, (text, _el) in enumerate(labels): if text.endswith(th.PROMPT_SUFFIX) and i + 1 < len(labels): return labels[i + 1][1] return None
def is_focused(ax, el): """AXFocused of an element; False when the element does not exist at all.""" if el is None: return False return bool(ax.get(el.id, ["AXFocused"]).get("AXFocused"))
def paste_badge_name(ax): """AXDescription of the paste-button selection badge ('1.circle.fill'), else None.""" for el in ax.find(role="image", max_results=60, max_depth=24): name = str(el.name or "") if BADGE_RE.match(name): return name return None
def segment_subroles(ax): """{'Console': 'AXSegment', 'Errors': 'AXSegment'} read off the CLI pane radios.""" out = {} for el in ax.find(role="radio", max_results=6, max_depth=20): if el.name in th.CLI_PANES: out[str(el.name)] = ax.get(el.id, ["AXSubrole"]).get("AXSubrole") return out
def splitter_element(ax): els = ax.find(role="splitter", max_results=3, max_depth=20) return els[0] if els else None
# ══════════════════════════════════════════════════════════════════════════════class TestNavigationEnabledState: """S1 / S2 — the Back and Forward toolbar buttons are history-driven."""
@pytest.mark.rb(depth=1, jump_kind="transition", expect="Back button AXEnabled False -> True after navigating to the " "'Documents' sidebar favourite (AXHelp stays " "'See folders you viewed previously')") def test_back_enables_after_sidebar_navigation(self, ax): found_b, before, help_b = th.button_state(ax, "Back") assert found_b, "Back button not found in the toolbar at launch" assert before is False, f"Back should be disabled at launch, AXEnabled={before!r}" assert help_b == th.BACK_HELP, f"Back AXHelp={help_b!r}, expected {th.BACK_HELP!r}"
home = th.current_dir_name(ax) assert rb_enter_favorite(ax, "Documents"), ( f"sidebar favourite 'Documents' did not navigate; " f"current dir={th.current_dir_name(ax)!r} (started at {home!r})")
found_a, after, _ = th.button_state(ax, "Back") assert kit.rb_flip(before, after), ( f"Back AXEnabled did not flip: before={before!r} after={after!r}") assert found_a and before is False and after is True, ( f"expected Back AXEnabled False -> True, observed {before!r} -> {after!r} " f"(found={found_a!r}) in dir {th.current_dir_name(ax)!r}")
@pytest.mark.rb(depth=1, jump_kind="transition", expect="Forward AXEnabled False -> True after pressing Back " "(dir Documents -> home) -> False again after pressing Forward " "(dir home -> Documents)") def test_forward_enables_after_back_then_disables_after_forward(self, ax): home = th.home_dir_name() assert rb_enter_favorite(ax, "Documents"), ( f"could not reach 'Documents'; dir={th.current_dir_name(ax)!r}")
_f0, before, _h0 = th.button_state(ax, "Forward") assert before is False, ( f"Forward should still be disabled after a forward-only navigation, " f"AXEnabled={before!r}")
assert press_and_settle(ax, "Back"), "Back button could not be pressed" dir_after_back = th.current_dir_name(ax) _f1, after, _h1 = th.button_state(ax, "Forward") assert kit.rb_flip(before, after), ( f"Forward AXEnabled did not flip after Back: {before!r} -> {after!r}") assert before is False and after is True, ( f"expected Forward AXEnabled False -> True after Back, " f"observed {before!r} -> {after!r}") assert dir_after_back == home, ( f"Back should restore the home directory {home!r}, observed {dir_after_back!r}")
assert press_and_settle(ax, "Forward"), "Forward button could not be pressed" dir_after_forward = th.current_dir_name(ax) _f2, final = th.button_state(ax, "Forward")[:2] assert dir_after_forward == "Documents", ( f"Forward should re-enter 'Documents', observed {dir_after_forward!r}") assert final is False, ( f"Forward should be disabled again at the end of history, AXEnabled={final!r}")
# ══════════════════════════════════════════════════════════════════════════════class TestSelectionState: """S3 / S7 / S8 — selection drives the paste button, its badge and the status bar."""
@pytest.mark.rb(depth=2, jump_kind="transition", expect="paste button 'Next Page' AXEnabled False (nothing selected) -> " "True after selecting beta.txt and returning to the CLI surface " "(AXHelp 'Paste selected items')") def test_paste_button_enables_when_a_file_is_selected(self, ax): assert th.rb_enter_fixtures(ax), ( f"could not cd into the fixture dir; dir={th.current_dir_name(ax)!r}") found_b, before, help_b = th.button_state(ax, th.PASTE_NAME) assert found_b, f"paste button {th.PASTE_NAME!r} not found on the CLI surface" assert before is False, ( f"paste button should be disabled with an empty selection, AXEnabled={before!r}") assert help_b == th.PASTE_HELP, ( f"paste button AXHelp={help_b!r}, expected {th.PASTE_HELP!r}")
assert th.rb_enter_gui(ax), "could not return to the graphical grid" assert th.click_file(ax, "beta.txt"), "could not click beta.txt in the grid" assert th.rb_enter_cli(ax), "could not switch back to the CLI surface"
found_a, after, help_a = th.button_state(ax, th.PASTE_NAME) assert kit.rb_flip(before, after), ( f"paste-button AXEnabled did not flip: before={before!r} after={after!r}") assert found_a and before is False and after is True, ( f"expected paste AXEnabled False -> True with 1 file selected, observed " f"{before!r} -> {after!r} (found={found_a!r}, AXHelp={help_a!r})")
@pytest.mark.rb(depth=2, jump_kind="transition", expect="paste-button badge image absent -> AXDescription '1.circle.fill' " "after selecting exactly one file") def test_paste_badge_image_appears_for_one_selection(self, ax): assert th.rb_enter_fixtures(ax), ( f"could not cd into the fixture dir; dir={th.current_dir_name(ax)!r}") before = paste_badge_name(ax) assert before is None, ( f"no badge should exist with an empty selection, observed badge={before!r}")
assert th.rb_enter_gui(ax), "could not return to the graphical grid" assert th.click_file(ax, "beta.txt"), "could not click beta.txt in the grid" assert th.rb_enter_cli(ax), "could not switch back to the CLI surface"
after = paste_badge_name(ax) assert kit.rb_flip(before, after), ( f"paste badge did not appear: before={before!r} after={after!r}") assert before is None and after == "1.circle.fill", ( f"expected badge None -> '1.circle.fill' for a single selection, observed " f"{before!r} -> {after!r}")
@pytest.mark.rb(depth=1, jump_kind="transition", expect="status bar counts (None, 5) -> (1, 5) after clicking beta.txt; a " "second click on gamma.txt REPLACES the selection so it stays (1, 5)") def test_selection_counts_replace_not_accumulate(self, ax): assert th.rb_enter_fixtures_gui(ax), ( f"could not reach the fixture grid; dir={th.current_dir_name(ax)!r}") before = th.status_counts(ax) total = len(th.RBTEST_ENTRIES) assert before == (None, total), ( f"fresh fixture dir should report {(None, total)!r}, observed {before!r} " f"(status={th.status_text(ax)!r})")
assert th.click_file(ax, "beta.txt"), "could not click beta.txt in the grid" after = th.status_counts(ax) assert kit.rb_flip(before, after), ( f"status counts did not flip on selection: {before!r} -> {after!r}") assert before == (None, total) and after == (1, total), ( f"expected (None, {total}) -> (1, {total}) after selecting beta.txt, observed " f"{before!r} -> {after!r} (status={th.status_text(ax)!r})") th.screenshot_assert( "states_selection_highlight", "Terminader's icon grid shows alpha.txt, beta.txt, gamma.txt, readme.md and the " "subdir folder; beta.txt's name is highlighted on a blue rounded background and " "its icon sits on a grey tile, and the status bar reads " "'1 of 5 selected, ... available'.", RESULTS_DIR)
assert th.click_file(ax, "gamma.txt"), "could not click gamma.txt in the grid" second = th.status_counts(ax) assert second == (1, total), ( f"a second single click must REPLACE the selection, expected (1, {total}), " f"observed {second!r} (status={th.status_text(ax)!r})")
@pytest.mark.rb(depth=2, jump_kind="transition", expect="selection (1, 5) -> (None, 1) after descending into subdir — " "navigation clears the selection") def test_selection_cleared_by_descending_into_subdir(self, ax): assert th.rb_enter_fixtures_gui(ax), ( f"could not reach the fixture grid; dir={th.current_dir_name(ax)!r}") assert th.click_file(ax, "beta.txt"), "could not click beta.txt in the grid" before = th.status_counts(ax) assert before == (1, len(th.RBTEST_ENTRIES)), ( f"expected (1, {len(th.RBTEST_ENTRIES)}) after selecting beta.txt, " f"observed {before!r} (status={th.status_text(ax)!r})")
assert th.rb_enter_directory(ax, "subdir"), ( f"could not descend into subdir; dir={th.current_dir_name(ax)!r}") after = th.status_counts(ax) assert kit.rb_flip(before, after), ( f"selection state did not flip on navigation: {before!r} -> {after!r}") assert after == (None, 1), ( f"descending into subdir must clear the selection and show 1 item, observed " f"{after!r} (status={th.status_text(ax)!r}, dir={th.current_dir_name(ax)!r})")
# ══════════════════════════════════════════════════════════════════════════════class TestModeAndPaneState: """S4 / S5 — the GUI/CLI toggle and the Console/Errors segmented radios."""
@pytest.mark.rb(depth=1, jump_kind="transition", expect="pane radios {'Console': 1, 'Errors': 0} -> {'Console': 0, " "'Errors': 1} after selecting the Errors segment; both radios are " "AXSubrole 'AXSegment'") def test_console_errors_segment_selection_flips(self, ax): assert th.rb_enter_cli(ax), "could not switch to the CLI surface" before = th.pane_states(ax) assert before == {"Console": 1, "Errors": 0}, ( f"fresh CLI surface should select Console, observed {before!r}")
subroles = segment_subroles(ax) assert subroles == {"Console": "AXSegment", "Errors": "AXSegment"}, ( f"both pane radios must be AXSegment sub-role, observed {subroles!r}")
assert th.rb_enter_pane(ax, "Errors"), "could not select the Errors segment" after = th.pane_states(ax) assert kit.rb_flip(before, after), ( f"pane radio values did not flip: {before!r} -> {after!r}") assert after == {"Console": 0, "Errors": 1}, ( f"expected {{'Console': 0, 'Errors': 1}} after selecting Errors, " f"observed {after!r} (before={before!r})")
@pytest.mark.rb(depth=2, jump_kind="transition", expect="console body swaps after `test_out 3`: Console shows " "'This is stdout...' -> Errors pane shows exactly 'This is stderr'") def test_console_body_swaps_to_stderr_in_errors_pane(self, ax): assert th.rb_enter_cli(ax), "could not switch to the CLI surface" th.run_command(ax, "test_out 3") before = th.command_output(ax, "test_out 3") assert before.startswith(STDOUT_PREFIX), ( f"Console pane output should start with {STDOUT_PREFIX!r}, observed {before!r}")
assert th.rb_enter_pane(ax, "Errors"), "could not select the Errors segment" after = th.command_output(ax, "test_out 3") assert kit.rb_flip(before, after), ( f"console body did not swap between panes: {before!r} -> {after!r}") assert after == STDERR_TEXT, ( f"Errors pane should show exactly {STDERR_TEXT!r}, observed {after!r}") texts = th.all_texts(ax) assert not any(t.startswith(STDOUT_PREFIX) for t in texts), ( f"stdout text must be hidden in the Errors pane, observed texts={texts!r}") th.screenshot_assert( "states_errors_pane", "Terminader's terminal surface with the segmented control switched to Errors " "(the Errors segment is selected/highlighted, Console is not); a single console " "block is listed and its body text reads 'This is stderr'.", RESULTS_DIR)
@pytest.mark.rb(depth=1, jump_kind="transition", expect="mode (is_gui_mode, is_cli_mode) (True, False) -> (False, True); " "the toolbar toggle renames 'terminal'/'Switch to Terminal' -> " "'Window'/'Switch to graphical interface'") def test_mode_toggle_flips_surface_and_button_face(self, ax): before = (th.is_gui_mode(ax), th.is_cli_mode(ax)) assert before == (True, False), ( f"fresh launch must be in GUI mode, observed (gui, cli)={before!r}") gui_found, gui_enabled, gui_help = th.button_state(ax, th.TOGGLE_NAME_GUI) assert gui_found and gui_enabled is True, ( f"GUI-mode toggle {th.TOGGLE_NAME_GUI!r} found={gui_found!r} " f"enabled={gui_enabled!r}, expected found+enabled") assert gui_help == th.TOGGLE_HELP_GUI, ( f"toggle AXHelp={gui_help!r}, expected {th.TOGGLE_HELP_GUI!r}")
assert th.rb_enter_cli(ax), "could not switch to the CLI surface"
after = (th.is_gui_mode(ax), th.is_cli_mode(ax)) assert kit.rb_flip(before, after), ( f"mode did not flip: (gui, cli) {before!r} -> {after!r}") assert after == (False, True), ( f"expected (gui, cli) (True, False) -> (False, True), observed " f"{before!r} -> {after!r}") cli_found, cli_enabled, cli_help = th.button_state(ax, th.TOGGLE_NAME_CLI) assert cli_found and cli_enabled is True, ( f"CLI-mode toggle {th.TOGGLE_NAME_CLI!r} found={cli_found!r} " f"enabled={cli_enabled!r}, expected found+enabled") assert cli_help == th.TOGGLE_HELP_CLI, ( f"toggle AXHelp after the flip={cli_help!r}, expected {th.TOGGLE_HELP_CLI!r}") assert th.button_state(ax, th.TOGGLE_NAME_GUI)[0] is False, ( f"the {th.TOGGLE_NAME_GUI!r} face must be gone in CLI mode, observed " f"{th.button_state(ax, th.TOGGLE_NAME_GUI)!r}")
# ══════════════════════════════════════════════════════════════════════════════class TestSidebarState: """S6 — the sidebar toggle hides the outline and renames itself."""
@pytest.mark.rb(depth=0, jump_kind="transition", expect="sidebar outline present + button 'Hide Sidebar' -> outline None + " "button 'Show Sidebar'; pressing again restores both") def test_sidebar_visibility_and_button_name_flip(self, ax): hide_found = th.button_state(ax, "Hide Sidebar")[0] show_found = th.button_state(ax, "Show Sidebar")[0] before = (th.sidebar_outline(ax) is not None, hide_found, show_found) assert before == (True, True, False), ( f"at launch expected (outline, HideBtn, ShowBtn) == (True, True, False), " f"observed {before!r}")
assert press_and_settle(ax, "Hide Sidebar", pause=1.2), ( "the 'Hide Sidebar' button could not be pressed")
hide_found_a = th.button_state(ax, "Hide Sidebar")[0] show_found_a, show_enabled_a, _h = th.button_state(ax, "Show Sidebar") after = (th.sidebar_outline(ax) is not None, hide_found_a, show_found_a) assert kit.rb_flip(before, after), ( f"sidebar state did not flip: {before!r} -> {after!r}") assert after == (False, False, True), ( f"after hiding expected (outline, HideBtn, ShowBtn) == (False, False, True), " f"observed {after!r}") assert show_enabled_a is True, ( f"'Show Sidebar' must stay enabled while hidden, AXEnabled={show_enabled_a!r}") th.screenshot_assert( "states_sidebar_hidden", "The Terminader window with its sidebar hidden: no Favorites / iCloud / Locations " "list on the left, the icon grid fills the whole window, and the toolbar's " "leftmost button now shows the 'show sidebar' icon.", RESULTS_DIR)
assert press_and_settle(ax, "Show Sidebar", pause=1.2), ( "the 'Show Sidebar' button could not be pressed") restored = (th.sidebar_outline(ax) is not None, th.button_state(ax, "Hide Sidebar")[0], th.button_state(ax, "Documents")[0]) assert restored == (True, True, True), ( f"pressing 'Show Sidebar' must restore the outline, the 'Hide Sidebar' face and " f"the favourite buttons, observed (outline, HideBtn, DocumentsBtn)={restored!r}")
# ══════════════════════════════════════════════════════════════════════════════class TestIconSliderState: """S9 / S10 — the icon-size slider value and the icon geometry it drives."""
@pytest.mark.rb(depth=1, jump_kind="transition", expect="icon slider AXValue 0.0833... -> 0.5 via a settable AXValue write; " "largest icon extent 72.0 -> 272.0 (32 + value*480)") def test_icon_slider_value_and_icon_growth(self, ax): assert th.rb_enter_fixtures_gui(ax), ( f"could not reach the fixture grid; dir={th.current_dir_name(ax)!r}") before_value = th.icon_slider_value(ax) before_extent = th.largest_icon_extent(ax) assert before_value is not None and abs(before_value - SLIDER_LAUNCH_VALUE) < 0.01, ( f"launch slider AXValue should be ~{SLIDER_LAUNCH_VALUE!r}, " f"observed {before_value!r}") assert abs(before_extent - 72.0) < 2.0, ( f"largest icon extent at the launch slider value should be 72.0, " f"observed {before_extent!r}")
assert th.set_icon_slider(ax, 0.5), "AXValue write to the icon slider was rejected"
after_value = th.icon_slider_value(ax) after_extent = th.largest_icon_extent(ax) assert kit.rb_flip((before_value, before_extent), (after_value, after_extent)), ( f"slider/icon state did not flip: (value, extent) " f"({before_value!r}, {before_extent!r}) -> ({after_value!r}, {after_extent!r})") assert after_value is not None and abs(after_value - 0.5) < 0.001, ( f"slider AXValue should be 0.5 after the write, observed {after_value!r} " f"(before {before_value!r})") assert abs(after_extent - (ICON_BASE + 0.5 * ICON_SPAN)) < 2.0, ( f"largest icon extent should grow to 272.0 at slider 0.5, observed " f"{after_extent!r} (before {before_extent!r})") th.screenshot_assert( "states_large_icons", "The five fixture entries (alpha.txt, beta.txt, gamma.txt, readme.md and the " "subdir folder) are drawn with very large icons filling the grid, and the " "icon-size slider knob at the bottom right sits near the middle of its track.", RESULTS_DIR)
@pytest.mark.rb(depth=1, jump_kind="transition", expect="one AXIncrement on the icon slider raises AXValue by 0.1 " "(0.0833... -> 0.1833...) and the grid icons grow with it") def test_slider_increment_raises_value_and_grows_icons(self, ax): assert th.rb_enter_fixtures_gui(ax), ( f"could not reach the fixture grid; dir={th.current_dir_name(ax)!r}") slider = th.icon_slider(ax) assert slider is not None, "no AXSlider found on the graphical surface" assert "AXIncrement" in slider.actions, ( f"the icon slider must expose AXIncrement, actions={slider.actions!r}")
before_value = th.icon_slider_value(ax) before_extent = th.largest_icon_extent(ax) assert before_value is not None and abs(before_value - SLIDER_LAUNCH_VALUE) < 0.01, ( f"launch slider AXValue should be ~{SLIDER_LAUNCH_VALUE!r}, " f"observed {before_value!r}")
assert ax.action(slider.id, "AXIncrement"), "AXIncrement action failed on the slider" time.sleep(0.9)
after_value = th.icon_slider_value(ax) after_extent = th.largest_icon_extent(ax) assert kit.rb_flip(before_value, after_value), ( f"slider AXValue did not change on AXIncrement: " f"{before_value!r} -> {after_value!r}") assert after_value is not None and abs( after_value - (before_value + SLIDER_INCREMENT)) < 0.01, ( f"one AXIncrement step should add {SLIDER_INCREMENT} " f"({before_value + SLIDER_INCREMENT:.4f}), observed {after_value!r} " f"(before {before_value!r})") assert after_extent > before_extent, ( f"icons must grow with the slider, extent observed " f"{before_extent!r} -> {after_extent!r}")
@pytest.mark.rb(depth=1, jump_kind="transition", expect="one AXDecrement on the icon slider lowers AXValue by 0.1 " "(0.5 -> 0.4) and the grid icons shrink from 272.0 to 224.0") def test_slider_decrement_lowers_value_and_shrinks_icons(self, ax): """S10, opposite direction: AXDecrement is a real state change, not a no-op, and it feeds the same `32 + value*480` icon geometry.""" assert th.rb_enter_fixtures_gui(ax), ( f"could not reach the fixture grid; dir={th.current_dir_name(ax)!r}") assert th.set_icon_slider(ax, 0.5), "could not seed the icon slider to 0.5" slider = th.icon_slider(ax) assert slider is not None, "no AXSlider found on the graphical surface" assert "AXDecrement" in slider.actions, ( f"the icon slider must expose AXDecrement, actions={slider.actions!r}")
before_value = th.icon_slider_value(ax) before_extent = th.largest_icon_extent(ax) assert before_value is not None and abs(before_value - 0.5) < 0.01, ( f"seeded slider AXValue should be ~0.5, observed {before_value!r}")
assert ax.action(slider.id, "AXDecrement"), "AXDecrement action failed on the slider" time.sleep(0.9)
after_value = th.icon_slider_value(ax) after_extent = th.largest_icon_extent(ax) assert kit.rb_flip(before_value, after_value), ( f"slider AXValue did not change on AXDecrement: " f"{before_value!r} -> {after_value!r}") assert after_value is not None and abs( after_value - (before_value - SLIDER_INCREMENT)) < 0.01, ( f"one AXDecrement step should subtract {SLIDER_INCREMENT} " f"({before_value - SLIDER_INCREMENT:.4f}), observed {after_value!r}") expected_extent = 32.0 + after_value * 480.0 assert abs(after_extent - expected_extent) < 4.0, ( f"icon extent after AXDecrement was {after_extent!r}, expected " f"~{expected_extent:.1f} (= 32 + {after_value!r}*480)") assert after_extent < before_extent, ( f"icons must shrink with the slider, extent observed " f"{before_extent!r} -> {after_extent!r}")
# ══════════════════════════════════════════════════════════════════════════════class TestFocusState: """S11 — where the keyboard focus lives on the CLI surface."""
@pytest.mark.rb(depth=1, jump_kind="transition", expect="no focused command line in GUI mode -> the CLI command-line label " "reports AXFocused True after switching to the Terminal surface") def test_command_line_label_takes_focus_in_cli(self, ax): before_el = command_line_element(ax) before = is_focused(ax, before_el) assert before is False, ( f"the GUI surface has no focused command line, observed AXFocused={before!r} " f"on element {before_el!r}")
assert th.rb_enter_cli(ax), "could not switch to the CLI surface"
after_el = command_line_element(ax) after = is_focused(ax, after_el) assert kit.rb_flip(before, after), ( f"command-line focus did not flip: {before!r} -> {after!r}") assert after_el is not None and before is False and after is True, ( f"expected the CLI command-line label AXFocused False -> True, observed " f"{before!r} -> {after!r} (prompt={th.prompt_label_value(ax)!r})")
@pytest.mark.rb(depth=1, jump_kind="transition", expect="search AXTextField AXFocused False -> True after clicking and " "typing 'zz' into it, and its AXValue becomes 'zz'") def test_search_field_takes_focus_and_holds_typed_text(self, ax): assert th.rb_enter_cli(ax), "could not switch to the CLI surface" field_before = th.search_field(ax) assert field_before is not None, "no console filter AXTextField on the CLI surface" before = is_focused(ax, field_before) assert before is False, ( f"the filter field should not own the focus before it is clicked, " f"AXFocused={before!r}")
assert th.type_in_search(ax, "zz"), "could not click+type into the filter field"
field_after = th.search_field(ax) assert field_after is not None, "the console filter field disappeared after typing" after = is_focused(ax, field_after) value = ax.get(field_after.id, ["AXValue"]).get("AXValue") assert kit.rb_flip(before, after), ( f"filter-field focus did not flip: {before!r} -> {after!r}") assert before is False and after is True, ( f"expected the search field AXFocused False -> True after typing, observed " f"{before!r} -> {after!r}") assert value == "zz", ( f"the typed text must land in the filter field, AXValue={value!r}, expected 'zz'")
# ══════════════════════════════════════════════════════════════════════════════class TestStaticControlState: """S12 / S13 — states that are read, not flipped: the splitter and AX settability."""
@pytest.mark.rb(depth=0, jump_kind="value", expect="split-group splitter AXValue == 140.0 and AXEnabled is False") def test_splitter_value_and_disabled_state(self, ax): el = splitter_element(ax) assert el is not None, "no AXSplitter found between the sidebar and the detail area" attrs = ax.get(el.id, ["AXValue", "AXEnabled"]) value, enabled = attrs.get("AXValue"), attrs.get("AXEnabled") assert kit.rb_value(value, SPLITTER_VALUE), ( f"splitter AXValue={value!r}, expected {SPLITTER_VALUE!r} (sidebar width)") assert value is not None and abs(float(value) - SPLITTER_VALUE) < 0.5, ( f"splitter AXValue={value!r}, expected ~{SPLITTER_VALUE!r}") assert bool(enabled) is False, ( f"the splitter is reported disabled by the reference app, AXEnabled={enabled!r}")
@pytest.mark.rb(depth=0, jump_kind="value", expect="AXValue settability: icon slider True, path pop-up False " "(the pop-up is driven by AXPress + menu items)") def test_axvalue_settability_slider_vs_path_popup(self, ax): slider = th.icon_slider(ax) popup = th.path_popup(ax) assert slider is not None, "no icon-size AXSlider on the graphical surface" assert popup is not None, "no path AXPopUpButton in the toolbar"
slider_settable = ax.is_attribute_settable(slider.id, "AXValue") popup_settable = ax.is_attribute_settable(popup.id, "AXValue") observed = (slider_settable, popup_settable) assert kit.rb_value(observed, (True, False)), ( f"AXValue settability (slider, path pop-up) observed {observed!r}, " f"expected (True, False)") assert slider_settable is True, ( f"the icon slider AXValue must be settable, observed {slider_settable!r} " f"(slider value={th.icon_slider_value(ax)!r})") assert popup_settable is False, ( f"the path pop-up AXValue must NOT be settable, observed {popup_settable!r} " f"(pop-up value={th.path_popup_value(ax)!r})")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705"""AX STRUCTURE tests for Terminader (Finder <-> Terminal hybrid file browser).
Generated from the behavioural recon (`recon.md` -> `## STRUCTURE`, `## AX_TREE`).Every fact asserted here was OBSERVED on the reference app:
* one `AXWindow`, `AXTitle == ""`, `AXIdentifier == "Terminader.ContentView-1-AppWindow-1"` * a shared toolbar (`Hide Sidebar`, `Back`, `Forward`, path `AXPopUpButton`, `terminal`) and a shared `AXOutline` named `Sidebar` (Favorites / iCloud / Locations) * two mutually exclusive detail surfaces: GUI -> icon grid (`Move`/`Document` images) + status bar + icon-size slider CLI -> `Console`/`Errors` segments + "\U0001f50d Search" field + prompt + paste button * shape deltas: mode switch, Hide Sidebar, File > New Window, Get Info, console pop-out, `cd` into the fixture dir, descending into `subdir`, running a command.
Tests are pytest methods taking the deployed `ax` fixture; navigation goes exclusivelythrough `terminader_helpers` (`th.rb_enter_*` / `th.rb_reach_*`) so the SAME file drivesthe reference app and any recreation. No app paths, no spawning, no preference seeding.
14 tests -- jump_kind: none=4 (the existence gate, 28.6 %), reach=5, transition=2,value=3; depth: 0 -> 5 tests, 1 -> 4 tests, 2 -> 5 tests."""
from __future__ import annotations
import osimport reimport sysimport time
import pytest
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import terminader_helpers as th # noqa: E402 (shared portable driver)import rb_testgen_kit as kit # noqa: E402 (depth/jump declaration kit)
RESULTS_DIR = os.environ.get("RESULTS_DIR", ".")
MAIN_WINDOW_ID = "Terminader.ContentView-1-AppWindow-1"STATUS_RE = re.compile(r"^\d+ items?, .+ available$")
# Roles the reference window subtree exposes (ax_helpers short names).REQUIRED_ROLES = { "window", "toolbar", "split_group", "outline", "row", "cell", "heading", "button", "popup", "slider", "image", "label", "scroll_area", "splitter",}# Controls that must expose AXPress at launch: the 6 named sidebar favourites, the# sidebar toggle and the mode toggle. `Back`/`Forward` are DISABLED at launch, so they# are asserted by role+name presence instead (see the gate test).NAMED_PRESSABLE = th.SIDEBAR_FAVORITES + ["Hide Sidebar", th.TOGGLE_NAME_GUI]NAMED_TOOLBAR_BUTTONS = ["Hide Sidebar", "Back", "Forward", th.TOGGLE_NAME_GUI]
# ── local read-only helpers (no navigation, no app knowledge) ─────────────────def _main_windows(ax, timeout: float = 6.0): """Top-level `AXWindow`s, polled briefly so a slow launch is not mis-read as 'no window'. The recon records Terminader as a regular (non-LSUIElement) app whose main window is on screen right after launch, so no reveal path is needed.""" wins = [] deadline = time.time() + timeout while time.time() < deadline: wins = ax.find(role="window", max_results=8, max_depth=1) if wins: break time.sleep(0.3) return wins
def _walk_nodes(node, depth=0): """(depth, role, name, actions) for every node of an `ax.tree()` dict.""" if not isinstance(node, dict): return name = node.get("name") or node.get("value") or "" yield depth, str(node.get("role") or ""), str(name), list(node.get("actions") or []) for child in (node.get("children") or []): yield from _walk_nodes(child, depth + 1)
def _has_text(ax, text): """Semantic (framework-agnostic) text lookup: the string shows up as a label value or as the AXTitle/AXDescription of a heading/label/button/row/cell.""" if text in th.all_texts(ax): return True for role in ("heading", "label", "button", "cell", "row"): if ax.find(role=role, name=text, max_results=1, max_depth=20): return True return False
def _showing_has(showing, role, name): """`kit.rb_showing` keys are "<short role>|<AXTitle/AXDescription or AXValue>", so a single tree walk answers many existence questions. Role-qualified so a grid label named "Documents" can never satisfy a sidebar *button* check.""" return f"{role}|{name}" in showing
def _titled_window(ax, title): return [t for t in th.window_titles(ax) if t == title]
# ─────────────────────────────────────────────────────────────────────────────# GATE — existence / shape of the surfaces that are on screen at launch.# Kept to 4 tests (<= 30 % of this file) and each one covers a whole surface.# ─────────────────────────────────────────────────────────────────────────────class TestStructureGate:
@pytest.mark.rb(depth=0, jump_kind="none") def test_gate_window_toolbar_sidebar_split(self, ax): """Main window + toolbar (4 controls + path picker) + Sidebar outline + split group.""" wins = _main_windows(ax) assert len(wins) == 1, ( f"expected exactly 1 Terminader window at launch, got {len(wins)} " f"(titles={th.window_titles(ax)})") attrs = ax.get(wins[0].id, ["AXTitle", "AXIdentifier", "AXSubrole"]) assert (attrs.get("AXTitle") or "") == "", \ f"main window AXTitle should be '' but is {attrs.get('AXTitle')!r}" assert attrs.get("AXIdentifier") == MAIN_WINDOW_ID, \ f"main window AXIdentifier = {attrs.get('AXIdentifier')!r}" assert attrs.get("AXSubrole") == "AXStandardWindow", \ f"main window AXSubrole = {attrs.get('AXSubrole')!r}"
toolbars = ax.find(role="toolbar", max_results=4, max_depth=8) assert len(toolbars) >= 1, "no AXToolbar under the Terminader window" tw, thh = th.element_size(ax, toolbars[0]) assert tw >= 400 and 30 <= thh <= 90, \ f"toolbar frame {tw}x{thh} does not look like Terminader's 900x52 toolbar"
# The four named toolbar controls, exactly as observed at launch. found, enabled, _ = th.button_state(ax, "Hide Sidebar") assert found and enabled, f"'Hide Sidebar' toolbar button found={found} enabled={enabled}" b_found, b_enabled, b_help = th.button_state(ax, "Back") assert b_found and not b_enabled, \ f"'Back' should exist and be disabled at launch (found={b_found}, enabled={b_enabled})" assert b_help == th.BACK_HELP, f"'Back' AXHelp = {b_help!r}" f_found, f_enabled, _ = th.button_state(ax, "Forward") assert f_found and not f_enabled, \ f"'Forward' should exist and be disabled at launch (found={f_found}, enabled={f_enabled})" t_found, t_enabled, t_help = th.button_state(ax, th.TOGGLE_NAME_GUI) assert t_found and t_enabled, \ f"mode toggle '{th.TOGGLE_NAME_GUI}' found={t_found} enabled={t_enabled}" assert t_help == th.TOGGLE_HELP_GUI, f"mode toggle AXHelp = {t_help!r}"
popup = th.path_popup(ax) assert popup is not None, "no AXPopUpButton path picker in the toolbar" assert "AXPress" in (popup.actions or []), \ f"path picker exposes no AXPress action (actions={popup.actions})" # The picker names the directory the browser is showing (the home dir at launch). # The exact trailing space is the TEXT lane's business; here only the identity. assert th.current_dir_name(ax) == th.home_dir_name(), \ f"path picker value = {th.path_popup_value(ax)!r}, expected the home dir " \ f"{th.home_dir_name()!r}"
outline = th.sidebar_outline(ax) assert outline is not None, "no AXOutline sidebar at launch" assert outline.name == "Sidebar", f"sidebar AXOutline name = {outline.name!r}" sw, sh = th.element_size(ax, outline) assert 100 <= sw <= 220, f"sidebar width {sw} is not Terminader's ~140 pt sidebar" assert sh > 100, f"sidebar height {sh} is too small to hold the favourite rows"
assert ax.find(role="split_group", max_results=2, max_depth=8), \ "no AXSplitGroup holding the sidebar + detail area" assert ax.find(role="splitter", max_results=2, max_depth=10), \ "no AXSplitter between the sidebar and the detail area"
th.screenshot_assert( "structure_gate_window_toolbar_sidebar", "One Terminader window (~900x450). A ~140pt sidebar down the left lists the " "heading 'Favorites' with rows Desktop, Documents, Downloads, Movies, Music, " "Pictures and the home folder, then the heading 'iCloud' with 'iCloud Drive' and " "the heading 'Locations' with 'Network'. A toolbar spans the top: a " "sidebar-toggle icon on the left, greyed-out back/forward chevrons, a path " "pop-up button showing the home folder name, and a terminal icon at the right " "edge. The detail area right of the sidebar shows an icon grid with a status bar " "reading '<n> items, ... available' and a small icon-size slider on its right.", RESULTS_DIR)
@pytest.mark.rb(depth=0, jump_kind="none") def test_gate_sidebar_favorites_and_sections(self, ax): """7 pressable favourites + the 3 headings + the 2 static location labels.""" outline = th.sidebar_outline(ax) assert outline is not None, "sidebar outline missing — cannot check its contents"
# One scoped pass over the Sidebar subtree, with an app-wide fallback so a # recreation that nests the rows differently still matches by name + role. sidebar_buttons = {} for el in ax.find(role="button", root_id=outline.id, max_results=40, max_depth=6): if el.name: sidebar_buttons.setdefault(el.name, el) expected_favs = list(th.SIDEBAR_FAVORITES) + [th.home_dir_name()] present = [] for name in expected_favs: el = sidebar_buttons.get(name) if el is None: cands = th.find_buttons(ax, name) el = cands[0] if cands else None assert el is not None, \ f"sidebar favourite button {name!r} not found; sidebar buttons = " \ f"{sorted(sidebar_buttons)}" assert "AXPress" in (el.actions or []), \ f"sidebar favourite {name!r} exposes no AXPress action (actions={el.actions})" present.append(name) assert len(present) == 7, \ f"expected 7 pressable sidebar favourites, got {len(present)}: {present}"
showing = kit.rb_showing(ax) for heading in th.SIDEBAR_HEADINGS: # Favorites / iCloud / Locations assert _showing_has(showing, "heading", heading) or _has_text(ax, heading), \ f"sidebar section heading {heading!r} missing" texts = th.all_texts(ax) for label in th.SIDEBAR_STATIC: # iCloud Drive / Network assert label in texts, f"sidebar label {label!r} missing from {texts[:12]}" # On the reference these two are inert rows (acts=[]), unlike the favourites. assert label not in sidebar_buttons, \ f"{label!r} is exposed as a pressable sidebar button; the reference renders " \ f"it as a plain label with no actions"
rows = ax.find(role="row", root_id=outline.id, max_results=40, max_depth=6) assert len(rows) >= 11, \ f"sidebar shows {len(rows)} AXRows, expected >= 11 (7 favourites + 2 statics + headings)" cells = ax.find(role="cell", root_id=outline.id, max_results=60, max_depth=6) assert len(cells) >= 11, f"sidebar shows only {len(cells)} AXCells"
@pytest.mark.rb(depth=0, jump_kind="none") def test_gate_gui_detail_trio(self, ax): """GUI surface = icon grid + status bar + icon-size slider (and no CLI widgets).""" icons = th.grid_icons(ax) assert icons, ( "no grid icons found: the GUI detail area exposes no AXImage named " f"{th.FOLDER_ICON_NAME!r} (folder) or {th.FILE_ICON_NAME!r} (file)") no_menu = [i.name for i in icons if "AXShowMenu" not in (i.actions or [])] assert not no_menu, f"grid icons without an AXShowMenu action: {no_menu}" names = th.grid_names(ax) assert names, "the icon grid exposes icons but no name labels" assert all(n.strip() for n in names), f"blank grid name label among {names}"
status = th.status_text(ax) assert STATUS_RE.match(status), f"GUI status bar text = {status!r}" sel, total = th.status_counts(ax) assert sel is None, f"nothing should be selected at launch, status says {sel} selected" assert total and total >= 1, f"status bar item total = {total!r}" assert 0 < len(icons) <= total, \ f"{len(icons)} grid icons for a directory the status bar reports as {total} items"
slider = th.icon_slider(ax) assert slider is not None, "no AXSlider for the icon size" value = th.icon_slider_value(ax) assert value is not None and abs(value - (1.0 / 12.0)) < 0.02, \ f"icon slider launch value = {value!r} (expected 0.08333...)" for act in ("AXIncrement", "AXDecrement"): assert act in (slider.actions or []), \ f"icon slider is missing {act}; actions={slider.actions}" assert ax.find(role="value_indicator", max_results=3, max_depth=22), \ "icon slider has no AXValueIndicator child"
# GUI and CLI are mutually exclusive surfaces. assert th.is_gui_mode(ax), "app did not launch on the graphical (Finder) surface" assert th.pane_states(ax) == {}, \ f"CLI Console/Errors segments visible in GUI mode: {th.pane_states(ax)}" assert th.search_field(ax) is None, "CLI search AXTextField present in GUI mode"
@pytest.mark.rb(depth=0, jump_kind="none") def test_gate_role_diversity_depth_and_menu_bar(self, ax): """Role diversity, hierarchy depth, interactive-widget count, and the menu bar.""" wins = _main_windows(ax) assert len(wins) == 1, f"expected 1 window, got {len(wins)}" nodes = list(_walk_nodes(ax.tree(max_depth=14, root_id=wins[0].id))) roles = {r for _d, r, _n, _a in nodes if r} missing = sorted(REQUIRED_ROLES - roles) assert not missing, f"window subtree is missing roles {missing}; found {sorted(roles)}" assert len(roles) >= 12, \ f"only {len(roles)} distinct roles under the window: {sorted(roles)}"
max_depth = max(d for d, _r, _n, _a in nodes) assert max_depth >= 6, \ f"deepest window descendant is only {max_depth} levels below the window " \ f"(grid/sidebar leaves sit >= 6 levels down)" assert len(nodes) >= 45, ( f"window subtree has only {len(nodes)} nodes — the sidebar rows/cells, the " f"toolbar controls and the grid alone account for more on the reference")
interactive = [(r, n) for _d, r, n, a in nodes if "AXPress" in a] assert len(interactive) >= 10, ( f"only {len(interactive)} AXPress-able widgets in the window (the 7 sidebar " f"favourites + the toolbar controls alone exceed that): {interactive[:15]}") named = {n for _r, n in interactive} for name in NAMED_PRESSABLE: assert name in named, \ f"pressable control {name!r} missing from the window's interactive widgets" all_named = {n for _d, _r, n, _a in nodes if n} for name in NAMED_TOOLBAR_BUTTONS: assert name in all_named, \ f"toolbar control {name!r} missing from the window subtree"
titles = th.menu_bar_titles(ax) for title in ["Terminader", "File", "Edit", "View", "Window", "Help"]: assert title in titles, f"menu bar title {title!r} missing from {titles}" assert th.menu_items(ax, "File") == ["New Window", "Close", "Close All"], \ f"File menu items = {th.menu_items(ax, 'File')}" assert th.menu_items(ax, "Help") == ["Terminader Help"], \ f"Help menu items = {th.menu_items(ax, 'Help')}" app_menu = th.menu_items(ax, "Terminader") for item in ["About Terminader", "Services", "Hide Terminader", "Hide Others", "Show All", "Quit Terminader"]: assert item in app_menu, f"Terminader menu item {item!r} missing from {app_menu}" edit_menu = th.menu_items(ax, "Edit") for item in ["Undo", "Redo", "Cut", "Copy", "Paste", "Select All", "AutoFill"]: assert item in edit_menu, f"Edit menu item {item!r} missing from {edit_menu}" view_menu = th.menu_items(ax, "View") for item in ["Show Tab Bar", "Show All Tabs"]: assert item in view_menu, f"View menu item {item!r} missing from {view_menu}" window_menu = th.menu_items(ax, "Window") for item in ["Minimize", "Zoom", "Merge All Windows", "Bring All to Front"]: assert item in window_menu, f"Window menu item {item!r} missing from {window_menu}"
# ─────────────────────────────────────────────────────────────────────────────# SHAPE DELTAS — the two mutually exclusive detail surfaces.# ─────────────────────────────────────────────────────────────────────────────class TestModeSurfaceShape:
@pytest.mark.rb(depth=1, jump_kind="reach", expect="GUI -> CLI: 'Console'/'Errors' segments + '\U0001f50d Search' field + " "'Next Page' paste button + prompt appear, icon grid + " "'<n> items, ... available' status bar + icon slider disappear") def test_cli_surface_replaces_gui_widgets(self, ax): before = kit.rb_showing(ax) assert th.rb_enter_cli(ax), "pressing the 'terminal' toolbar button did not reach CLI mode" after = kit.rb_showing(ax) assert kit.rb_reach(before, after, target="Console", source="items,"), \ "no GUI->CLI surface jump: 'Console' did not appear / the status bar did not go away"
assert th.pane_states(ax) == {"Console": 1, "Errors": 0}, \ f"CLI pane segments = {th.pane_states(ax)} (expected Console selected)" for pane in th.CLI_PANES: els = ax.find(role="radio", name=pane, max_results=2, max_depth=20) assert els, f"CLI pane segment {pane!r} not found as an AXRadioButton" assert any("AXPress" in (e.actions or []) for e in els), \ f"CLI pane segment {pane!r} exposes no AXPress"
field = th.search_field(ax) assert field is not None, "no AXTextField console filter in CLI mode" placeholder = ax.get(field.id, ["AXPlaceholderValue"]).get("AXPlaceholderValue") assert placeholder == th.SEARCH_PLACEHOLDER, \ f"search field placeholder = {placeholder!r}"
prompt = th.prompt_label_value(ax) assert prompt and prompt.endswith(th.PROMPT_SUFFIX), \ f"CLI prompt label = {prompt!r} (expected '<dir> {th.PROMPT_SUFFIX}')"
p_found, p_enabled, p_help = th.button_state(ax, th.PASTE_NAME) assert p_found, f"paste button {th.PASTE_NAME!r} not found in CLI mode" assert not p_enabled, "paste button should be disabled while nothing is selected" assert p_help == th.PASTE_HELP, f"paste button AXHelp = {p_help!r}"
# The GUI trio is gone and the toolbar toggle has flipped its face. assert th.icon_slider(ax) is None, "icon-size slider still present in CLI mode" assert th.status_text(ax) == "", f"GUI status bar still shows {th.status_text(ax)!r}" assert not th.grid_icons(ax), \ f"{len(th.grid_icons(ax))} grid icons still present in CLI mode" w_found, w_enabled, w_help = th.button_state(ax, th.TOGGLE_NAME_CLI) assert w_found and w_enabled, \ f"CLI mode toggle {th.TOGGLE_NAME_CLI!r} found={w_found} enabled={w_enabled}" assert w_help == th.TOGGLE_HELP_CLI, f"CLI toggle AXHelp = {w_help!r}" # The sidebar is shared by both surfaces and must survive the jump. assert th.sidebar_outline(ax) is not None, "the Sidebar outline vanished with the mode switch"
th.screenshot_assert( "structure_cli_surface", "Terminader on the Terminal (CLI) surface: the sidebar with Favorites / iCloud / " "Locations is still on the left, but the detail area now shows a paste-document " "button, a Console/Errors segmented control with 'Console' selected, a " "'\U0001f50d Search' field on its right, an empty console history area, and a green " "'<dir> ➜' prompt with a yellow block cursor along the bottom. No icon grid, " "no '<n> items, ... available' status bar and no icon-size slider are visible.", RESULTS_DIR)
@pytest.mark.rb(depth=2, jump_kind="reach", expect="CLI -> GUI: icon grid + '<n> items, ... available' status bar + " "icon slider come back, 'Console'/'Errors' segments and the " "'\U0001f50d Search' field disappear") def test_gui_surface_restored_after_cli(self, ax): assert th.rb_enter_cli(ax), "could not reach the CLI surface" before = kit.rb_showing(ax) assert th.rb_enter_gui(ax), "pressing the 'Window' toolbar button did not restore GUI mode" after = kit.rb_showing(ax) assert kit.rb_reach(before, after, target="items,", source="Console"), \ "no CLI->GUI surface jump: the status bar did not reappear / 'Console' did not go away"
assert th.icon_slider(ax) is not None, "icon-size slider did not come back in GUI mode" assert STATUS_RE.match(th.status_text(ax)), \ f"restored status bar text = {th.status_text(ax)!r}" assert th.grid_icons(ax), "icon grid did not come back in GUI mode" assert th.pane_states(ax) == {}, \ f"CLI Console/Errors segments survived the switch back: {th.pane_states(ax)}" assert th.search_field(ax) is None, "CLI search field survived the switch back to GUI" assert th.prompt_label_value(ax) is None, \ f"CLI prompt label survived the switch back: {th.prompt_label_value(ax)!r}" t_found, _t_enabled, t_help = th.button_state(ax, th.TOGGLE_NAME_GUI) assert t_found and t_help == th.TOGGLE_HELP_GUI, \ f"toolbar toggle back in GUI mode: found={t_found} help={t_help!r}"
# ─────────────────────────────────────────────────────────────────────────────# SHAPE DELTAS — sidebar visibility and window count.# ─────────────────────────────────────────────────────────────────────────────class TestSidebarAndWindowShape:
@pytest.mark.rb(depth=0, jump_kind="transition", expect="'Hide Sidebar' flips the Sidebar outline from an element to None, " "removes the 7 favourite buttons / Favorites-iCloud-Locations rows, " "and renames the toolbar button to 'Show Sidebar'") def test_hide_sidebar_removes_outline_and_favorites(self, ax): before_outline = th.sidebar_outline(ax) assert before_outline is not None, "no Sidebar outline to hide" before_showing = kit.rb_showing(ax) before_favs = sorted(n for n in th.SIDEBAR_FAVORITES if _showing_has(before_showing, "button", n)) assert before_favs == sorted(th.SIDEBAR_FAVORITES), \ f"favourite buttons before hiding: {before_favs}"
assert th.press_button(ax, "Hide Sidebar"), \ "could not press the 'Hide Sidebar' toolbar button" time.sleep(1.0)
after_outline = th.sidebar_outline(ax) after_showing = kit.rb_showing(ax) assert kit.rb_flip(before_outline is None, after_outline is None), \ "the Sidebar outline did not flip from present to absent" assert after_outline is None, \ f"an AXOutline is still exposed after Hide Sidebar: {after_outline.name!r}"
still = sorted(n for n in list(th.SIDEBAR_FAVORITES) + [th.home_dir_name()] if _showing_has(after_showing, "button", n)) assert not still, f"sidebar favourite buttons survived Hide Sidebar: {still}" texts = th.all_texts(ax) for label in th.SIDEBAR_STATIC: assert label not in texts, f"sidebar label {label!r} survived Hide Sidebar" for heading in th.SIDEBAR_HEADINGS: assert not _showing_has(after_showing, "heading", heading), \ f"the {heading!r} sidebar heading survived Hide Sidebar" assert not ax.find(role="row", max_results=4, max_depth=20), \ "sidebar AXRows survived Hide Sidebar"
s_found, s_enabled, _ = th.button_state(ax, "Show Sidebar") assert s_found and s_enabled, \ f"toolbar button did not become 'Show Sidebar' (found={s_found}, enabled={s_enabled})" assert not _showing_has(after_showing, "button", "Hide Sidebar"), \ "'Hide Sidebar' is still exposed after the sidebar was hidden" assert len(after_showing) < len(before_showing), \ f"tree did not shrink: {len(before_showing)} -> {len(after_showing)} nodes" # The detail surface is untouched by the sidebar toggle. assert STATUS_RE.match(th.status_text(ax)), \ f"status bar after Hide Sidebar = {th.status_text(ax)!r}"
th.screenshot_assert( "structure_sidebar_hidden", "The Terminader window with NO sidebar: the Favorites / iCloud / Locations list " "(Desktop, Documents, Downloads, Movies, Music, Pictures, home, iCloud Drive, " "Network) is gone, the icon grid now fills the full window width, and the " "leftmost toolbar button shows the 'show sidebar' icon. The toolbar still has " "back/forward chevrons, the path pop-up and the terminal icon, and the status bar " "still reads '<n> items, ... available'.", RESULTS_DIR)
@pytest.mark.rb(depth=1, jump_kind="transition", expect="window count 1 -> 2 after File > New Window; identifiers " "Terminader.ContentView-1-AppWindow-1 and ...AppWindow-2, both titles ''") def test_new_window_adds_second_main_window(self, ax): before = _main_windows(ax) assert len(before) == 1, f"expected 1 window before File > New Window, got {len(before)}" assert ax.get(before[0].id, ["AXIdentifier"]).get("AXIdentifier") == MAIN_WINDOW_ID, \ f"first window identifier = {ax.get(before[0].id, ['AXIdentifier'])}"
assert th.rb_reach_menu_item(ax, "File", "New Window"), \ "File > New Window could not be activated"
after = ax.find(role="window", max_results=8, max_depth=1) assert kit.rb_flip(len(before), len(after)), \ f"window count did not change: still {len(after)}" assert len(after) == 2, f"expected 2 windows after File > New Window, got {len(after)}"
idents = [str(ax.get(w.id, ["AXIdentifier"]).get("AXIdentifier") or "") for w in after] assert any(i.endswith("AppWindow-1") for i in idents), \ f"no ...AppWindow-1 identifier among {idents}" assert any(i.endswith("AppWindow-2") for i in idents), \ f"no ...AppWindow-2 identifier among {idents}" assert th.window_titles(ax) == ["", ""], \ f"both Terminader windows should have empty titles, got {th.window_titles(ax)}" for w in after: assert ax.find(role="toolbar", root_id=w.id, max_results=2, max_depth=6), \ "a Terminader window opened without its own toolbar" assert ax.find(role="split_group", root_id=w.id, max_results=2, max_depth=6), \ "a Terminader window opened without its own sidebar/detail split group"
th.screenshot_assert( "structure_two_windows", "Two overlapping Terminader windows. Each one has its own sidebar listing " "Favorites (Desktop, Documents, Downloads, Movies, Music, Pictures, home), iCloud " "and Locations, its own toolbar with the sidebar toggle, back/forward chevrons, " "path pop-up and terminal icon, and its own icon grid with a status bar. Neither " "window shows any text in its title bar.", RESULTS_DIR)
# ─────────────────────────────────────────────────────────────────────────────# SHAPE DELTAS — the icon grid follows the current directory.# ─────────────────────────────────────────────────────────────────────────────class TestGridShape:
@pytest.mark.rb(depth=1, jump_kind="value", expect="fixture dir grid = 5 icons (4 'Document' + 1 'Move'), names " "['alpha.txt','beta.txt','gamma.txt','readme.md','subdir'], " "status '5 items, ... available'") def test_fixture_dir_grid_shape(self, ax): assert th.rb_enter_fixtures_gui(ax), \ "could not cd into the rbtest fixture directory and return to the icon grid" assert th.current_dir_name(ax) == th.RBTEST_NAME, \ f"path picker reads {th.path_popup_value(ax)!r}"
icons = th.grid_icons(ax) assert kit.rb_value(len(icons), len(th.RBTEST_ENTRIES)), \ f"grid shows {len(icons)} icons, expected {len(th.RBTEST_ENTRIES)}" docs = [i for i in icons if i.name == th.FILE_ICON_NAME] dirs = [i for i in icons if i.name == th.FOLDER_ICON_NAME] assert len(docs) == len(th.RBTEST_FILES), \ f"{len(docs)} '{th.FILE_ICON_NAME}' icons, expected {len(th.RBTEST_FILES)}" assert len(dirs) == len(th.RBTEST_DIRS), \ f"{len(dirs)} '{th.FOLDER_ICON_NAME}' icons, expected {len(th.RBTEST_DIRS)}"
names = th.grid_names(ax) assert names == th.RBTEST_ENTRIES, f"grid name labels = {names}" assert len(names) == len(icons), \ f"{len(icons)} icons but {len(names)} name labels — grid cells are unbalanced" status = th.status_text(ax) assert status.startswith("%d items," % len(th.RBTEST_ENTRIES)), \ f"fixture-dir status bar = {status!r} (expected '5 items, ... available')" assert status.endswith(" available"), f"fixture-dir status bar = {status!r}" assert th.status_counts(ax) == (None, len(th.RBTEST_ENTRIES)), \ f"status bar counts = {th.status_counts(ax)} ({status!r})"
th.screenshot_assert( "structure_fixture_grid", "Terminader's icon grid showing exactly five items: four grey document icons " "labelled alpha.txt, beta.txt, gamma.txt and readme.md, plus one cyan folder icon " "labelled subdir. The toolbar path pop-up reads 'rbtest', the sidebar is still " "visible on the left, and the status bar under the grid reads '5 items, ... " "available' with the icon-size slider at its right.", RESULTS_DIR)
@pytest.mark.rb(depth=2, jump_kind="value", expect="descending into 'subdir' shrinks the grid 5 -> 1 icon, " "grid names == ['nested.txt'], status '1 item, ... available'") def test_descending_subdir_shrinks_grid(self, ax): assert th.rb_enter_fixtures_gui(ax), "could not reach the rbtest fixture grid" before_icons = len(th.grid_icons(ax)) assert before_icons == len(th.RBTEST_ENTRIES), \ f"fixture grid had {before_icons} icons before descending"
assert th.rb_enter_directory(ax, "subdir"), \ "double-clicking the 'subdir' folder did not descend into it" assert th.current_dir_name(ax) == "subdir", \ f"path picker reads {th.path_popup_value(ax)!r} after descending" assert kit.rb_value(th.grid_names(ax), ["nested.txt"]), \ f"grid names inside subdir = {th.grid_names(ax)}" after_icons = th.grid_icons(ax) assert len(after_icons) == 1, \ f"{len(after_icons)} icons inside subdir (expected 1, was {before_icons})" assert after_icons[0].name == th.FILE_ICON_NAME, \ f"nested.txt icon AXDescription = {after_icons[0].name!r}" status = th.status_text(ax) assert status.startswith("1 item,"), \ f"status bar inside subdir = {status!r} (expected the singular '1 item,')" assert th.status_counts(ax) == (None, 1), \ f"status counts inside subdir = {th.status_counts(ax)}" # The shared chrome is unaffected by the directory change. assert th.sidebar_outline(ax) is not None, "sidebar disappeared while descending" b_found, b_enabled, _ = th.button_state(ax, "Back") assert b_found and b_enabled, \ f"'Back' should be enabled after navigating (found={b_found}, enabled={b_enabled})"
# ─────────────────────────────────────────────────────────────────────────────# SHAPE DELTAS — extra windows, pop-up menus and console blocks.# ─────────────────────────────────────────────────────────────────────────────class TestExtraSurfaceShape:
@pytest.mark.rb(depth=2, jump_kind="reach", expect="grid item context menu > Get Info opens a 2nd window titled " "'alpha.txt Info' containing the label 'Info pane'") def test_get_info_window_opens_with_info_pane(self, ax): assert th.rb_enter_fixtures_gui(ax), "could not reach the rbtest fixture grid" before_windows = len(ax.find(role="window", max_results=8, max_depth=1)) assert before_windows == 1, f"expected 1 window before Get Info, got {before_windows}" before = kit.rb_showing(ax)
assert th.rb_reach_get_info(ax, "alpha.txt"), \ "context menu > 'Get Info' on alpha.txt did not activate" after = kit.rb_showing(ax) assert kit.rb_reach(before, after, target="Info pane"), \ "no 'Info pane' element appeared — the Get Info window did not open"
windows = ax.find(role="window", max_results=8, max_depth=1) assert len(windows) == before_windows + 1, \ f"window count {before_windows} -> {len(windows)} (expected +1 for the Info window)" assert _titled_window(ax, "alpha.txt Info"), \ f"no window titled 'alpha.txt Info'; titles = {th.window_titles(ax)}" info_win = [w for w in windows if str(ax.get(w.id, ["AXTitle"]).get("AXTitle") or "") == "alpha.txt Info"][0] info_labels = [str(e.value or e.name or "") for e in ax.find(role="label", root_id=info_win.id, max_results=20, max_depth=10)] assert "Info pane" in info_labels, \ f"Get Info window body labels = {info_labels}" assert "" in th.window_titles(ax), \ f"the main (untitled) window disappeared; titles = {th.window_titles(ax)}"
@pytest.mark.rb(depth=2, jump_kind="reach", expect="toolbar path picker opens a menu whose items are the path chain " "'rbtest' -> its parent -> ... (menu_item|<parent> appears)") def test_path_picker_menu_lists_path_chain(self, ax): assert th.rb_enter_fixtures(ax), \ "could not cd into the rbtest fixture directory from the CLI" parent = th.rbtest_parent_name() before = kit.rb_showing(ax)
components = th.rb_reach_path_menu(ax) after = kit.rb_showing(ax) assert kit.rb_reach(before, after, target="menu_item|" + parent), \ f"no menu item for the parent component {parent!r} appeared after pressing the picker"
assert components[:2] == [th.RBTEST_NAME, parent], \ f"path menu should start with the current dir then its parent, got {components[:3]}" assert len(components) >= 3, \ f"path menu should list the whole ancestor chain, got only {components}" # Strictly ancestor-walking: every listed component is a real ancestor name of the # fixture dir, in the same (leaf -> root) order, and listed once. upwards = list(reversed([p for p in th.rbtest_dir().split(os.sep) if p])) known = [c for c in components if c in upwards] assert len(known) >= 3, \ f"path menu components {components} do not match the ancestor chain {upwards}" positions = [upwards.index(c) for c in known] assert positions == sorted(positions), \ f"path menu {components} is not ordered leaf -> root along {upwards}" assert len(set(components)) == len(components), \ f"path menu components are not de-duplicated: {components}" th.dismiss_menus(ax)
@pytest.mark.rb(depth=2, jump_kind="reach", expect="console entry pop-out button opens a 2nd window titled 'echo popme' " "(window count 1 -> 2)") def test_console_entry_pops_out_into_own_window(self, ax): assert th.rb_enter_cli(ax), "could not reach the CLI surface" th.run_command(ax, "echo popme") before_windows = len(ax.find(role="window", max_results=8, max_depth=1)) assert before_windows == 1, f"expected 1 window before the pop-out, got {before_windows}" assert th.console_commands(ax) == ["echo popme"], \ f"console should hold exactly the one 'echo popme' entry, got {th.console_commands(ax)}" popouts = ax.find(role="button", name=th.POPOUT_NAME, max_results=10, max_depth=24) assert popouts, \ f"the console entry has no {th.POPOUT_NAME!r} pop-out button" before = kit.rb_showing(ax)
assert th.rb_reach_popout(ax), "the console entry's pop-out button did not activate" after = kit.rb_showing(ax) assert kit.rb_reach(before, after, target="echo popme"), \ "no new 'echo popme' surface appeared — the pop-out window did not open"
windows = ax.find(role="window", max_results=8, max_depth=1) assert len(windows) == before_windows + 1, \ f"window count {before_windows} -> {len(windows)} (expected +1 for the pop-out)" titles = th.window_titles(ax) assert any(t == "echo popme" or t.startswith("echo popme —") for t in titles), \ f"no pop-out window titled 'echo popme'; titles = {titles}" assert "" in titles, f"the main (untitled) window disappeared; titles = {titles}"
@pytest.mark.rb(depth=1, jump_kind="value", expect="running 'pwd' in the CLI adds one console block: prompt '<dir> % ', " "command label 'pwd', an output label and one pop-out button (0 -> 1)") def test_command_adds_one_console_block(self, ax): assert th.rb_enter_cli(ax), "could not reach the CLI surface" before_popouts = ax.find(role="button", name=th.POPOUT_NAME, max_results=10, max_depth=24) assert len(before_popouts) == 0, \ f"fresh CLI already shows {len(before_popouts)} console entries" assert th.console_commands(ax) == [], \ f"fresh CLI console already lists {th.console_commands(ax)}"
th.run_command(ax, "pwd")
assert kit.rb_value(th.console_commands(ax), ["pwd"]), \ f"console entries after running pwd = {th.console_commands(ax)}" after_popouts = ax.find(role="button", name=th.POPOUT_NAME, max_results=10, max_depth=24) assert len(after_popouts) > len(before_popouts), \ f"pop-out buttons {len(before_popouts)} -> {len(after_popouts)}: the console block " \ f"grew no {th.POPOUT_NAME!r} button" assert len(after_popouts) <= 2, \ f"one command produced {len(after_popouts)} pop-out buttons — expected one per entry" texts = th.all_texts(ax) assert any(t.endswith(" % ") for t in texts), \ f"no console-entry prompt label ending in ' % ' among {texts[:12]}" assert "pwd" in texts, f"no 'pwd' command label in the console; texts = {texts[:12]}" assert th.command_output(ax, "pwd"), \ "the 'pwd' console block carries no output label" # The CLI chrome is unchanged by running a command. assert th.pane_states(ax) == {"Console": 1, "Errors": 0}, \ f"pane segments after running a command = {th.pane_states(ax)}" assert th.prompt_label_value(ax), "the command prompt label disappeared after a command"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561"""AX TEXT-content tests for Terminader (Finder <-> Terminal hybrid file browser).
Covers the recon `## TEXT` section T1-T22 plus the measured`interaction -> text change` table: every assertion names the EXACT string thereference app produced.
pytest only: `Test*` classes, methods take the `ax` fixture (conftest launches theapp fresh per test and hands over an AXHelper). No argparse, no __main__, noself-written results JSON — the runner scores via pytest and the@pytest.mark.rb(...) declarations.
Non-deterministic text is NEVER asserted: relative-date labels ('3 sec'), thefree-space figure ('226.675 GB'), the literal account name (th.home_dir_name()is used instead) and home-directory item counts (the fixture dir is used)."""
from __future__ import annotations
import osimport reimport sysimport time
import pytest
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import terminader_helpers as th # noqa: E402 shared portable driverimport rb_testgen_kit as kit # noqa: E402 depth/jump declaration kit
RESULTS_DIR = os.environ.get("RESULTS_DIR", ".")
EM_DASH = "—" # '—' U+2014, used by the pop-out titleSEARCH_PLACEHOLDER = th.SEARCH_PLACEHOLDER # '🔍 Search'MENU_BAR_TITLES = ["Terminader", "File", "Edit", "View", "Window", "Help"]
# ── screenshot assertion (delegates to the shared helper, with an inline fallback) ──def screenshot_assert(test_name, description, results_dir=RESULTS_DIR): """Capture the screen and record what a VLM judge should read in it.""" results_dir = results_dir or RESULTS_DIR try: th.screenshot_assert(test_name, description, results_dir) return except Exception: pass import json import subprocess ss_dir = os.path.join(results_dir, "screenshots") os.makedirs(ss_dir, exist_ok=True) ss_path = os.path.join(ss_dir, f"{test_name}.png") try: subprocess.run(["screencapture", "-x", ss_path], timeout=5) except Exception: pass assertions_file = os.path.join(ss_dir, "assertions.json") assertions = {} if os.path.exists(assertions_file): try: with open(assertions_file) as f: assertions = json.load(f) except Exception: assertions = {} assertions[f"{test_name}.png"] = description with open(assertions_file, "w") as f: json.dump(assertions, f, indent=2)
# ── small, read-only text utilities (no re-implementation of drivers) ────────def _ready(ax): """Reveal the app's window before any window-dependent check.
Terminader is a regular (non-LSUIElement) app whose main window is on screen immediately, so this is a no-op there — but a recreation may reveal its window through a different path, so ask ax_helpers to do it when nothing is showing. """ try: if not ax.find(role="window", max_results=1, max_depth=2): ax.ensure_ui_visible() time.sleep(1.0) except Exception: pass
def _heading_texts(ax, texts=None): """Sidebar section headings. Read from role=heading (AXHeading) first and fall back to every static text, because a different UI framework may expose a section header as plain static text.""" out = [] try: for el in ax.find(role="heading", max_results=40, max_depth=24): v = el.name or el.value if v: out.append(str(v)) except Exception: pass return out + (list(texts) if texts is not None else th.all_texts(ax))
def _button_names(ax): """AXTitle/AXDescription of every button — semantic locator, never an index.""" return [str(e.name) for e in ax.find(role="button", max_results=80, max_depth=22) if e.name]
def _radio_names(ax): return [str(e.name) for e in ax.find(role="radio", max_results=8, max_depth=22) if e.name]
def _placeholder(ax, el): return ax.get(el.id, ["AXPlaceholderValue"]).get("AXPlaceholderValue")
def _label_stats(ax): """(labels_with_text, labels_total) — text accessibility coverage.""" els = ax.find(role="label", max_results=400, max_depth=24) with_text = [e for e in els if str(e.value or e.name or "").strip()] return len(with_text), len(els)
# ══════════════════════════════════════════════════════════════════════════════class TestSidebarText: """T1 / T2 / T3 / T7 / T20 — fixed vocabulary and its disappearance."""
@pytest.mark.rb(depth=0, jump_kind="value", expect="sidebar headings 'Favorites'/'iCloud'/'Locations', labels " "'iCloud Drive'/'Network', 7 favourite buttons, menu bar " "Terminader/File/Edit/View/Window/Help") def test_sidebar_vocabulary_and_menu_bar_titles(self, ax): _ready(ax) texts = th.all_texts(ax) headings = _heading_texts(ax, texts) for want in th.SIDEBAR_HEADINGS: # T1 got = next((t for t in headings if t == want), None) assert kit.rb_value(got, want), ( f"sidebar heading {want!r} not found; observed heading texts=" f"{headings[:20]}") for want in th.SIDEBAR_STATIC: # T2 got = next((t for t in texts if t == want), None) assert kit.rb_value(got, want), ( f"sidebar label {want!r} not found; observed texts={texts[:25]}") names = _button_names(ax) favourites = list(th.SIDEBAR_FAVORITES) + [th.home_dir_name()] # T3 assert len(favourites) == 7, f"expected 7 favourites, listed {favourites}" for want in favourites: got = next((n for n in names if n == want), None) assert kit.rb_value(got, want), ( f"sidebar favourite button {want!r} not found; observed button names=" f"{names}") bar = th.menu_bar_titles(ax) # T20 for want in MENU_BAR_TITLES: got = next((t for t in bar if t == want), None) assert kit.rb_value(got, want), ( f"menu-bar title {want!r} missing; observed menu bar={bar}") # text-accessibility coverage: labels that carry content vs. those that don't. # (The toolbar title area is a legitimately empty label, so don't demand 100 %.) with_text, total = _label_stats(ax) without = total - with_text assert with_text >= 5, ( f"only {with_text} of {total} AXStaticText nodes carry text; " f"observed texts={texts[:25]}") assert with_text >= without, ( f"more empty labels ({without}) than labels with text ({with_text}); " f"observed texts={texts[:25]}") readable = [t for t in texts if t.strip()] assert len(readable) >= len(th.SIDEBAR_STATIC) + 1, ( f"only {len(readable)} readable text value(s) on the home surface " f"({with_text} of {total} labels carry text); observed texts={texts[:25]}") # character count of every observed vocabulary string == its real length for want in th.SIDEBAR_HEADINGS + th.SIDEBAR_STATIC: observed = next((t for t in headings if t == want), "") assert len(observed) == len(want) and observed.strip() == observed, ( f"{want!r} should be {len(want)} chars with no padding, " f"observed {observed!r} ({len(observed)} chars)") screenshot_assert( "text_sidebar_vocabulary", "Terminader's left sidebar lists the section headings Favorites, iCloud and " "Locations, the rows Desktop, Documents, Downloads, Movies, Music, Pictures " "and the user's home folder, plus the static labels 'iCloud Drive' and " "'Network'; the toolbar above shows back/forward chevrons, a path pop-up " "button and a terminal icon.", RESULTS_DIR)
@pytest.mark.rb(depth=0, jump_kind="value", expect="after Hide Sidebar the toolbar button reads 'Show Sidebar' and " "'iCloud Drive'/'Network'/'Favorites' are gone") def test_hide_sidebar_replaces_sidebar_text(self, ax): _ready(ax) before_texts = _heading_texts(ax) # headings are AXHeading, not AXStaticText before_names = _button_names(ax) assert "Hide Sidebar" in before_names, ( f"'Hide Sidebar' toolbar button missing; observed buttons={before_names}") found, _en, help_before = th.button_state(ax, "Hide Sidebar") # T7 (before) assert found, f"Hide Sidebar button not found; observed buttons={before_names}" assert kit.rb_value(help_before, "Hide Sidebar"), ( f"Hide Sidebar tooltip expected 'Hide Sidebar', observed AXHelp=" f"{help_before!r}") assert th.press_button(ax, "Hide Sidebar"), "could not press 'Hide Sidebar'" time.sleep(0.8) after_texts = _heading_texts(ax) after_names = _button_names(ax) still = [t for t in th.SIDEBAR_STATIC + th.SIDEBAR_HEADINGS if t in after_texts] assert not still, ( f"sidebar text still present after Hide Sidebar: {still}; " f"observed texts={after_texts[:25]}") got = next((n for n in after_names if n == "Show Sidebar"), None) assert kit.rb_value(got, "Show Sidebar"), ( # T7 (after) f"toolbar button did not become 'Show Sidebar'; observed buttons=" f"{after_names}") assert "Hide Sidebar" not in after_names, ( f"'Hide Sidebar' still listed after pressing it; observed={after_names}") assert after_texts != before_texts, ( f"text did not change at all; observed={after_texts[:25]}")
# ══════════════════════════════════════════════════════════════════════════════class TestToolbarAndCLIChromeText: """T4 / T5 / T6 / T8 / T9 — tooltip (AXHelp) strings and CLI chrome text."""
@pytest.mark.rb(depth=1, jump_kind="value", expect="Back AXHelp 'See folders you viewed previously'; toggle AXHelp " "'Switch to Terminal' -> 'Switch to graphical interface'") def test_toolbar_help_text_flips_with_mode(self, ax): _ready(ax) found, _en, back_help = th.button_state(ax, "Back") # T4 assert found, "Back button not found in the toolbar" assert kit.rb_value(back_help, th.BACK_HELP), ( f"Back AXHelp expected {th.BACK_HELP!r}, observed {back_help!r}") f_gui, _e, help_gui = th.button_state(ax, th.TOGGLE_NAME_GUI) # T5 (GUI face) assert f_gui, f"mode toggle {th.TOGGLE_NAME_GUI!r} not found in GUI mode" assert kit.rb_value(help_gui, th.TOGGLE_HELP_GUI), ( f"GUI-mode toggle AXHelp expected {th.TOGGLE_HELP_GUI!r}, " f"observed {help_gui!r}") assert th.rb_enter_cli(ax), "could not cross into the CLI surface" f_cli, _e2, help_cli = th.button_state(ax, th.TOGGLE_NAME_CLI) # T5 (CLI face) assert f_cli, f"mode toggle {th.TOGGLE_NAME_CLI!r} not found in CLI mode" assert kit.rb_value(help_cli, th.TOGGLE_HELP_CLI), ( f"CLI-mode toggle AXHelp expected {th.TOGGLE_HELP_CLI!r}, " f"observed {help_cli!r}") assert help_cli != help_gui, ( f"toggle tooltip did not change with the mode; observed {help_cli!r} twice")
@pytest.mark.rb(depth=1, jump_kind="value", expect="paste button AXHelp 'Paste selected items', search placeholder " "'🔍 Search', segments 'Console'/'Errors'") def test_cli_chrome_text_paste_search_and_panes(self, ax): _ready(ax) assert th.rb_enter_cli(ax), "could not cross into the CLI surface" found, _en, paste_help = th.button_state(ax, th.PASTE_NAME) # T6 assert found, f"paste button {th.PASTE_NAME!r} not found on the CLI surface" assert kit.rb_value(paste_help, th.PASTE_HELP), ( f"paste AXHelp expected {th.PASTE_HELP!r}, observed {paste_help!r}") tf = th.search_field(ax) assert tf is not None, "console filter AXTextField not found on the CLI surface" placeholder = _placeholder(ax, tf) # T8 assert kit.rb_value(placeholder, SEARCH_PLACEHOLDER), ( f"search placeholder expected {SEARCH_PLACEHOLDER!r}, " f"observed {placeholder!r}") radios = _radio_names(ax) # T9 for want in th.CLI_PANES: got = next((r for r in radios if r == want), None) assert kit.rb_value(got, want), ( f"CLI segment {want!r} missing; observed radio names={radios}")
# ══════════════════════════════════════════════════════════════════════════════class TestStatusBarAndPathText: """T10 / T11 / T21 — status-bar grammar, path-picker value, grid name labels."""
@pytest.mark.rb(depth=1, jump_kind="value", expect="path picker AXValue '<home> ' -> 'Documents ' -> 'rbtest ' " "(trailing space kept)") def test_path_picker_value_keeps_trailing_space(self, ax): _ready(ax) home_expected = th.home_dir_name() + " " home_value = th.path_popup_value(ax) # T11 (home) assert kit.rb_value(home_value, home_expected), ( f"path picker at launch expected {home_expected!r}, observed {home_value!r}") assert home_value.endswith(" ") and len(home_value) == len(home_value.strip()) + 1, ( f"trailing space lost from the path picker value: {home_value!r}") assert th.press_button(ax, "Documents"), "could not press sidebar 'Documents'" time.sleep(1.2) docs_value = th.path_popup_value(ax) assert kit.rb_value(docs_value, "Documents "), ( f"after pressing Documents expected 'Documents ', observed {docs_value!r}") assert docs_value != home_value, ( f"path picker text did not change; observed {docs_value!r}") assert th.rb_enter_fixtures_gui(ax), "could not reach the fixture directory grid" fixture_value = th.path_popup_value(ax) # T11 (fixture dir) assert kit.rb_value(fixture_value, "rbtest "), ( f"in the fixture directory expected 'rbtest ', observed {fixture_value!r}") assert fixture_value.endswith(" ") and fixture_value != docs_value, ( f"observed path picker value {fixture_value!r} (was {docs_value!r})")
@pytest.mark.rb(depth=1, jump_kind="value", expect="grid names alpha.txt/beta.txt/gamma.txt/readme.md/subdir; status " "'5 items, … available' -> '1 of 5 selected, … available'") def test_fixture_grid_names_and_status_bar_selection(self, ax): _ready(ax) assert th.rb_enter_fixtures_gui(ax), "could not reach the fixture directory grid" names = th.grid_names(ax) # T21 assert kit.rb_value(names, th.RBTEST_ENTRIES), ( f"grid name labels expected {th.RBTEST_ENTRIES}, observed {names}") before = th.status_text(ax) # T10 (plural) assert re.match(r"^5 items, .* available$", before) and kit.rb_value( before, "5 items,"), ( f"status bar expected to match '^5 items, .* available$', observed {before!r}") assert th.click_file(ax, "beta.txt"), "could not click grid item 'beta.txt'" time.sleep(0.4) after = th.status_text(ax) # T10 (selection) ok = bool(re.match(r"^1 of 5 selected, .* available$", after)) and kit.rb_value( after, "1 of 5 selected,") assert ok, ( f"status bar after selecting beta.txt expected to match " f"'^1 of 5 selected, .* available$', observed {after!r}") assert after != before, f"status text did not change; observed {after!r}" screenshot_assert( "text_status_bar_selection", "The Terminader icon grid shows four grey document icons labelled alpha.txt, " "beta.txt, gamma.txt, readme.md and one cyan folder labelled subdir; " "beta.txt's name is highlighted on a blue rounded background and the status " "bar under the grid reads '1 of 5 selected, <free space> available'.", RESULTS_DIR)
@pytest.mark.rb(depth=2, jump_kind="value", expect="inside subdir the status bar reads the SINGULAR '1 item, … " "available' and the path picker 'subdir '") def test_subdir_status_bar_is_singular(self, ax): _ready(ax) assert th.rb_enter_fixtures_gui(ax), "could not reach the fixture directory grid" before = th.status_text(ax) assert re.match(r"^5 items, .* available$", before), ( f"fixture-dir status expected '^5 items, .* available$', observed {before!r}") assert th.rb_enter_directory(ax, "subdir"), "could not descend into 'subdir'" after = th.status_text(ax) # T10 (singular) ok = bool(re.match(r"^1 item, .* available$", after)) and kit.rb_value( after, "1 item,") assert ok, ( f"status bar in subdir expected to match '^1 item, .* available$' " f"(singular 'item'), observed {after!r}") assert after != before, f"status text did not change; observed {after!r}" picker = th.path_popup_value(ax) # T11 assert kit.rb_value(picker, "subdir "), ( f"path picker in subdir expected 'subdir ', observed {picker!r}")
# ══════════════════════════════════════════════════════════════════════════════class TestCLIPromptText: """T12 / T13 — the green prompt label and the command-line label."""
@pytest.mark.rb(depth=2, jump_kind="value", expect="prompt label '<home> Arrow Right Circle ' -> " "'rbtest Arrow Right Circle ' after cd into the fixture dir") def test_cli_prompt_label_tracks_directory(self, ax): _ready(ax) assert th.rb_enter_cli(ax), "could not cross into the CLI surface" home_prompt = th.prompt_label_value(ax) # T12 (home) expected_home = f"{th.home_dir_name()} {th.PROMPT_SUFFIX}" assert kit.rb_value(home_prompt, expected_home), ( f"CLI prompt expected {expected_home!r}, observed {home_prompt!r}") assert th.rb_enter_fixtures(ax), "could not cd into the fixture directory" fixture_prompt = th.prompt_label_value(ax) # T12 (fixture dir) expected_fixture = f"rbtest {th.PROMPT_SUFFIX}" assert kit.rb_value(fixture_prompt, expected_fixture), ( f"CLI prompt after cd expected {expected_fixture!r}, " f"observed {fixture_prompt!r}") assert fixture_prompt != home_prompt, ( f"prompt did not track the directory; observed {fixture_prompt!r}") screenshot_assert( "text_cli_prompt", "Terminader's Terminal (CLI) surface: a paste-document button, a " "Console/Errors segmented control with Console selected, a '🔍 Search' " "field, and at the bottom left a green 'rbtest' prompt followed by an " "arrow-right-circle glyph and a yellow block cursor.", RESULTS_DIR)
@pytest.mark.rb(depth=1, jump_kind="value", expect="command-line label ' ' when empty, 'pwd ' after typing pwd") def test_command_line_label_empty_then_typed(self, ax): _ready(ax) assert th.rb_enter_cli(ax), "could not cross into the CLI surface" empty = th.command_line_text(ax) # T13 (empty) assert kit.rb_value(empty, " "), ( f"empty command line expected ' ' (the block cursor), observed {empty!r}") assert len(empty) == 1, f"command line should be 1 char wide, observed {empty!r}" th.activate(ax) th.cg_type("pwd") # typed, deliberately NOT submitted time.sleep(0.6) typed = th.command_line_text(ax) # T13 (typed) assert kit.rb_value(typed, "pwd "), ( f"after typing 'pwd' the command line should read 'pwd ', observed {typed!r}") assert typed != empty, f"command-line text did not change; observed {typed!r}" th.clear_command_line(ax)
# ══════════════════════════════════════════════════════════════════════════════class TestConsoleEntryText: """T14 / T15 / T16 / T17 / T22 — console-entry prompt, command, output, status."""
@pytest.mark.rb(depth=1, jump_kind="value", expect="console entry '<home> % ' + commands ['echo aaa','pwd'] + output " "'aaa'/home path; filter 'pwd' leaves only ['pwd']") def test_console_entry_prompt_command_and_output(self, ax): _ready(ax) assert th.rb_enter_cli(ax), "could not cross into the CLI surface" th.run_command(ax, "echo aaa") th.run_command(ax, "pwd") texts = th.all_texts(ax) prompts = [t for t in texts if t.endswith(" % ")] # T14 expected_prompt = f"{th.home_dir_name()} % " assert prompts and kit.rb_value(prompts[0], expected_prompt), ( f"console entry prompt expected {expected_prompt!r}, observed {prompts!r}") cmds = th.console_commands(ax) # T15 assert kit.rb_value(cmds, ["echo aaa", "pwd"]), ( f"console command labels expected ['echo aaa', 'pwd'], observed {cmds}") out_echo = th.command_output(ax, "echo aaa") # T16 assert kit.rb_value(out_echo, "aaa"), ( f"output of 'echo aaa' expected 'aaa', observed {out_echo!r}") out_pwd = th.command_output(ax, "pwd") # T16 assert kit.rb_value(out_pwd, os.path.expanduser("~")), ( f"output of 'pwd' expected the home path, observed {out_pwd!r}") th.type_in_search(ax, "pwd") # interaction -> text change: console filters filtered = th.console_commands(ax) assert kit.rb_value(filtered, ["pwd"]), ( f"after filtering on 'pwd' the console should list only ['pwd'], " f"observed {filtered}") assert filtered != cmds, f"filter changed nothing; observed {filtered}"
@pytest.mark.rb(depth=1, jump_kind="value", expect="console status label '127' for an unknown command, no status " "label at all for a successful one") def test_status_label_127_and_absent_when_ok(self, ax): _ready(ax) assert th.rb_enter_cli(ax), "could not cross into the CLI surface" th.run_command(ax, "echo ok") ok_texts = th.all_texts(ax) stray = [t for t in ok_texts if t.strip().isdigit()] # T17 (absent) assert not stray, ( f"a successful command must show no status label, observed digit labels=" f"{stray} in {ok_texts}") th.run_command(ax, "nosuchcommandxyz") bad_texts = th.all_texts(ax) status = [t for t in bad_texts if t.strip().isdigit()] # T17 ('127') assert status and kit.rb_value(status[0], "127"), ( f"unknown command should show status label '127', observed digit labels=" f"{status} in {bad_texts}") cmd_label = next((t for t in bad_texts if t == "nosuchcommandxyz"), None) assert kit.rb_value(cmd_label, "nosuchcommandxyz"), ( f"console entry command label missing; observed texts={bad_texts}")
@pytest.mark.rb(depth=1, jump_kind="value", expect="`ls` markdown table headers Permissions/Links/Owner/Group/Size/" "Date/Name") def test_ls_markdown_table_headers(self, ax): _ready(ax) assert th.rb_enter_fixtures(ax), "could not cd into the fixture directory" th.run_command(ax, "ls") texts = th.all_texts(ax) missing = [h for h in th.LS_TABLE_HEADERS if h not in texts] # T22 assert not missing, ( f"`ls` table headers missing {missing}; observed texts={texts[:40]}") for want in th.LS_TABLE_HEADERS: got = next((t for t in texts if t == want), None) assert kit.rb_value(got, want), ( f"`ls` header {want!r} not rendered; observed texts={texts[:40]}")
@pytest.mark.rb(depth=2, jump_kind="value", expect="Errors pane body 'This is stderr' replaces the Console pane's " "'This is stdout…' after test_out 3") def test_errors_pane_text_replaces_stdout(self, ax): _ready(ax) assert th.rb_enter_cli(ax), "could not cross into the CLI surface" th.run_command(ax, "test_out 3") before = th.text_snapshot(ax) # Counter of every text, tree order stdout_before = [t for t in before if t.startswith("This is stdout")] assert stdout_before, ( f"Console pane should show 'This is stdout…'; observed texts=" f"{sorted(before)[:30]}") assert th.rb_enter_pane(ax, "Errors"), "could not select the 'Errors' pane" after = th.text_snapshot(ax) stderr_after = next((t for t in after if t == "This is stderr"), None) assert kit.rb_value(stderr_after, "This is stderr"), ( f"Errors pane body expected 'This is stderr', observed texts=" f"{sorted(after)[:30]}") assert not [t for t in after if t.startswith("This is stdout")], ( f"stdout text must disappear when the Errors pane is selected; observed=" f"{sorted(after)[:30]}") assert after != before, f"pane switch changed no text; observed {sorted(after)[:30]}" status = [t for t in after if t.strip() == "3"] # T17 ('3') assert status and kit.rb_value(status[0], "3"), ( f"the entry's status label should read '3'; observed digit labels=" f"{[t for t in after if t.strip().isdigit()]}")
# ══════════════════════════════════════════════════════════════════════════════class TestSecondaryWindowText: """T18 / T19 — Get Info window text and console-entry pop-out window titles."""
@pytest.mark.rb(depth=2, jump_kind="value", expect="Get Info window AXTitle 'gamma.txt Info' with body label " "'Info pane'") def test_get_info_window_title_and_body(self, ax): _ready(ax) assert th.rb_enter_fixtures_gui(ax), "could not reach the fixture directory grid" before_titles = th.window_titles(ax) assert th.rb_reach_get_info(ax, "gamma.txt"), ( f"could not open Get Info for gamma.txt; window titles={before_titles}") titles = th.window_titles(ax) # T18 (title) got = next((t for t in titles if t == "gamma.txt Info"), None) assert kit.rb_value(got, "gamma.txt Info"), ( f"Get Info window title expected 'gamma.txt Info', observed titles={titles}") texts = th.all_texts(ax) # T18 (body) body = next((t for t in texts if t == "Info pane"), None) assert kit.rb_value(body, "Info pane"), ( f"Get Info body label expected 'Info pane', observed texts={texts[:30]}") assert titles != before_titles, ( f"no new window title appeared; observed {titles}") screenshot_assert( "text_get_info_window", "A second, small Terminader window titled 'gamma.txt Info' is in front of " "the main window; its only content is the text 'Info pane'.", RESULTS_DIR)
@pytest.mark.rb(depth=2, jump_kind="value", expect="pop-out window AXTitle 'echo popme' (the command verbatim)") def test_popout_window_title_is_the_command(self, ax): _ready(ax) assert th.rb_enter_cli(ax), "could not cross into the CLI surface" th.run_command(ax, "echo popme") before_titles = th.window_titles(ax) assert th.rb_reach_popout(ax), ( f"could not press the console entry pop-out button; titles={before_titles}") titles = th.window_titles(ax) # T19 (status 0) got = next((t for t in titles if t == "echo popme"), None) assert kit.rb_value(got, "echo popme"), ( f"pop-out window title expected 'echo popme', observed titles={titles}") assert titles != before_titles, ( f"no pop-out window title appeared; observed {titles}")
@pytest.mark.rb(depth=2, jump_kind="value", expect="failing command pop-out title 'test_out 3 — 3' with the EM DASH " "U+2014 between command and exit status") def test_popout_window_title_shows_em_dash_status(self, ax): _ready(ax) assert th.rb_enter_cli(ax), "could not cross into the CLI surface" th.run_command(ax, "test_out 3") before_titles = th.window_titles(ax) assert th.rb_reach_popout(ax), ( f"could not press the console entry pop-out button; titles={before_titles}") titles = th.window_titles(ax) # T19 (status != 0) expected = f"test_out 3 {EM_DASH} 3" got = next((t for t in titles if t == expected), None) assert kit.rb_value(got, expected), ( f"failing pop-out title expected {expected!r} (em dash U+2014), " f"observed titles={titles}") assert EM_DASH in (got or ""), ( f"title must join command and status with the EM DASH U+2014, " f"observed {got!r}") assert titles != before_titles, ( f"no pop-out window title appeared; observed {titles}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748{ "ax_total": 102, "vlm_total": 22, "ax_by_lane": { "test_ax_buttons.py": 15, "test_ax_computation.py": 26, "test_ax_menus.py": 14, "test_ax_states.py": 17, "test_ax_structure.py": 14, "test_ax_text.py": 16 }, "vlm_by_dir": { "buttons": 2, "computation": 5, "menus": 4, "states": 3, "structure": 4, "text": 4 }, "vlm_names": [ "buttons_mode_toggle_cli.png", "buttons_sidebar_hidden.png", "computation_echo_command_results.png", "computation_errors_pane_stderr.png", "computation_failed_command_status.png", "computation_ls_markdown_table.png", "computation_markdown_file_render.png", "menus_context_menu.png", "menus_get_info_window.png", "menus_path_menu.png", "menus_two_windows.png", "states_errors_pane.png", "states_selection_highlight.png", "states_sidebar_hidden.png", "structure_cli_surface.png", "structure_fixture_grid.png", "structure_gate_window_toolbar_sidebar.png", "structure_sidebar_hidden.png", "text_cli_prompt.png", "text_get_info_window.png", "text_sidebar_vocabulary.png", "text_status_bar_selection.png" ], "frozen_at": "stage2_finalize", "vlm_pruned_offline_rejudge": [ "buttons_paste_selection_badge.png" ]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753"""verifier_helpers.py — High-level AX testing patterns for macOS app verification.
v6 core library. Encodes all robust testing patterns as reusable functionsso verifier agents call high-level APIs instead of building from scratch.
Depends on: ax_helpers.py (AXHelper class)"""
import datetimeimport osimport reimport signalimport subprocessimport timefrom collections import Counter
# ---------------------------------------------------------------------------# Key codes (macOS virtual key codes)# ---------------------------------------------------------------------------KC_LEFT_ARROW = 123KC_RIGHT_ARROW = 124KC_UP_ARROW = 126KC_DOWN_ARROW = 125KC_SPACE = 49KC_RETURN = 36KC_TAB = 48KC_ESCAPE = 53KC_Q = 12KC_W = 13
# ---------------------------------------------------------------------------# Bilingual keyword constants# ---------------------------------------------------------------------------
QUIT_KEYWORDS = [ "quit", "exit", "close app", "terminate", "退出", "关闭", "结束",]UPDATE_KEYWORDS = [ "update", "updates", "check for update", "check for updates", "check update", "software update", "更新", "检查更新", "软件更新",]CALENDAR_KEYWORDS = [ "calendar", "calendars", "event", "events", "show calendar", "hide calendar", "toggle calendar", "日历", "事件", "日程",]HOLIDAY_KEYWORDS = [ "holiday", "holidays", "public holiday", "festival", "假日", "节假日", "节日", "假期", "公共假日",]APPEARANCE_KEYWORDS = [ "appearance", "theme", "dark", "light", "system", "dark mode", "light mode", "外观", "主题", "深色", "浅色", "暗色", "亮色",]LOGIN_KEYWORDS = [ "login", "launch at login", "start at login", "open at login", "launch at startup", "start at startup", "auto start", "autostart", "登录时启动", "开机启动", "自动启动", "启动时打开",]ABOUT_KEYWORDS = [ "about", "info", "information", "version", "关于", "版本", "信息",]TODAY_KEYWORDS = [ "today", "go to today", "return to today", "current", "now", "今天", "今日", "当前",]
NAV_PREV_KEYWORDS = [ "prev", "previous", "back", "left", "earlier", "上一", "前一", "上个", "前", "◀", "←", "❮", "◁", "⬅",]NAV_NEXT_KEYWORDS = [ "next", "forward", "right", "later", "下一", "后一", "下个", "后", "▶", "→", "❯", "▷", "➡",]
WEEKDAY_SYMBOLS = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "SU", "MO", "TU", "WE", "TH", "FR", "SA", "Su", "Mo", "Tu", "We", "Th", "Fr", "S", "M", "T", "W", "F", "日", "一", "二", "三", "四", "五", "六",}
MONTH_YEAR_PATTERN = re.compile( r"(" r"[A-Z][a-z]{2,8}\s+\d{4}" r"|\d{4}\s*[年/\-\.]\s*\d{1,2}\s*[月]?" r"|\d{1,2}\s*[月]\s*\d{4}" r"|\d{4}\s*[年]" r"|[A-Z][a-z]{2,8}\s*\d{4}" r")", re.UNICODE,)
LUNAR_KEYWORDS = [ "初", "十", "廿", "卅", "正月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "冬月", "腊月",]
SOLAR_TERM_KEYWORDS = [ "立春", "雨水", "惊蛰", "春分", "清明", "谷雨", "立夏", "小满", "芒种", "夏至", "小暑", "大暑", "立秋", "处暑", "白露", "秋分", "寒露", "霜降", "立冬", "小雪", "大雪", "冬至", "小寒", "大寒",]
# ---------------------------------------------------------------------------# Low-level: Key sending via CGEvent# ---------------------------------------------------------------------------
def send_key(keycode, modifiers=None): """Send a keyboard event via CGEvent API. modifiers: list of "cmd", "shift", "alt", "ctrl".""" import Quartz src = Quartz.CGEventSourceCreate(Quartz.kCGEventSourceStateHIDSystemState) down = Quartz.CGEventCreateKeyboardEvent(src, keycode, True) up = Quartz.CGEventCreateKeyboardEvent(src, keycode, False) flags = 0 if modifiers: flag_map = { "cmd": Quartz.kCGEventFlagMaskCommand, "shift": Quartz.kCGEventFlagMaskShift, "alt": Quartz.kCGEventFlagMaskAlternate, "ctrl": Quartz.kCGEventFlagMaskControl, } for mod in modifiers: flags |= flag_map.get(mod, 0) Quartz.CGEventSetFlags(down, flags) Quartz.CGEventSetFlags(up, flags) Quartz.CGEventPost(Quartz.kCGHIDEventTap, down) Quartz.CGEventPost(Quartz.kCGHIDEventTap, up) time.sleep(0.3)
def click_at(x, y): """Click at absolute screen coordinates via CGEvent.""" import Quartz point = Quartz.CGPointMake(x, y) down = Quartz.CGEventCreateMouseEvent( None, Quartz.kCGEventLeftMouseDown, point, Quartz.kCGMouseButtonLeft) up = Quartz.CGEventCreateMouseEvent( None, Quartz.kCGEventLeftMouseUp, point, Quartz.kCGMouseButtonLeft) Quartz.CGEventPost(Quartz.kCGHIDEventTap, down) time.sleep(0.05) Quartz.CGEventPost(Quartz.kCGHIDEventTap, up) time.sleep(0.3)
# ---------------------------------------------------------------------------# Panel detection: find and manage UI panels/windows# ---------------------------------------------------------------------------
def find_panel_container(ax, min_texts=3, max_depth=12): """Find the app's main panel container.
A popover/sheet is accepted by ROLE alone: a menu-bar / status-item app's freshly-opened popover is often sparse (an empty clipboard list, an empty note, a search field) so requiring >= min_texts wrongly REJECTS it. The generic container roles (window/group/web_area/scroll_area) still require >= min_texts text children to avoid matching window chrome.
Searches to max_depth=12 (was 3). Status-item popovers sit ~7-8 levels deep in the AX tree, so the old depth-3 search SILENTLY MISSED them -> ensure_panel_open()/ensure_ui_visible() returned None -> every reveal- dependent test hit `None.id` -> 0% baseline -> the whole menu-bar app was pruned to 0 and the job failed. (Verified on a live VM: depth-3 missed the popover 3/3 fresh launches; depth-12 + role-accept found it 3/3.) Returns the AXElement or None.""" for role in ("popover", "sheet"): containers = ax.find(role=role, max_results=10, max_depth=max_depth) if containers: return containers[0] for role in ("window", "group", "web_area", "scroll_area"): containers = ax.find(role=role, max_results=10, max_depth=max_depth) for c in containers: texts = ax.find_text_elements(root_id=c.id, max_results=min_texts + 1) if len(texts) >= min_texts: return c return None
def is_panel_visible(ax, min_texts=2): """Check if any panel-like container with content is visible.""" return find_panel_container(ax, min_texts=min_texts) is not None
def ensure_panel_open(ax): """Ensure the app's panel is open. Tries clicking each menu_bar_item. Returns the panel container element, or None if all attempts fail.""" panel = find_panel_container(ax) if panel: return panel
# max_depth=6 (was 3): the status-item / menu-bar-extra item that actually # reveals a status app's popover sits ~depth 4 — DEEPER than the app's own # menu-bar items (Apple/File/Edit at depth 2-3). A depth-3 search returned # only the app menus (whose AXPress opens dropdowns, NOT the popover), so the # status item was never pressed and the popover never opened -> None -> # 0% baseline for every menu-bar app. Widen the net so the status item is # found and pressed. (Verified on a live VM: depth-3 never opened the popover; # depth>=4 did.) mbis = ax.find(role="menu_bar_item", max_results=12, max_depth=6) # Two passes. The old code interleaved a CG click per item: AXPress, and if # that didn't reveal, click_element_cg the SAME item immediately. But a CG # click on an app menu (Apple/File/Edit) opens a blocking dropdown that # POISONS the next press, so the status popover a later AXPress would have # opened was never seen -> None -> 0% baseline for menu-bar apps. # Pass 1: AXPress every item, dismissing any dropdown a miss leaves open. # (Verified on a live VM: AXPress-only opened + detected the popover 3/3; # the interleaved CG click made it fail 3/3.) for mbi in mbis: ax.action(mbi.id, "AXPress") time.sleep(1.0) panel = find_panel_container(ax) if panel: return panel dismiss_menus(ax) # Pass 2: CG-click fallback only if AXPress revealed nothing anywhere. for mbi in mbis: ax.click_element_cg(mbi.id) time.sleep(1.0) panel = find_panel_container(ax) if panel: return panel dismiss_menus(ax)
return None
def dismiss_panel(ax): """Dismiss the panel. Multi-strategy: Escape -> click outside. Returns True if panel was dismissed (or was already closed).""" if not is_panel_visible(ax): return True
send_key(KC_ESCAPE) time.sleep(0.8) if not is_panel_visible(ax): return True
click_at(10, 10) time.sleep(0.8) return not is_panel_visible(ax)
def dismiss_menus(ax): """Dismiss any open menus by pressing Escape twice.""" send_key(KC_ESCAPE) time.sleep(0.3) send_key(KC_ESCAPE) time.sleep(0.3)
# ---------------------------------------------------------------------------# Text extraction: robust methods for getting text from panels# ---------------------------------------------------------------------------
def get_panel_texts(ax, panel=None): """Get all text strings from the panel. Scoped to the target app only. Returns list[str].""" if panel is None: panel = find_panel_container(ax) if panel is None: return [] text_els = ax.find_text_elements(root_id=panel.id, max_results=300) return [el.text for el in text_els if el.text]
def snapshot_panel_text(ax, panel=None): """Counter-based snapshot of panel text, for detecting changes.""" return Counter(get_panel_texts(ax, panel))
def extract_date_numbers(texts): """Extract day-of-month numbers (1-31) from a list of text strings. Handles standalone "7", mixed "7 廿一", "15 初一", etc.""" found = set() for t in texts: s = str(t).strip() if s.isdigit(): n = int(s) if 1 <= n <= 31: found.add(n) continue for m in re.finditer(r'\b(\d{1,2})\b', s): n = int(m.group(1)) if 1 <= n <= 31: found.add(n) m = re.match(r'^(\d{1,2})', s) if m: n = int(m.group(1)) if 1 <= n <= 31: found.add(n) return found
def count_weekday_symbols(texts): """Count how many texts match known weekday symbols.""" return sum(1 for t in texts if str(t).strip() in WEEKDAY_SYMBOLS)
def has_month_year(texts): """Check if any text contains a month/year pattern.""" all_text = " ".join(str(t) for t in texts) return MONTH_YEAR_PATTERN.search(all_text) is not None
# ---------------------------------------------------------------------------# Menu item search: keyword-based with fallback# ---------------------------------------------------------------------------
def find_by_keywords(items, keywords): """Find first item matching any keyword (case-insensitive, partial match).""" for item in items: name_lower = (item.name or "").lower() for kw in keywords: if kw.lower() in name_lower: return item return None
def find_menu_item(ax, keywords): """Search for a menu item by keyword list. First searches role=menu_item, then falls back to all clickable elements.""" items = ax.find(role="menu_item", max_results=100) result = find_by_keywords(items, keywords) if result: return result
clickable = ax.find_clickable(max_results=200) return find_by_keywords(clickable, keywords)
def open_actions_menu(ax): """Open the actions/settings menu and return its menu items. Tries buttons, pop-up buttons, menu buttons, then all clickable elements.""" panel = ensure_panel_open(ax) if panel is None: return []
existing = ax.find(role="menu_item", max_results=5) if len(existing) >= 3: return existing
skip_keywords = ["quit", "close", "exit", "delete", "remove"]
def _try_press(el): ax.action(el.id, "AXPress") time.sleep(0.6) menu_items = ax.find(role="menu_item", max_results=50) if len(menu_items) >= 3: return menu_items ax.click_element_cg(el.id) time.sleep(0.6) menu_items = ax.find(role="menu_item", max_results=50) if len(menu_items) >= 3: return menu_items send_key(KC_ESCAPE) time.sleep(0.3) return None
for role in ("button", "pop_up_button", "menu_button"): elements = ax.find(role=role, root_id=panel.id, max_results=20) for el in elements: name = (el.name or "").lower() if any(kw in name for kw in skip_keywords): continue result = _try_press(el) if result: return result
clickable = ax.find_clickable(root_id=panel.id, max_results=50) for el in clickable: name = (el.name or "").lower() if any(kw in name for kw in skip_keywords): continue if el.role in ("button", "pop_up_button", "menu_button"): continue result = _try_press(el) if result: return result
return ax.find(role="menu_item", max_results=50)
# ---------------------------------------------------------------------------# Month navigation: multi-strategy with fallback# ---------------------------------------------------------------------------
def navigate_month(ax, direction="forward"): """Navigate to the next/previous month. Multi-strategy fallback: 1. Named button (prev/next/arrow keywords) 2. Keyboard arrow key 3. Brute force — try all clickable elements Returns True if panel text changed.""" panel = ensure_panel_open(ax) if panel is None: return False text_before = snapshot_panel_text(ax, panel)
# Strategy 1: named button keywords = NAV_NEXT_KEYWORDS if direction == "forward" else NAV_PREV_KEYWORDS clickable = ax.find_clickable(root_id=panel.id, max_results=50) for el in clickable: name_lower = (el.name or "").lower() if any(kw.lower() in name_lower for kw in keywords): ax.action(el.id, "AXPress") time.sleep(0.6) panel2 = find_panel_container(ax) if panel2: text_after = snapshot_panel_text(ax, panel2) if text_after != text_before: return True ax.click_element_cg(el.id) time.sleep(0.6) panel2 = find_panel_container(ax) if panel2: text_after = snapshot_panel_text(ax, panel2) if text_after != text_before: return True
# Strategy 2: keyboard key_code = KC_RIGHT_ARROW if direction == "forward" else KC_LEFT_ARROW send_key(key_code) time.sleep(0.5) panel2 = find_panel_container(ax) if panel2: text_after = snapshot_panel_text(ax, panel2) if text_after != text_before: return True
# Strategy 3: brute force — try all clickable in panel panel = ensure_panel_open(ax) if panel is None: return False text_before = snapshot_panel_text(ax, panel) buttons = ax.find(role="button", root_id=panel.id, max_results=20) for btn in buttons: name = (btn.name or "").lower() if any(kw in name for kw in ["quit", "close", "exit", "setting", "about"]): continue ax.action(btn.id, "AXPress") time.sleep(0.6) panel2 = find_panel_container(ax) if panel2: text_after = snapshot_panel_text(ax, panel2) if text_after != text_before: return True ax.click_element_cg(btn.id) time.sleep(0.6) panel2 = find_panel_container(ax) if panel2: text_after = snapshot_panel_text(ax, panel2) if text_after != text_before: return True
return False
# ---------------------------------------------------------------------------# Today detection: multi-strategy# ---------------------------------------------------------------------------
def check_today_in_panel(ax, panel=None): """Check if today's date is present in the panel. Multi-strategy: 1. Extract date numbers and check for today 2. Search for "today" keywords in text 3. Check AXSelected/AXDescription attributes""" today = datetime.date.today().day
if panel is None: panel = ensure_panel_open(ax) texts = get_panel_texts(ax, panel)
# Strategy 1: date number extraction numbers = extract_date_numbers(texts) if today in numbers: return True
# Strategy 2: "today" keyword search for t in texts: for kw in TODAY_KEYWORDS: if kw.lower() in str(t).lower(): return True
# Strategy 3: AX attributes if panel: elements = ax.find(root_id=panel.id, max_results=200) for el in elements: attrs = ax.get(el.id, ["AXSelected", "AXDescription"]) if attrs.get("AXSelected"): return True desc = str(attrs.get("AXDescription", "")) if re.search(r"\btoday\b|今天|今日", desc, re.IGNORECASE): return True if str(today) in desc: return True
return False
# ---------------------------------------------------------------------------# Application lifecycle# ---------------------------------------------------------------------------
def quit_app_via_menu(ax): """Try to quit the app via menu item. Returns True if quit item found and clicked.""" items = open_actions_menu(ax) quit_item = find_by_keywords(items, QUIT_KEYWORDS) if quit_item: ax.action(quit_item.id, "AXPress") time.sleep(1.0) return True return False
def quit_app_via_shortcut(pid): """Quit app via Cmd+Q. Returns True if process terminated.""" send_key(KC_Q, modifiers=["cmd"]) time.sleep(1.5) try: os.kill(pid, 0) return False except ProcessLookupError: return True
def is_process_running(pid): """Check if a process is still running.""" try: os.kill(pid, 0) return True except ProcessLookupError: return False
# ---------------------------------------------------------------------------# Screenshot capture# ---------------------------------------------------------------------------
def take_screenshot(save_path, region=None): """Take a screenshot and save to save_path. region: optional (x, y, w, h) tuple for partial capture. Returns the save_path on success, None on failure.""" os.makedirs(os.path.dirname(os.path.abspath(save_path)), exist_ok=True) cmd = ["screencapture", "-x"] if region: x, y, w, h = region cmd.extend(["-R", f"{x},{y},{w},{h}"]) cmd.append(save_path) try: subprocess.run(cmd, timeout=10, check=True, capture_output=True, text=True) if os.path.exists(save_path) and os.path.getsize(save_path) > 0: return save_path except (subprocess.SubprocessError, OSError): pass return None
def take_screenshot_of_panel(ax, save_path): """Take a fullscreen screenshot. Uses fullscreen to stay consistent with official screenshots captured by the App Explorer (CU-based).""" return take_screenshot(save_path)
# ---------------------------------------------------------------------------# VLM screenshot comparison (Claude Vision API)# ---------------------------------------------------------------------------
def _load_image_base64(path): """Load image file as base64 string.""" import base64 with open(path, "rb") as f: return base64.b64encode(f.read()).decode("utf-8")
def _get_media_type(path): """Infer media type from file extension.""" ext = os.path.splitext(path)[1].lower() return {"png": "image/png", "jpg": "image/jpeg", "jpeg": "image/jpeg", "gif": "image/gif", "webp": "image/webp"}.get(ext.lstrip("."), "image/png")
def compare_screenshots_vlm(official_path, recreated_path, aspect, model=None, api_key=None, base_url=None): """Compare two screenshots using VLM via OpenAI-compatible API.
Args: official_path: path to the official app screenshot (ground truth) recreated_path: path to the recreated app screenshot aspect: what visual aspect to compare model: VLM model name (default: env VLM_MODEL) api_key: API key (default: env VLM_API_KEY) base_url: API base URL (default: env VLM_BASE_URL)
Returns: dict with keys: score (int 1-10), reason (str) """ import json try: import urllib.request import urllib.error except ImportError: return {"score": 1, "reason": "urllib not available"}
if not os.path.exists(official_path): return {"score": 1, "reason": f"Official screenshot not found: {official_path}"} if not os.path.exists(recreated_path): return {"score": 1, "reason": f"Recreated screenshot not found: {recreated_path}"}
model = model or os.environ.get("VLM_MODEL", "qwen-vl-max") api_key = api_key or os.environ.get("VLM_API_KEY") \ or os.environ.get("OPENAI_API_KEY") \ or os.environ.get("ANTHROPIC_API_KEY") base_url = base_url or os.environ.get("VLM_BASE_URL") \ or os.environ.get("OPENAI_BASE_URL") \ or "https://dashscope.aliyuncs.com/compatible-mode/v1"
if not api_key: return {"score": 1, "reason": "No API key found (set VLM_API_KEY)"}
base_url = base_url.rstrip("/")
official_b64 = _load_image_base64(official_path) recreated_b64 = _load_image_base64(recreated_path) official_mime = _get_media_type(official_path) recreated_mime = _get_media_type(recreated_path)
prompt = f"""You are a visual QA judge comparing two macOS app screenshots.
Image 1 (OFFICIAL): The reference/ground-truth screenshot of the original app.Image 2 (RECREATED): A screenshot of a recreated version of the same app.
Visual aspect to evaluate: {aspect}
Compare the two screenshots and rate how faithfully the recreated app reproduces the visual aspect described above.
Focus on:- Layout and positioning of UI elements- Text content and formatting- Colors, icons, and visual styling- Overall visual similarity for the specified aspect
Rate on a scale of 1-10: 1-2: Completely different, no resemblance 3-4: Major differences, some elements recognizable 5-6: Moderate similarity, layout roughly correct but notable differences 7-8: Good reproduction, minor visual differences 9-10: Near-perfect match, only trivial differences (antialiasing, font rendering)
Be lenient on minor pixel differences, font rendering, and antialiasing — focus on functional visual equivalence.
Respond in EXACTLY this JSON format (no other text):{{"score": <integer 1-10>, "reason": "one sentence explanation"}}"""
payload = { "model": model, "messages": [{ "role": "user", "content": [ {"type": "image_url", "image_url": { "url": f"data:{official_mime};base64,{official_b64}"}}, {"type": "image_url", "image_url": { "url": f"data:{recreated_mime};base64,{recreated_b64}"}}, {"type": "text", "text": prompt} ] }], "temperature": 0, "max_tokens": 256, }
headers = { "Content-Type": "application/json", "Authorization": f"Bearer {api_key}", }
import time as _time max_retries = 12 last_err = None
for attempt in range(max_retries): try: req = urllib.request.Request( f"{base_url}/chat/completions", data=json.dumps(payload).encode("utf-8"), headers=headers, method="POST") with urllib.request.urlopen(req, timeout=120) as resp: body = json.loads(resp.read().decode("utf-8"))
text = body["choices"][0]["message"]["content"].strip()
json_match = re.search(r'\{[^{}]*"score"[^{}]*\}', text) if json_match: result = json.loads(json_match.group()) score = int(result.get("score", 1)) score = max(1, min(10, score)) result["score"] = score result.setdefault("reason", "") return result
return {"score": 1, "reason": f"Could not parse VLM response: {text[:200]}"}
except urllib.error.HTTPError as e: last_err = f"HTTP {e.code}: {e.read().decode('utf-8', errors='replace')[:200]}" if e.code == 429: delay = 3 else: delay = 10 if attempt < max_retries - 1: _time.sleep(delay) continue except (urllib.error.URLError, json.JSONDecodeError, OSError) as e: last_err = str(e) if attempt < max_retries - 1: _time.sleep(10) continue
return {"score": 1, "reason": f"VLM API error after {max_retries} attempts: {last_err}"}
def assert_screenshot_match(ax, official_screenshot_path, aspect, save_dir="/tmp/verifier_screenshots"): """High-level helper: take screenshot of current app panel, compare with official. Raises AssertionError if VLM judges the screenshots don't match.""" import time as _time _time.sleep(1.0) os.makedirs(save_dir, exist_ok=True) basename = os.path.basename(official_screenshot_path) recreated_path = os.path.join(save_dir, f"recreated_{basename}")
result = take_screenshot_of_panel(ax, recreated_path) assert result is not None, "Failed to take screenshot of recreated app"
comparison = compare_screenshots_vlm(official_screenshot_path, recreated_path, aspect) score = comparison.get("score", 1) assert score >= 7, ( f"Screenshot mismatch for '{aspect}': {comparison.get('reason', '')} " f"(score={score}/10)" )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309{ "schema_version": 2, "instance_id": "macos/shuang886-terminader", "grading": { "mode": "deferred", "model": null, "scored_separately": true }, "totals": { "assertions": 22, "with_verdict": 0, "calibrated": 0, "usable": null, "scored_records": 0, "unbacked_records": 0 }, "assertions": [ { "id": "buttons_mode_toggle_cli.png", "screenshot": "buttons_mode_toggle_cli.png", "assertion": "Terminader is in Terminal mode after pressing the toolbar terminal button: a paste-document button, a Console/Errors segmented control with Console selected, a '🔍 Search' field, an empty console area, and a green '<dir> ➜' prompt with a yellow block cursor. The icon grid, status bar and icon-size slider are gone; the sidebar and toolbar are still there.", "form": "statement", "expected": true, "aspect": null, "modality": null, "links_to": "buttons_mode_toggle_cli.png", "rigor": null, "verdict": null, "calibration": null }, { "id": "buttons_sidebar_hidden.png", "screenshot": "buttons_sidebar_hidden.png", "assertion": "The sidebar is gone: no Favorites / iCloud / Locations list on the left. The icon grid now fills the whole window width, the status bar and icon-size slider are still along the bottom, and the toolbar's leftmost button shows the 'show sidebar' icon.", "form": "statement", "expected": true, "aspect": null, "modality": null, "links_to": "buttons_sidebar_hidden.png", "rigor": null, "verdict": null, "calibration": null }, { "id": "computation_echo_command_results.png", "screenshot": "computation_echo_command_results.png", "assertion": "Terminader is in CLI/Terminal mode with two stacked console blocks, each carrying a green header of the form '<dir> % <command>' with a relative time on its right: the first block's command is 'echo hello-terminader' and its monospace output line below reads 'hello-terminader'; the second block's command is 'echo smoke-value' and its output reads 'smoke-value'. A Console/Errors segmented control (Console selected) and a '🔍 Search' field sit above the blocks, and a green '<dir> ➜' prompt with a yellow block cursor sits below them.", "form": "statement", "expected": true, "aspect": null, "modality": null, "links_to": "computation_echo_command_results.png", "rigor": null, "verdict": null, "calibration": null }, { "id": "computation_failed_command_status.png", "screenshot": "computation_failed_command_status.png", "assertion": "Terminader's console shows a single command block whose header is RED (not green), reading '<dir> % nosuchcommandxyz' with a '↳ 127' exit status on the right-hand side of that header; the monospace body underneath reads 'zsh:1: command not found: nosuchcommandxyz'.", "form": "statement", "expected": true, "aspect": null, "modality": null, "links_to": "computation_failed_command_status.png", "rigor": null, "verdict": null, "calibration": null }, { "id": "computation_errors_pane_stderr.png", "screenshot": "computation_errors_pane_stderr.png", "assertion": "Terminader is in CLI/Terminal mode with the 'Errors' segment of the Console/Errors segmented control selected (highlighted) instead of 'Console'. A single command block for 'test_out 3' is shown and its body text is exactly 'This is stderr' — the 'This is stdout' text is not visible.", "form": "statement", "expected": true, "aspect": null, "modality": null, "links_to": "computation_errors_pane_stderr.png", "rigor": null, "verdict": null, "calibration": null }, { "id": "computation_markdown_file_render.png", "screenshot": "computation_markdown_file_render.png", "assertion": "Terminader's console shows the output of 'cat readme.md' rendered as real markdown: a large bold title 'Heading One' above the sentence 'Some markdown body text.' with the single word 'markdown' in italics. The raw source ('# Heading One' with a hash, or asterisks around markdown) is NOT shown.", "form": "statement", "expected": true, "aspect": null, "modality": null, "links_to": "computation_markdown_file_render.png", "rigor": null, "verdict": null, "calibration": null }, { "id": "computation_ls_markdown_table.png", "screenshot": "computation_ls_markdown_table.png", "assertion": "Terminader's console shows the output of 'ls' in the rbtest fixture directory as a rendered markdown table with visible borders: the header row reads Permissions / Links / Owner / Group / Size / Date / Name, and there is one row per fixture entry — alpha.txt, beta.txt, gamma.txt, readme.md and subdir/ — with the file names drawn as underlined links.", "form": "statement", "expected": true, "aspect": null, "modality": null, "links_to": "computation_ls_markdown_table.png", "rigor": null, "verdict": null, "calibration": null }, { "id": "menus_context_menu.png", "screenshot": "menus_context_menu.png", "assertion": "A small pop-up menu over the icon grid containing exactly two items, 'Open' and 'Get Info'.", "form": "statement", "expected": true, "aspect": null, "modality": null, "links_to": "menus_context_menu.png", "rigor": null, "verdict": null, "calibration": null }, { "id": "menus_get_info_window.png", "screenshot": "menus_get_info_window.png", "assertion": "A second, small window titled 'gamma.txt Info' whose only content is the text 'Info pane', in front of the main Terminader window.", "form": "statement", "expected": true, "aspect": null, "modality": null, "links_to": "menus_get_info_window.png", "rigor": null, "verdict": null, "calibration": null }, { "id": "menus_path_menu.png", "screenshot": "menus_path_menu.png", "assertion": "An open pop-up menu below the toolbar path control listing the current directory 'rbtest' and each of its ancestor folders up to 'Users'.", "form": "statement", "expected": true, "aspect": null, "modality": null, "links_to": "menus_path_menu.png", "rigor": null, "verdict": null, "calibration": null }, { "id": "menus_two_windows.png", "screenshot": "menus_two_windows.png", "assertion": "Two overlapping Terminader windows, each with its own sidebar (Favorites / iCloud / Locations), its own toolbar with back/forward chevrons, a path pop-up and a terminal icon, and its own icon grid.", "form": "statement", "expected": true, "aspect": null, "modality": null, "links_to": "menus_two_windows.png", "rigor": null, "verdict": null, "calibration": null }, { "id": "states_selection_highlight.png", "screenshot": "states_selection_highlight.png", "assertion": "Terminader's icon grid shows alpha.txt, beta.txt, gamma.txt, readme.md and the subdir folder; beta.txt's name is highlighted on a blue rounded background and its icon sits on a grey tile, and the status bar reads '1 of 5 selected, ... available'.", "form": "statement", "expected": true, "aspect": null, "modality": null, "links_to": "states_selection_highlight.png", "rigor": null, "verdict": null, "calibration": null }, { "id": "states_errors_pane.png", "screenshot": "states_errors_pane.png", "assertion": "Terminader's terminal surface with the segmented control switched to Errors (the Errors segment is selected/highlighted, Console is not); a single console block is listed and its body text reads 'This is stderr'.", "form": "statement", "expected": true, "aspect": null, "modality": null, "links_to": "states_errors_pane.png", "rigor": null, "verdict": null, "calibration": null }, { "id": "states_sidebar_hidden.png", "screenshot": "states_sidebar_hidden.png", "assertion": "The Terminader window with its sidebar hidden: no Favorites / iCloud / Locations list on the left, the icon grid fills the whole window, and the toolbar's leftmost button now shows the 'show sidebar' icon.", "form": "statement", "expected": true, "aspect": null, "modality": null, "links_to": "states_sidebar_hidden.png", "rigor": null, "verdict": null, "calibration": null }, { "id": "structure_gate_window_toolbar_sidebar.png", "screenshot": "structure_gate_window_toolbar_sidebar.png", "assertion": "One Terminader window (~900x450). A ~140pt sidebar down the left lists the heading 'Favorites' with rows Desktop, Documents, Downloads, Movies, Music, Pictures and the home folder, then the heading 'iCloud' with 'iCloud Drive' and the heading 'Locations' with 'Network'. A toolbar spans the top: a sidebar-toggle icon on the left, greyed-out back/forward chevrons, a path pop-up button showing the home folder name, and a terminal icon at the right edge. The detail area right of the sidebar shows an icon grid with a status bar reading '<n> items, ... available' and a small icon-size slider on its right.", "form": "statement", "expected": true, "aspect": null, "modality": null, "links_to": "structure_gate_window_toolbar_sidebar.png", "rigor": null, "verdict": null, "calibration": null }, { "id": "structure_cli_surface.png", "screenshot": "structure_cli_surface.png", "assertion": "Terminader on the Terminal (CLI) surface: the sidebar with Favorites / iCloud / Locations is still on the left, but the detail area now shows a paste-document button, a Console/Errors segmented control with 'Console' selected, a '🔍 Search' field on its right, an empty console history area, and a green '<dir> ➜' prompt with a yellow block cursor along the bottom. No icon grid, no '<n> items, ... available' status bar and no icon-size slider are visible.", "form": "statement", "expected": true, "aspect": null, "modality": null, "links_to": "structure_cli_surface.png", "rigor": null, "verdict": null, "calibration": null }, { "id": "structure_sidebar_hidden.png", "screenshot": "structure_sidebar_hidden.png", "assertion": "The Terminader window with NO sidebar: the Favorites / iCloud / Locations list (Desktop, Documents, Downloads, Movies, Music, Pictures, home, iCloud Drive, Network) is gone, the icon grid now fills the full window width, and the leftmost toolbar button shows the 'show sidebar' icon. The toolbar still has back/forward chevrons, the path pop-up and the terminal icon, and the status bar still reads '<n> items, ... available'.", "form": "statement", "expected": true, "aspect": null, "modality": null, "links_to": "structure_sidebar_hidden.png", "rigor": null, "verdict": null, "calibration": null }, { "id": "structure_fixture_grid.png", "screenshot": "structure_fixture_grid.png", "assertion": "Terminader's icon grid showing exactly five items: four grey document icons labelled alpha.txt, beta.txt, gamma.txt and readme.md, plus one cyan folder icon labelled subdir. The toolbar path pop-up reads 'rbtest', the sidebar is still visible on the left, and the status bar under the grid reads '5 items, ... available' with the icon-size slider at its right.", "form": "statement", "expected": true, "aspect": null, "modality": null, "links_to": "structure_fixture_grid.png", "rigor": null, "verdict": null, "calibration": null }, { "id": "text_sidebar_vocabulary.png", "screenshot": "text_sidebar_vocabulary.png", "assertion": "Terminader's left sidebar lists the section headings Favorites, iCloud and Locations, the rows Desktop, Documents, Downloads, Movies, Music, Pictures and the user's home folder, plus the static labels 'iCloud Drive' and 'Network'; the toolbar above shows back/forward chevrons, a path pop-up button and a terminal icon.", "form": "statement", "expected": true, "aspect": null, "modality": null, "links_to": "text_sidebar_vocabulary.png", "rigor": null, "verdict": null, "calibration": null }, { "id": "text_status_bar_selection.png", "screenshot": "text_status_bar_selection.png", "assertion": "The Terminader icon grid shows four grey document icons labelled alpha.txt, beta.txt, gamma.txt, readme.md and one cyan folder labelled subdir; beta.txt's name is highlighted on a blue rounded background and the status bar under the grid reads '1 of 5 selected, <free space> available'.", "form": "statement", "expected": true, "aspect": null, "modality": null, "links_to": "text_status_bar_selection.png", "rigor": null, "verdict": null, "calibration": null }, { "id": "text_cli_prompt.png", "screenshot": "text_cli_prompt.png", "assertion": "Terminader's Terminal (CLI) surface: a paste-document button, a Console/Errors segmented control with Console selected, a '🔍 Search' field, and at the bottom left a green 'rbtest' prompt followed by an arrow-right-circle glyph and a yellow block cursor.", "form": "statement", "expected": true, "aspect": null, "modality": null, "links_to": "text_cli_prompt.png", "rigor": null, "verdict": null, "calibration": null }, { "id": "text_get_info_window.png", "screenshot": "text_get_info_window.png", "assertion": "A second, small Terminader window titled 'gamma.txt Info' is in front of the main window; its only content is the text 'Info pane'.", "form": "statement", "expected": true, "aspect": null, "modality": null, "links_to": "text_get_info_window.png", "rigor": null, "verdict": null, "calibration": null } ], "merged_from_files": 6, "source_shapes": { "dict_str": 22 }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661 GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license forsoftware and other kinds of works, specifically designed to ensurecooperation with the community in the case of network server software.
The licenses for most software and other practical works are designedto take away your freedom to share and change the works. By contrast,our General Public Licenses are intended to guarantee your freedom toshare and change all versions of a program--to make sure it remains freesoftware for all its users.
When we speak of free software, we are referring to freedom, notprice. Our General Public Licenses are designed to make sure that youhave the freedom to distribute copies of free software (and charge forthem if you wish), that you receive source code or can get it if youwant it, that you can change the software or use pieces of it in newfree programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rightswith two steps: (1) assert copyright on the software, and (2) offeryou this License which gives you legal permission to copy, distributeand/or modify the software.
A secondary benefit of defending all users' freedom is thatimprovements made in alternate versions of the program, if theyreceive widespread use, become available for other developers toincorporate. Many developers of free software are heartened andencouraged by the resulting cooperation. However, in the case ofsoftware used on network servers, this result may fail to come about.The GNU General Public License permits making a modified version andletting the public access it on a server without ever releasing itssource code to the public.
The GNU Affero General Public License is designed specifically toensure that, in such cases, the modified source code becomes availableto the community. It requires the operator of a network server toprovide the source code of the modified version running there to theusers of that server. Therefore, public use of a modified version, ona publicly accessible server, gives the public access to the sourcecode of the modified version.
An older license, called the Affero General Public License andpublished by Affero, was designed to accomplish similar goals. This isa different license, not a version of the Affero GPL, but Affero hasreleased a new version of the Affero GPL which permits relicensing underthis license.
The precise terms and conditions for copying, distribution andmodification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds ofworks, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under thisLicense. Each licensee is addressed as "you". "Licensees" and"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the workin a fashion requiring copyright permission, other than the making of anexact copy. The resulting work is called a "modified version" of theearlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work basedon the Program.
To "propagate" a work means to do anything with it that, withoutpermission, would make you directly or secondarily liable forinfringement under applicable copyright law, except executing it on acomputer or modifying a private copy. Propagation includes copying,distribution (with or without modification), making available to thepublic, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables otherparties to make or receive copies. Mere interaction with a user througha computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"to the extent that it includes a convenient and prominently visiblefeature that (1) displays an appropriate copyright notice, and (2)tells the user that there is no warranty for the work (except to theextent that warranties are provided), that licensees may convey thework under this License, and how to view a copy of this License. Ifthe interface presents a list of user commands or options, such as amenu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the workfor making modifications to it. "Object code" means any non-sourceform of a work.
A "Standard Interface" means an interface that either is an officialstandard defined by a recognized standards body, or, in the case ofinterfaces specified for a particular programming language, one thatis widely used among developers working in that language.
The "System Libraries" of an executable work include anything, otherthan the work as a whole, that (a) is included in the normal form ofpackaging a Major Component, but which is not part of that MajorComponent, and (b) serves only to enable use of the work with thatMajor Component, or to implement a Standard Interface for which animplementation is available to the public in source code form. A"Major Component", in this context, means a major essential component(kernel, window system, and so on) of the specific operating system(if any) on which the executable work runs, or a compiler used toproduce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means allthe source code needed to generate, install, and (for an executablework) run the object code and to modify the work, including scripts tocontrol those activities. However, it does not include the work'sSystem Libraries, or general-purpose tools or generally available freeprograms which are used unmodified in performing those activities butwhich are not part of the work. For example, Corresponding Sourceincludes interface definition files associated with source files forthe work, and the source code for shared libraries and dynamicallylinked subprograms that the work is specifically designed to require,such as by intimate data communication or control flow between thosesubprograms and other parts of the work.
The Corresponding Source need not include anything that userscan regenerate automatically from other parts of the CorrespondingSource.
The Corresponding Source for a work in source code form is thatsame work.
2. Basic Permissions.
All rights granted under this License are granted for the term ofcopyright on the Program, and are irrevocable provided the statedconditions are met. This License explicitly affirms your unlimitedpermission to run the unmodified Program. The output from running acovered work is covered by this License only if the output, given itscontent, constitutes a covered work. This License acknowledges yourrights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do notconvey, without conditions so long as your license otherwise remainsin force. You may convey covered works to others for the sole purposeof having them make modifications exclusively for you, or provide youwith facilities for running those works, provided that you comply withthe terms of this License in conveying all material for which you donot control copyright. Those thus making or running the covered worksfor you must do so exclusively on your behalf, under your directionand control, on terms that prohibit them from making any copies ofyour copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely underthe conditions stated below. Sublicensing is not allowed; section 10makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technologicalmeasure under any applicable law fulfilling obligations under article11 of the WIPO copyright treaty adopted on 20 December 1996, orsimilar laws prohibiting or restricting circumvention of suchmeasures.
When you convey a covered work, you waive any legal power to forbidcircumvention of technological measures to the extent such circumventionis effected by exercising rights under this License with respect tothe covered work, and you disclaim any intention to limit operation ormodification of the work as a means of enforcing, against the work'susers, your or third parties' legal rights to forbid circumvention oftechnological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as youreceive it, in any medium, provided that you conspicuously andappropriately publish on each copy an appropriate copyright notice;keep intact all notices stating that this License and anynon-permissive terms added in accord with section 7 apply to the code;keep intact all notices of the absence of any warranty; and give allrecipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications toproduce it from the Program, in the form of source code under theterms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices".
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independentworks, which are not by their nature extensions of the covered work,and which are not combined with it such as to form a larger program,in or on a volume of a storage or distribution medium, is called an"aggregate" if the compilation and its resulting copyright are notused to limit the access or legal rights of the compilation's usersbeyond what the individual works permit. Inclusion of a covered workin an aggregate does not cause this License to apply to the otherparts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the termsof sections 4 and 5, provided that you also convey themachine-readable Corresponding Source under the terms of this License,in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excludedfrom the Corresponding Source as a System Library, need not beincluded in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means anytangible personal property which is normally used for personal, family,or household purposes, or (2) anything designed or sold for incorporationinto a dwelling. In determining whether a product is a consumer product,doubtful cases shall be resolved in favor of coverage. For a particularproduct received by a particular user, "normally used" refers to atypical or common use of that class of product, regardless of the statusof the particular user or of the way in which the particular useractually uses, or expects or is expected to use, the product. A productis a consumer product regardless of whether the product has substantialcommercial, industrial or non-consumer uses, unless such uses representthe only significant mode of use of the product.
"Installation Information" for a User Product means any methods,procedures, authorization keys, or other information required to installand execute modified versions of a covered work in that User Product froma modified version of its Corresponding Source. The information mustsuffice to ensure that the continued functioning of the modified objectcode is in no case prevented or interfered with solely becausemodification has been made.
If you convey an object code work under this section in, or with, orspecifically for use in, a User Product, and the conveying occurs aspart of a transaction in which the right of possession and use of theUser Product is transferred to the recipient in perpetuity or for afixed term (regardless of how the transaction is characterized), theCorresponding Source conveyed under this section must be accompaniedby the Installation Information. But this requirement does not applyif neither you nor any third party retains the ability to installmodified object code on the User Product (for example, the work hasbeen installed in ROM).
The requirement to provide Installation Information does not include arequirement to continue to provide support service, warranty, or updatesfor a work that has been modified or installed by the recipient, or forthe User Product in which it has been modified or installed. Access to anetwork may be denied when the modification itself materially andadversely affects the operation of the network or violates the rules andprotocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,in accord with this section must be in a format that is publiclydocumented (and with an implementation available to the public insource code form), and must require no special password or key forunpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of thisLicense by making exceptions from one or more of its conditions.Additional permissions that are applicable to the entire Program shallbe treated as though they were included in this License, to the extentthat they are valid under applicable law. If additional permissionsapply only to part of the Program, that part may be used separatelyunder those permissions, but the entire Program remains governed bythis License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your optionremove any additional permissions from that copy, or from any part ofit. (Additional permissions may be written to require their ownremoval in certain cases when you modify the work.) You may placeadditional permissions on material, added by you to a covered work,for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material youadd to a covered work, you may (if authorized by the copyright holders ofthat material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered "furtherrestrictions" within the meaning of section 10. If the Program as youreceived it, or any part of it, contains a notice stating that it isgoverned by this License along with a term that is a furtherrestriction, you may remove that term. If a license document containsa further restriction but permits relicensing or conveying under thisLicense, you may add to a covered work material governed by the termsof that license document, provided that the further restriction doesnot survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, youmust place, in the relevant source files, a statement of theadditional terms that apply to those files, or a notice indicatingwhere to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in theform of a separately written license, or stated as exceptions;the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expresslyprovided under this License. Any attempt otherwise to propagate ormodify it is void, and will automatically terminate your rights underthis License (including any patent licenses granted under the thirdparagraph of section 11).
However, if you cease all violation of this License, then yourlicense from a particular copyright holder is reinstated (a)provisionally, unless and until the copyright holder explicitly andfinally terminates your license, and (b) permanently, if the copyrightholder fails to notify you of the violation by some reasonable meansprior to 60 days after the cessation.
Moreover, your license from a particular copyright holder isreinstated permanently if the copyright holder notifies you of theviolation by some reasonable means, this is the first time you havereceived notice of violation of this License (for any work) from thatcopyright holder, and you cure the violation prior to 30 days afteryour receipt of the notice.
Termination of your rights under this section does not terminate thelicenses of parties who have received copies or rights from you underthis License. If your rights have been terminated and not permanentlyreinstated, you do not qualify to receive new licenses for the samematerial under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive orrun a copy of the Program. Ancillary propagation of a covered workoccurring solely as a consequence of using peer-to-peer transmissionto receive a copy likewise does not require acceptance. However,nothing other than this License grants you permission to propagate ormodify any covered work. These actions infringe copyright if you donot accept this License. Therefore, by modifying or propagating acovered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automaticallyreceives a license from the original licensors, to run, modify andpropagate that work, subject to this License. You are not responsiblefor enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of anorganization, or substantially all assets of one, or subdividing anorganization, or merging organizations. If propagation of a coveredwork results from an entity transaction, each party to thattransaction who receives a copy of the work also receives whateverlicenses to the work the party's predecessor in interest had or couldgive under the previous paragraph, plus a right to possession of theCorresponding Source of the work from the predecessor in interest, ifthe predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of therights granted or affirmed under this License. For example, you maynot impose a license fee, royalty, or other charge for exercise ofrights granted under this License, and you may not initiate litigation(including a cross-claim or counterclaim in a lawsuit) alleging thatany patent claim is infringed by making, using, selling, offering forsale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under thisLicense of the Program or a work on which the Program is based. Thework thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claimsowned or controlled by the contributor, whether already acquired orhereafter acquired, that would be infringed by some manner, permittedby this License, of making, using, or selling its contributor version,but do not include claims that would be infringed only as aconsequence of further modification of the contributor version. Forpurposes of this definition, "control" includes the right to grantpatent sublicenses in a manner consistent with the requirements ofthis License.
Each contributor grants you a non-exclusive, worldwide, royalty-freepatent license under the contributor's essential patent claims, tomake, use, sell, offer for sale, import and otherwise run, modify andpropagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any expressagreement or commitment, however denominated, not to enforce a patent(such as an express permission to practice a patent or covenant not tosue for patent infringement). To "grant" such a patent license to aparty means to make such an agreement or commitment not to enforce apatent against the party.
If you convey a covered work, knowingly relying on a patent license,and the Corresponding Source of the work is not available for anyoneto copy, free of charge and under the terms of this License, through apublicly available network server or other readily accessible means,then you must either (1) cause the Corresponding Source to be soavailable, or (2) arrange to deprive yourself of the benefit of thepatent license for this particular work, or (3) arrange, in a mannerconsistent with the requirements of this License, to extend the patentlicense to downstream recipients. "Knowingly relying" means you haveactual knowledge that, but for the patent license, your conveying thecovered work in a country, or your recipient's use of the covered workin a country, would infringe one or more identifiable patents in thatcountry that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction orarrangement, you convey, or propagate by procuring conveyance of, acovered work, and grant a patent license to some of the partiesreceiving the covered work authorizing them to use, propagate, modifyor convey a specific copy of the covered work, then the patent licenseyou grant is automatically extended to all recipients of the coveredwork and works based on it.
A patent license is "discriminatory" if it does not include withinthe scope of its coverage, prohibits the exercise of, or isconditioned on the non-exercise of one or more of the rights that arespecifically granted under this License. You may not convey a coveredwork if you are a party to an arrangement with a third party that isin the business of distributing software, under which you make paymentto the third party based on the extent of your activity of conveyingthe work, and under which the third party grants, to any of theparties who would receive the covered work from you, a discriminatorypatent license (a) in connection with copies of the covered workconveyed by you (or copies made from those copies), or (b) primarilyfor and in connection with specific products or compilations thatcontain the covered work, unless you entered into that arrangement,or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limitingany implied license or other defenses to infringement that mayotherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement orotherwise) that contradict the conditions of this License, they do notexcuse you from the conditions of this License. If you cannot convey acovered work so as to satisfy simultaneously your obligations under thisLicense and any other pertinent obligations, then as a consequence you maynot convey it at all. For example, if you agree to terms that obligate youto collect a royalty for further conveying from those to whom you conveythe Program, the only way you could satisfy both those terms and thisLicense would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify theProgram, your modified version must prominently offer all usersinteracting with it remotely through a computer network (if your versionsupports such interaction) an opportunity to receive the CorrespondingSource of your version by providing access to the Corresponding Sourcefrom a network server at no charge, through some standard or customarymeans of facilitating copying of software. This Corresponding Sourceshall include the Corresponding Source for any work covered by version 3of the GNU General Public License that is incorporated pursuant to thefollowing paragraph.
Notwithstanding any other provision of this License, you havepermission to link or combine any covered work with a work licensedunder version 3 of the GNU General Public License into a singlecombined work, and to convey the resulting work. The terms of thisLicense will continue to apply to the part which is the covered work,but the work with which it is combined will remain governed by version3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions ofthe GNU Affero General Public License from time to time. Such new versionswill be similar in spirit to the present version, but may differ in detail toaddress new problems or concerns.
Each version is given a distinguishing version number. If theProgram specifies that a certain numbered version of the GNU Affero GeneralPublic License "or any later version" applies to it, you have theoption of following the terms and conditions either of that numberedversion or of any later version published by the Free SoftwareFoundation. If the Program does not specify a version number of theGNU Affero General Public License, you may choose any version ever publishedby the Free Software Foundation.
If the Program specifies that a proxy can decide which futureversions of the GNU Affero General Public License can be used, that proxy'spublic statement of acceptance of a version permanently authorizes youto choose that version for the Program.
Later license versions may give you additional or differentpermissions. However, no additional obligations are imposed on anyauthor or copyright holder as a result of your choosing to follow alater version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BYAPPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHTHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTYOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULARPURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAMIS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OFALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITINGWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYSTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANYGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THEUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OFDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRDPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OFSUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability providedabove cannot be given local legal effect according to their terms,reviewing courts shall apply local law that most closely approximatesan absolute waiver of all civil liability in connection with theProgram, unless a warranty or assumption of liability accompanies acopy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatestpossible use to the public, the best way to achieve this is to make itfree software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safestto attach them to the start of each source file to most effectivelystate the exclusion of warranty; and each file should have at leastthe "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.> Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computernetwork, you should also make sure that it provides a way for users toget its source. For example, if your program is a web application, itsinterface could display a "Source" link that leads users to an archiveof the code. There are many ways you could offer source, and differentsolutions will be better for different programs; see section 13 for thespecific requirements.
You should also get your employer (if you work as a programmer) or school,if any, to sign a "copyright disclaimer" for the program, if necessary.For more information on this, and how to apply and follow the GNU AGPL, see<https://www.gnu.org/licenses/>.12345678910{ "schema_version": 1, "instance_id": "macos/sn4k3-uvtools", "platform": "macos", "repo": "https://github.com/sn4k3/UVtools", "commit": "f56dc0407dccc459ea4f033cb3efc4815295ab88", "patches": [], "package": null, "license": null}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234#!/usr/bin/env bash## Standalone, reproducible build script for UVtools (macOS).## UVtools is a .NET / Avalonia desktop application. This script publishes a# self-contained macOS build and wraps it into a UVtools.app bundle, mirroring# what build/createRelease.sh does for the official releases.## It is fully self-contained: on a fresh `git clone` into which only this# build.sh (and launch.sh) have been copied, `bash build.sh` produces the app.## Everything the build needs lives in this script or in the cloned repo:# - The .NET SDK is used if already present, otherwise installed locally# (script-relative, no sudo) via the official dotnet-install.sh.# - Info.plist / entitlements are generated INLINE (heredoc) below.# - The app icon (UVtools.icns) and native libcvextern.dylib come from the# repo (both are tracked in git, so present after a clean clone) and from# the Emgu.CV.runtime.mini.macos NuGet package.#set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"cd "$SCRIPT_DIR"
# ---------------------------------------------------------------------------# Configuration# ---------------------------------------------------------------------------export DOTNET_CLI_TELEMETRY_OPTOUT=1export DOTNET_NOLOGO=1export DOTNET_SKIP_FIRST_TIME_EXPERIENCE=1
# Where the finished .app is copied to (pipeline may override APP_OUTPUT_DIR).APP_OUTPUT_DIR="${APP_OUTPUT_DIR:-$SCRIPT_DIR}"mkdir -p "$APP_OUTPUT_DIR"
# Map the current CPU architecture to a .NET runtime identifier.ARCH="$(uname -m)"case "$ARCH" in arm64) RID="osx-arm64" ;; x86_64) RID="osx-x64" ;; *) echo "ERROR: unsupported architecture '$ARCH'"; exit 1 ;;esacecho "==> Target runtime identifier: $RID"
# ---------------------------------------------------------------------------# 1. Ensure a usable .NET SDK (>= 6). Install locally if none is available.# ---------------------------------------------------------------------------DOTNET=""if command -v dotnet >/dev/null 2>&1; then MAJOR="$(dotnet --version 2>/dev/null | cut -d. -f1 || true)" if [[ "$MAJOR" =~ ^[0-9]+$ ]] && [ "$MAJOR" -ge 6 ]; then DOTNET="$(command -v dotnet)" fifi
if [ -z "$DOTNET" ]; then echo "==> No suitable .NET SDK found; installing locally (no sudo)" export DOTNET_ROOT="$SCRIPT_DIR/.dotnet" mkdir -p "$DOTNET_ROOT" # Official Microsoft installer; installs into a script-relative directory. curl -fsSL https://dot.net/v1/dotnet-install.sh | \ bash -s -- --channel 10.0 --install-dir "$DOTNET_ROOT" export PATH="$DOTNET_ROOT:$PATH" DOTNET="$DOTNET_ROOT/dotnet"fiecho "==> Using dotnet: $DOTNET (SDK $("$DOTNET" --version 2>/dev/null))"
# ---------------------------------------------------------------------------# 2. Resolve the product version (used in the bundle Info.plist).# ---------------------------------------------------------------------------VERSION="$(perl -nle 'print $1 if /<UVtoolsVersion>([0-9]+\.[0-9]+\.[0-9]+)<\/UVtoolsVersion>/' \ "$SCRIPT_DIR/Directory.Build.props" 2>/dev/null || true)"[ -z "$VERSION" ] && VERSION="0.0.0"echo "==> UVtools version: $VERSION"
# ---------------------------------------------------------------------------# 3. Restore, then publish UVtoolsCmd + UVtools (self-contained) for this RID.## Two deliberate choices make the .NET 10 SDK produce a COMPLETE, correct build# of this net6.0 solution:## * ONE coherent, sequential whole-solution restore (--disable-parallel),# reused by the publishes via --no-restore. Publishing the projects# individually with their own cold, parallel restores intermittently drops# package references that reach Cmd/UI only TRANSITIVELY through# UVtools.Core: Emgu.CV and Microsoft.CodeAnalysis.Scripting (-> CS0246 /# CS0234 at compile time) and BinarySerializer (-> FileNotFoundException at# run time). One whole-solution restore resolves every project's complete# transitive closure and downloads the osx runtime pack in a single pass.# (Packages reaching a project through a DIRECT reference, e.g. SkiaSharp# via Avalonia, are never affected.)## * RELATIVE project/solution paths (we cd into SCRIPT_DIR first). Passing an# ABSOLUTE project path to `dotnet build/publish` with this SDK/TFM makes# the generated deps.json OMIT the UVtools.Core project reference -> "Could# not load file or assembly 'UVtools.Core'" (SIGABRT) at run time. Relative# paths avoid it.## ReadyToRun is disabled: it is only a startup optimisation and would otherwise# need its crossgen pack restored up front. The app is functionally identical.# ---------------------------------------------------------------------------cd "$SCRIPT_DIR"echo "==> Restoring solution ($RID)""$DOTNET" restore UVtools.sln -r "$RID" --disable-parallel
PUBLISH_DIR="$SCRIPT_DIR/publish/UVtools_${RID}_v${VERSION}"rm -rf "$PUBLISH_DIR"mkdir -p "$PUBLISH_DIR"
# Reference each project by RELATIVE path (see note above); -o may be absolute.for proj in UVtools.Cmd UVtools.UI; do echo "==> Publishing $proj ($RID)" "$DOTNET" publish "$proj" \ -o "$PUBLISH_DIR" -c Release -r "$RID" \ --self-contained --no-restore \ -p:PublishReadyToRun=false \ --verbosity minimaldone
# Sanity: both apphosts, the shared managed assembly, and a representative# transitive runtime dependency (BinarySerializer, loaded by UVtools.Core at# startup) must all be present.[ -f "$PUBLISH_DIR/UVtools" ] || { echo "ERROR: UVtools apphost missing"; exit 1; }[ -f "$PUBLISH_DIR/UVtoolsCmd" ] || { echo "ERROR: UVtoolsCmd apphost missing"; exit 1; }[ -f "$PUBLISH_DIR/UVtools.Core.dll" ] || { echo "ERROR: UVtools.Core.dll missing"; exit 1; }[ -f "$PUBLISH_DIR/BinarySerializer.dll" ] || { echo "ERROR: transitive runtime deps incomplete (BinarySerializer.dll missing)"; exit 1; }
# Health check: run UVtoolsCmd print-formats, which forces UVtools.Core's static# initializer (loading UVtools.Core itself, Emgu.CV and BinarySerializer via the# PhotonWorkshopFile format) to run. We assert on the OUTPUT, not the exit code:# UVtoolsCmd returns a non-zero code for informational commands even on success,# so a pipe would misreport under `set -o pipefail`. Capture then match instead.echo "==> Verifying runtime payload (UVtoolsCmd print-formats)"hc_out="$("$PUBLISH_DIR/UVtoolsCmd" print-formats 2>&1 || true)"case "$hc_out" in *PhotonWorkshopFile*) echo "==> Runtime payload OK" ;; *) echo "ERROR: runtime payload incomplete (print-formats did not list PhotonWorkshopFile):" printf '%s\n' "$hc_out" | head -n 8 exit 1 ;;esac
# ---------------------------------------------------------------------------# 4. Assemble the macOS .app bundle.# ---------------------------------------------------------------------------APP="$APP_OUTPUT_DIR/UVtools.app"echo "==> Building bundle: $APP"rm -rf "$APP"mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources"
# App icon (repo source, tracked in git -> present after a clean clone).cp -af "$SCRIPT_DIR/UVtools.CAD/UVtools.icns" "$APP/Contents/Resources/"
# Published payload (includes UVtools, UVtoolsCmd, all managed dlls and the# native libcvextern.dylib provided by the Emgu.CV runtime NuGet package).cp -a "$PUBLISH_DIR/." "$APP/Contents/MacOS/"
# Info.plist (generated inline; #VERSION substituted with the real version).cat > "$APP/Contents/Info.plist" <<PLIST<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"> <dict> <key>CFBundleDevelopmentRegion</key> <string>en</string> <key>CFBundleIconFile</key> <string>UVtools.icns</string> <key>CFBundleIdentifier</key> <string>com.UVtools</string> <key>CFBundleDisplayName</key> <string>UVtools</string> <key>CFBundleName</key> <string>UVtools</string> <key>CFBundleVersion</key> <string>${VERSION}</string> <key>LSMinimumSystemVersion</key> <string>10.15</string> <key>CFBundleExecutable</key> <string>UVtools</string> <key>CFBundleInfoDictionaryVersion</key> <string>6.0</string> <key>CFBundlePackageType</key> <string>APPL</string> <key>CFBundleShortVersionString</key> <string>${VERSION}</string> <key>CFBundleSupportedPlatforms</key> <array> <string>MacOSX</string> </array> <key>LSApplicationCategoryType</key> <string>public.app-category.utilities</string> <key>NSHighResolutionCapable</key> <true/> <key>NSHumanReadableCopyright</key> <string>Copyright © 2020 PTRTECH. All rights reserved.</string> </dict></plist>PLIST
# Entitlements (generated inline).cat > "$APP/Contents/UVtools.entitlements" <<'ENTITLEMENTS'<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><dict> <key>com.apple.security.cs.allow-jit</key> <true/> <key>com.apple.security.cs.allow-unsigned-executable-memory</key> <true/> <key>com.apple.security.cs.disable-library-validation</key> <true/> <key>com.apple.security.cs.allow-dyld-environment-variables</key> <true/></dict></plist>ENTITLEMENTS
# Make sure the launchers are executable.chmod 0755 "$APP/Contents/MacOS/UVtools" "$APP/Contents/MacOS/UVtoolsCmd" 2>/dev/null || true[ -f "$APP/Contents/MacOS/UVtools.sh" ] && chmod 0755 "$APP/Contents/MacOS/UVtools.sh" || true
# On Apple Silicon an ad-hoc code signature is required for the app to run.# `dotnet publish` already ad-hoc signs the apphost; re-sign the whole bundle# so the modified bundle stays valid. Harmless / skipped on Intel.if [ "$RID" = "osx-arm64" ] && command -v codesign >/dev/null 2>&1; then codesign --force --deep --sign - \ --entitlements "$APP/Contents/UVtools.entitlements" \ "$APP" 2>/dev/null || truefi
# Remove the now-redundant intermediate publish output to keep the tree tidy.rm -rf "$SCRIPT_DIR/publish"
echo "==> Done. Built: $APP"ls -la "$APP/Contents/MacOS/UVtools" "$APP/Contents/MacOS/libcvextern.dylib" 2>/dev/null || true1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253#!/usr/bin/env bash## Launch script for UVtools (macOS).## Locates the built UVtools.app relative to this script and starts it via# `open`, which hands the bundle to macOS LaunchServices / the logged-in GUI# session. (Running the Mach-O binary directly from a non-GUI shell can fail to# obtain a WindowServer connection; `open` avoids that.)## Works standalone (build.sh does not need to have been sourced first).#set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
# Where build.sh placed the bundle (pipeline may override APP_OUTPUT_DIR).APP_OUTPUT_DIR="${APP_OUTPUT_DIR:-$SCRIPT_DIR}"APP="$APP_OUTPUT_DIR/UVtools.app"
# Fallback: search a few levels down if it is not where we expect.if [ ! -d "$APP" ]; then found="$(/usr/bin/find "$SCRIPT_DIR" -maxdepth 4 -name 'UVtools.app' -type d 2>/dev/null | head -n 1 || true)" [ -n "$found" ] && APP="$found"fi
if [ ! -d "$APP" ]; then echo "ERROR: UVtools.app not found (looked in $APP_OUTPUT_DIR). Run build.sh first." >&2 exit 1fi
BIN="$APP/Contents/MacOS/UVtools"if [ ! -x "$BIN" ]; then echo "ERROR: executable not found at $BIN" >&2 exit 1fi
# The build is self-contained (the native libcvextern.dylib sits next to the# executable and is resolved from the app directory), so no special runtime# variables are required. Export the dyld search path anyway as a harmless# belt-and-suspenders measure for anyone running the binary directly.export DYLD_LIBRARY_PATH="$APP/Contents/MacOS:${DYLD_LIBRARY_PATH:-}"export DYLD_FRAMEWORK_PATH="$APP/Contents/MacOS:${DYLD_FRAMEWORK_PATH:-}"
echo "==> Launching $APP"
if command -v open >/dev/null 2>&1; then # -n: new instance, -W: wait for the app to exit. Everything after --args # is forwarded to UVtools. exec open -n -W "$APP" --args "$@"else # Non-macOS fallback: run the binary directly. exec "$BIN" "$@"fi123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849import osimport reimport timeimport warningsimport subprocessfrom dataclasses import dataclass, fieldfrom typing import Optionalfrom collections import Counter, deque
from ApplicationServices import ( AXUIElementCreateApplication, AXUIElementCreateSystemWide, AXUIElementCopyAttributeNames, AXUIElementCopyAttributeValue, AXUIElementGetAttributeValueCount, AXUIElementCopyAttributeValues, AXUIElementIsAttributeSettable, AXUIElementSetAttributeValue, AXUIElementCopyMultipleAttributeValues, AXUIElementCopyParameterizedAttributeNames, AXUIElementCopyParameterizedAttributeValue, AXUIElementCopyActionNames, AXUIElementCopyActionDescription, AXUIElementPerformAction, AXUIElementCopyElementAtPosition, AXUIElementGetPid, AXUIElementSetMessagingTimeout, kAXValueCGPointType, kAXValueCGSizeType, AXValueGetValue,)import Quartz
ROLE_MAP = { "AXButton": "button", "AXStaticText": "label", "AXTextField": "text_field", "AXTextArea": "text_area", "AXCheckBox": "checkbox", "AXRadioButton": "radio", "AXPopUpButton": "popup", "AXComboBox": "combobox", "AXSlider": "slider", "AXImage": "image", "AXGroup": "group", "AXList": "list", "AXTable": "table", "AXGrid": "grid", "AXCell": "cell", "AXRow": "row", "AXColumn": "column", "AXOutline": "outline", "AXToolbar": "toolbar", "AXTabGroup": "tab_group", "AXTab": "tab", "AXScrollArea": "scroll_area", "AXScrollBar": "scroll_bar", "AXWindow": "window", "AXSheet": "sheet", "AXDialog": "dialog", "AXPopover": "popover", "AXMenu": "menu", "AXMenuBar": "menu_bar", "AXMenuBarItem": "menu_bar_item", "AXMenuItem": "menu_item", "AXSplitGroup": "split_group", "AXSplitter": "splitter", "AXProgressIndicator": "progress", "AXBusyIndicator": "busy", "AXValueIndicator": "value_indicator", "AXLink": "link", "AXDisclosureTriangle": "disclosure",}
@dataclassclass AXElement: id: str role: str name: Optional[str] = None value: Optional[str] = None text: Optional[str] = None enabled: bool = True actions: list = field(default_factory=list) ref: object = field(default=None, repr=False)
_DYNAMIC_TEXT_PATTERNS = [ re.compile(r"^\d{1,2}:\d{2}(:\d{2})?(\s*[AP]M)?$"), re.compile(r"^\d{4}-\d{2}-\d{2}"), re.compile(r"^\d{1,2}/\d{1,2}/\d{2,4}$"),]
def _bundle_for_pid(pid): """Best-effort .app bundle path for a running pid (via its executable path).""" try: out = subprocess.run( ["ps", "-o", "comm=", "-p", str(int(pid))], capture_output=True, text=True, ).stdout.strip() except Exception: return "" marker = "/Contents/MacOS/" return out.split(marker)[0] if marker in out else ""
def is_electron_app(pid): """True if the app for `pid` is a Chromium-based app (Electron or CEF) whose web content AX tree stays empty unless launched with --force-renderer-accessibility. Detected by the presence of the Electron/CEF framework — precise, and does NOT false-positive on a native app that merely bundles a "* Helper.app" (XPC helper).""" bundle = _bundle_for_pid(pid) if not bundle: return False fw = bundle + "/Contents/Frameworks" return (os.path.isdir(fw + "/Electron Framework.framework") or os.path.isdir(fw + "/Chromium Embedded Framework.framework"))
def wait_for_web_ax(pid, timeout=8.0): """For Electron apps launched with --force-renderer-accessibility, the Chromium AXWebArea appears a few seconds after launch (async). Poll until it shows up so a read right after launch doesn't capture an empty window. Fast no-op for non-Electron apps (native/Gecko already expose AX). Best-effort; returns True when settled or when the app isn't Electron.""" try: if not is_electron_app(pid): return True app = AXUIElementCreateApplication(int(pid)) except Exception: return True try: AXUIElementSetMessagingTimeout(app, 5.0) except Exception: pass deadline = time.time() + timeout while time.time() < deadline: dq = deque([app]) seen = 0 while dq and seen < 8000: el = dq.popleft() seen += 1 err, role = AXUIElementCopyAttributeValue(el, "AXRole", None) if err == 0 and str(role) == "AXWebArea": return True # Chromium web content is built err, kids = AXUIElementCopyAttributeValue(el, "AXChildren", None) if err == 0 and kids: for k in kids: dq.append(k) time.sleep(0.5) return True
class AXHelper: def __init__(self, app_name_or_pid, wait_for_ready=True, ready_timeout=10, prime=True): if isinstance(app_name_or_pid, int): self._pid = app_name_or_pid else: self._pid = self._find_pid_by_name(app_name_or_pid) self._app_ref = AXUIElementCreateApplication(self._pid) self._element_cache = {}
# Electron apps launched with --force-renderer-accessibility build their # Chromium AXWebArea a few seconds after launch (async). Wait for it here so # the first real read sees full web content, not an empty window. Runs even # when wait_for_ready=False (e.g. the pytest `ax` fixture). Fast no-op for # non-Electron apps (native/Gecko already expose AX). if prime: wait_for_web_ax(self._pid)
if wait_for_ready: self._wait_until_ready(ready_timeout)
def _wait_until_ready(self, timeout): deadline = time.time() + timeout while time.time() < deadline: try: err, role = AXUIElementCopyAttributeValue(self._app_ref, "AXRole", None) if err == 0 and role: err, children = AXUIElementCopyAttributeValue( self._app_ref, "AXChildren", None ) if err == 0 and children and len(children) > 0: return except Exception: pass time.sleep(0.3) warnings.warn(f"AX tree for PID {self._pid} not ready after {timeout}s")
def _find_pid_by_name(self, name): search_name = name[:15] result = subprocess.run( ["pgrep", "-x", search_name], capture_output=True, text=True ) if result.returncode != 0: result = subprocess.run( ["pgrep", "-f", search_name], capture_output=True, text=True ) if result.returncode != 0: raise RuntimeError(f"Process '{name}' not found") return int(result.stdout.strip().split("\n")[0])
# ── Core API ──
def find( self, role=None, name=None, name_contains=None, value=None, enabled=None, max_results=50, root_id=None, max_depth=None, ): root_ref = self._get_ref(root_id) if root_id else self._app_ref results = []
def _recurse(ref, depth): if max_depth is not None and depth > max_depth: return if len(results) >= max_results: return el = self._ref_to_element(ref) if self._matches(el, role, name, name_contains, value, enabled): results.append(el) err, children = AXUIElementCopyAttributeValue(ref, "AXChildren", None) if err == 0 and children: for child in children: _recurse(child, depth + 1) if len(results) >= max_results: return
_recurse(root_ref, 0) return results
def action(self, element_id, action_name): ref = self._get_ref(element_id) if ref is None: return False try: err = AXUIElementPerformAction(ref, action_name) return err == 0 except Exception: return False
def action_checked(self, element_id, action_name): success = self.action(element_id, action_name) if not success: warnings.warn(f"Action '{action_name}' failed on {element_id}") return success
def click_element_cg(self, element_id): """Simulate a real mouse click at the element's screen position using CGEvent.
Use this when AXPress doesn't work — e.g. menu bar apps that use NSEvent.addLocalMonitorForEvents instead of button target-action. """ ref = self._get_ref(element_id) if ref is None: return False center = self._get_element_center(ref) if center is None: return False point = Quartz.CGPointMake(center[0], center[1]) event_down = Quartz.CGEventCreateMouseEvent( None, Quartz.kCGEventLeftMouseDown, point, Quartz.kCGMouseButtonLeft ) Quartz.CGEventPost(Quartz.kCGHIDEventTap, event_down) time.sleep(0.05) event_up = Quartz.CGEventCreateMouseEvent( None, Quartz.kCGEventLeftMouseUp, point, Quartz.kCGMouseButtonLeft ) Quartz.CGEventPost(Quartz.kCGHIDEventTap, event_up) return True
def get(self, element_id, attributes): # element_id=None 表示 APPLICATION 元素,与 find(root_id=None)/attribute_names(None) 一致。 # 否则 ax.get(None, ["AXTitle"]) 走不进元素缓存、返回 {},读 app 自身标题的 test 拿到 None。 ref = self._get_ref(element_id) if element_id else self._app_ref if ref is None: return {} result = {} for attr in attributes: try: err, val = AXUIElementCopyAttributeValue(ref, attr, None) if err == 0: result[attr] = self._serialize_value(val) else: result[attr] = None except Exception: result[attr] = None return result
def activate(self): """把本 helper 绑定的 app 提到前台,返回是否成功。
有些 toolkit 只在进程被 ACTIVATED 时才装原生菜单栏:olive(Qt)启动后 90s 仍只有 ['Apple','Olive'];zotero(Gecko/XUL)一直只有 ['Apple','Zotero','File','Window'], 且搜索框会吞掉合成键。一次激活即补齐。用 AX API 设 AXFrontmost 会返回成功但无效, 所以走 NSRunningApplication。 """ try: from AppKit import NSRunningApplication except Exception: return False try: app = NSRunningApplication.runningApplicationWithProcessIdentifier_(int(self._pid)) if app is None: return False return bool(app.activateWithOptions_(1 << 1)) # IgnoringOtherApps except Exception: return False
def set_value(self, element_id, value): ref = self._get_ref(element_id) if ref is None: return False try: err = AXUIElementSetAttributeValue(ref, "AXValue", value) return err == 0 except Exception: return False
# ── Attribute Introspection ──
def attribute_names(self, element_id=None): ref = self._get_ref(element_id) if element_id else self._app_ref if ref is None: return [] try: err, names = AXUIElementCopyAttributeNames(ref, None) if err == 0 and names: return list(names) except Exception: pass return []
def is_attribute_settable(self, element_id, attribute): ref = self._get_ref(element_id) if ref is None: return False try: err, settable = AXUIElementIsAttributeSettable(ref, attribute, None) return err == 0 and bool(settable) except Exception: return False
def attribute_value_count(self, element_id, attribute): ref = self._get_ref(element_id) if ref is None: return 0 try: err, count = AXUIElementGetAttributeValueCount(ref, attribute, None) return count if err == 0 else 0 except Exception: return 0
def attribute_values_range(self, element_id, attribute, index, count): ref = self._get_ref(element_id) if ref is None: return [] try: err, values = AXUIElementCopyAttributeValues(ref, attribute, index, count, None) if err == 0 and values: return [self._serialize_value(v) for v in values] except Exception: pass return []
def get_multiple(self, element_id, attributes): ref = self._get_ref(element_id) if ref is None: return {} try: err, values, errors = AXUIElementCopyMultipleAttributeValues( ref, attributes, 0, None, None ) if err == 0 and values: result = {} for i, attr in enumerate(attributes): if i < len(values): result[attr] = self._serialize_value(values[i]) else: result[attr] = None return result except Exception: pass return self.get(element_id, attributes)
# ── Parameterized Attributes ──
def parameterized_attribute_names(self, element_id=None): ref = self._get_ref(element_id) if element_id else self._app_ref if ref is None: return [] try: err, names = AXUIElementCopyParameterizedAttributeNames(ref, None) if err == 0 and names: return list(names) except Exception: pass return []
def parameterized_attribute_value(self, element_id, attribute, parameter): ref = self._get_ref(element_id) if ref is None: return None try: err, value = AXUIElementCopyParameterizedAttributeValue( ref, attribute, parameter, None ) if err == 0: return self._serialize_value(value) except Exception: pass return None
# ── Action Introspection ──
def action_description(self, element_id, action_name): ref = self._get_ref(element_id) if ref is None: return "" try: err, desc = AXUIElementCopyActionDescription(ref, action_name, None) if err == 0 and desc: return str(desc) except Exception: pass return ""
# ─��� Position / PID / Timeout ──
def element_at_position(self, x, y): try: sys_ref = AXUIElementCreateSystemWide() err, el_ref = AXUIElementCopyElementAtPosition(sys_ref, float(x), float(y), None) if err == 0 and el_ref: element = self._ref_to_element(el_ref) return element except Exception: pass return None
def get_pid(self, element_id=None): ref = self._get_ref(element_id) if element_id else self._app_ref if ref is None: return -1 try: err, pid = AXUIElementGetPid(ref, None) return pid if err == 0 else -1 except Exception: return -1
def set_messaging_timeout(self, element_id, timeout_seconds): ref = self._get_ref(element_id) if element_id else self._app_ref if ref is None: return False try: err = AXUIElementSetMessagingTimeout(ref, float(timeout_seconds)) return err == 0 except Exception: return False
@staticmethod def create_system_wide(): return AXUIElementCreateSystemWide()
def tree(self, max_depth=5, root_id=None): root_ref = self._get_ref(root_id) if root_id else self._app_ref
def _build(ref, depth): el = self._ref_to_element(ref) node = { "role": el.role, "name": el.name, "id": el.id, "actions": el.actions, } if el.value: node["value"] = str(el.value)[:100] if depth < max_depth: err, children = AXUIElementCopyAttributeValue(ref, "AXChildren", None) if err == 0 and children: node["children"] = [_build(c, depth + 1) for c in children] return node
return _build(root_ref, 0)
def list_apps(self): from AppKit import NSWorkspace
apps = NSWorkspace.sharedWorkspace().runningApplications() return [ { "name": app.localizedName(), "pid": app.processIdentifier(), "bundle_id": app.bundleIdentifier() or "", "type": "regular" if app.activationPolicy() == 0 else "accessory", } for app in apps if app.activationPolicy() in (0, 1) ]
# ── Capability-based Search ──
def find_clickable(self, root_id=None, max_results=50): all_elements = self._walk_tree(root_id, max_results * 3) clickable = [] for el in all_elements: if "AXPress" in el.actions or "AXConfirm" in el.actions: subrole = self._get_attr(el.ref, "AXSubrole", "") if subrole in ( "AXCloseButton", "AXMinimizeButton", "AXZoomButton", "AXFullScreenButton", ): continue clickable.append(el) if len(clickable) >= max_results: break return clickable
def find_text_elements(self, root_id=None, max_results=100): all_elements = self._walk_tree(root_id, max_results * 3) text_elements = [] for el in all_elements: text = ( self._get_attr(el.ref, "AXValue", "") or self._get_attr(el.ref, "AXTitle", "") or self._get_attr(el.ref, "AXDescription", "") or el.name or "" ) if isinstance(text, str) and text.strip(): el.text = text.strip() text_elements.append(el) if len(text_elements) >= max_results: break return text_elements
def find_value_settable(self, root_id=None, max_results=20): all_elements = self._walk_tree(root_id, max_results * 3) settable = [] for el in all_elements: try: err, is_settable = AXUIElementIsAttributeSettable( el.ref, "AXValue", None ) if err == 0 and is_settable: settable.append(el) if len(settable) >= max_results: break except Exception: continue return settable
def find_togglable(self, root_id=None, max_results=20): all_elements = self._walk_tree(root_id, max_results * 3) togglable = [] for el in all_elements: if "AXPress" in el.actions: value = self._get_attr(el.ref, "AXValue", None) if value in (0, 1, True, False, "0", "1"): togglable.append(el) if len(togglable) >= max_results: break return togglable
# ── Text Snapshot ──
def snapshot_all_text(self, exclude_dynamic=True): text_elements = self.find_text_elements(max_results=200) texts = [] for el in text_elements: text = el.text if exclude_dynamic and any( p.match(text) for p in _DYNAMIC_TEXT_PATTERNS ): continue texts.append(text) return Counter(texts)
def wait_for_text_change(self, original_text, timeout=3.0): deadline = time.time() + timeout while time.time() < deadline: current = self.snapshot_all_text() if current != original_text: return current time.sleep(0.2) return self.snapshot_all_text()
def wait_for(self, role=None, name=None, timeout=5.0, max_results=1): deadline = time.time() + timeout while time.time() < deadline: results = self.find(role=role, name=name, max_results=max_results) if results: return results time.sleep(0.3) return []
# ── Verifier Helpers ──
def find_safe_buttons(self, max_results=20): clickable = self.find_clickable(max_results=max_results * 2) safe = [] for el in clickable: name_lower = (el.name or "").lower() if any( kw in name_lower for kw in [ "quit", "delete", "remove", "erase", "reset", "clear all", "uninstall", ] ): continue safe.append(el) if len(safe) >= max_results: break return safe
def ensure_ui_visible(self): _CONTAINER_ROLES = ["window", "popover", "group", "sheet"] # Menu-item labels that reveal the main UI via a Settings/Preferences # window (EN + ZH). Kept deliberately narrow and high-signal: broader # verbs like "open"/"show" risk pressing File-menu items such as # "Open…" that pop a file dialog instead of revealing the main UI. _REVEAL_KW = ("preference", "settings", "偏好", "设置")
def _visible(): # max_depth=12 (was 3): status-item / menu-bar popovers sit ~7-8 levels # deep in the AX tree, so a depth-3 check reported "not visible" even # after the popover opened -> reveal loops gave up / tests saw no UI. for role in _CONTAINER_ROLES: if self.find(role=role, max_results=1, max_depth=12): return True return False
if _visible(): return True menu_items = self.find(role="menu_bar_item", max_results=8, max_depth=3) for item in menu_items: self.action(item.id, "AXPress") time.sleep(0.5) if _visible(): return True # Two-level reveal: pressing the status/menu-bar item may open a MENU # (not the window). A valid recreation can wire it as # icon -> menu -> "Preferences…" -> window. Click a reveal item. for mi in self.find(role="menu_item", max_results=40, max_depth=6): name = (mi.name or "").lower() if name and any(k in name for k in _REVEAL_KW): self.action(mi.id, "AXPress") time.sleep(0.5) if _visible(): return True # AXPress may not work for apps using NSEvent mouse monitoring; # fall back to a real CGEvent click at the element's position. self.click_element_cg(item.id) time.sleep(1.0) if _visible(): return True # Preferences hotkey (⌘,) — standard macOS "show settings" trigger. # Guarded so this method preserves its contract of never raising # (osascript can hit the subprocess timeout). try: subprocess.run( [ "osascript", "-e", 'tell application "System Events" to ' 'keystroke "," using command down', ], capture_output=True, timeout=3, ) time.sleep(0.5) except Exception: pass return _visible()
def dismiss_any_dialog(self): for role in ["sheet", "dialog"]: dialogs = self.find(role=role, max_results=3, max_depth=3) for dlg in dialogs: buttons = self.find(role="button", root_id=dlg.id, max_results=10) for btn in buttons: name_lower = (btn.name or "").lower() if name_lower in ( "cancel", "ok", "close", "dismiss", "don't save", ): self.action(btn.id, "AXPress") time.sleep(0.3) return True subprocess.run( [ "osascript", "-e", 'tell application "System Events" to key code 53', ], capture_output=True, timeout=2, ) time.sleep(0.3) return True return False
def get_main_window(self): windows = self.find(role="window", max_results=10, max_depth=1) if not windows: return None if len(windows) == 1: return windows[0].id for w in windows: attrs = self.get(w.id, ["AXMain"]) if attrs.get("AXMain"): return w.id best, best_area = None, 0 for w in windows: attrs = self.get(w.id, ["AXSize"]) size = attrs.get("AXSize") if size is not None: area = getattr(size, "width", 0) * getattr(size, "height", 0) else: area = 0 if area > best_area: best_area = area best = w.id return best
# ── Internal ──
def _walk_tree(self, root_id, max_count): root_ref = self._get_ref(root_id) if root_id else self._app_ref results = []
def _recurse(ref): if len(results) >= max_count: return el = self._ref_to_element(ref) results.append(el) err, children = AXUIElementCopyAttributeValue(ref, "AXChildren", None) if err == 0 and children: for child in children: _recurse(child) if len(results) >= max_count: return
_recurse(root_ref) return results
def _ref_to_element(self, ref): el_id = str(hash(ref)) self._element_cache[el_id] = ref
role_raw = self._get_attr(ref, "AXRole", "") role = ROLE_MAP.get( role_raw, role_raw.replace("AX", "").lower() if role_raw else "unknown", ) name = self._get_attr(ref, "AXTitle", "") or self._get_attr( ref, "AXDescription", "" ) value = self._get_attr(ref, "AXValue", "") enabled = self._get_attr(ref, "AXEnabled", True)
actions = [] try: err, action_names = AXUIElementCopyActionNames(ref, None) if err == 0 and action_names: actions = list(action_names) except Exception: pass
return AXElement( id=el_id, role=role, name=name, value=value, enabled=enabled, actions=actions, ref=ref, )
def _get_ref(self, element_id): return self._element_cache.get(element_id)
def _get_element_center(self, ref): """Return (x, y) screen coordinates of the element's center, or None.""" pos_val = self._get_attr(ref, "AXPosition", None) size_val = self._get_attr(ref, "AXSize", None) if pos_val is None or size_val is None: return None pos_str = str(pos_val) size_str = str(size_val) pos_nums = re.findall(r"[-\d.]+", pos_str) size_nums = re.findall(r"[-\d.]+", size_str) if len(pos_nums) < 2 or len(size_nums) < 2: return None px, py = float(pos_nums[-2]), float(pos_nums[-1]) sw, sh = float(size_nums[-2]), float(size_nums[-1]) return (px + sw / 2, py + sh / 2)
def _get_attr(self, ref, attr_name, default=None): try: err, val = AXUIElementCopyAttributeValue(ref, attr_name, None) return val if err == 0 else default except Exception: return default
def _matches(self, el, role, name, name_contains, value, enabled): if role and el.role != role: return False if name and el.name != name: return False if name_contains and (not el.name or name_contains not in el.name): return False if value is not None and el.value != value: return False if enabled is not None and el.enabled != enabled: return False return True
def _serialize_value(self, val): if val is None: return None if isinstance(val, (str, int, float, bool)): return val if hasattr(val, "width") and hasattr(val, "height"): return {"width": val.width, "height": val.height} if hasattr(val, "x") and hasattr(val, "y"): return {"x": val.x, "y": val.y} return str(val)
def _pid_by_name(name): """Resolve a pid from a process name using the same MAXCOMLEN(15)/pgrep logic the stage shells use.""" s = name[:15] r = subprocess.run(["pgrep", "-x", s], capture_output=True, text=True) if r.returncode != 0: r = subprocess.run(["pgrep", "-f", s], capture_output=True, text=True) if r.returncode != 0: return None out = r.stdout.strip() return int(out.split("\n")[0]) if out else None123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584"""conftest.py template for verifiers.
Provides fixtures: app_path, app_process, ax, ax_with_reset, open_panel.Each test gets a fresh app instance — app is launched before and killed after every test."""
import jsonimport osimport signalimport subprocessimport tempfileimport time
import pytest
# ── RB TestGen kit: depth/jump declaration capture ──────────────────────────# Tests declare navigation depth + jump rigor via @pytest.mark.rb(depth=, jump_kind=,# expect=). This hook records the declaration + outcome so the runner can fold# depth/jump/tier/expect into <module>_results.json (rb_audit/rb_lint read them).# The record's `passed` is informational — the runner keeps pytest's exit code as the# authoritative pass/fail, so a teardown-phase failure (e.g. app crash check) is never# masked by a call-phase pass here._RB_TIER = {"none": 0, "liveness": 1, "reach": 2, "transition": 2, "value": 3}
def pytest_configure(config): config.addinivalue_line( "markers", "rb(depth, jump_kind, expect): declare navigation depth + jump rigor (RB TestGen kit)", )
@pytest.hookimpl(hookwrapper=True)def pytest_runtest_makereport(item, call): outcome = yield rep = outcome.get_result() if rep.when != "call": return rec_path = os.environ.get("RB_RECORD_FILE", "") if not rec_path: return m = item.get_closest_marker("rb") depth, jump_kind, expect = 0, "none", "" if m is not None: if m.args: try: depth = int(m.args[0]) except Exception: depth = 0 try: depth = int(m.kwargs.get("depth", depth) or 0) except Exception: depth = 0 jump_kind = m.kwargs.get("jump_kind", "none") or "none" expect = m.kwargs.get("expect", "") or "" if jump_kind not in _RB_TIER: jump_kind = "none" rec = { "name": item.nodeid, "passed": bool(rep.passed), "depth": max(0, int(depth)), "jump_kind": jump_kind, "tier": _RB_TIER[jump_kind], "expect": str(expect), } try: d = os.path.dirname(rec_path) if d: os.makedirs(d, exist_ok=True) with open(rec_path, "w") as f: json.dump(rec, f) except Exception: pass
def _find_pid_by_name(name): # macOS kernel truncates process names to 16 chars (MAXCOMLEN). # Drop -x (exact match) and use substring match so name[:15] still # matches the 16-char truncated kernel name. search = name[:15] result = subprocess.run( ["pgrep", search], capture_output=True, text=True, timeout=5) if result.returncode != 0: return None pids = result.stdout.strip().split("\n") return int(pids[0]) if pids and pids[0] else None
def _kill_pid(pid): try: os.kill(pid, signal.SIGTERM) time.sleep(1) os.kill(pid, 0) os.kill(pid, signal.SIGKILL) except ProcessLookupError: pass
def _find_all_pids_by_name(name): search = name[:15] result = subprocess.run( ["pgrep", search], capture_output=True, text=True, timeout=5) if result.returncode != 0: return [] return [int(p) for p in result.stdout.strip().split("\n") if p.strip()]
def _kill_existing_app(binary_name): # Kill ALL instances matching the name (not just the first). Otherwise a # still-running reference app (same binary name, launched in stage3/4) lingers # into the test run and can be scored in place of the recreation. Target # disambiguation for the process we actually test is done by executable PATH # in _resolve_target_pid below. if not binary_name: return for pid in _find_all_pids_by_name(binary_name): _kill_pid(pid) time.sleep(0.5)
def _get_all_pids(): result = subprocess.run(["ps", "-axo", "pid="], capture_output=True, text=True) return [int(p.strip()) for p in result.stdout.splitlines() if p.strip().isdigit()]
def _get_process_name(pid): # Use args= (full command line) instead of comm= which is truncated to # 16 chars (MAXCOMLEN) by the macOS kernel — breaks detection for long # binary names like "MacOSReachabilityTestARC" (24 chars). result = subprocess.run( ["ps", "-p", str(pid), "-o", "args="], capture_output=True, text=True) if result.returncode == 0 and result.stdout.strip(): exe = result.stdout.strip().split()[0] name = os.path.basename(exe) if name: return name result = subprocess.run( ["ps", "-p", str(pid), "-o", "comm="], capture_output=True, text=True) return os.path.basename(result.stdout.strip()) if result.returncode == 0 else None
def _get_process_args(pid): """Full command line (executable path + args) for a pid, kept WHOLE (not split). Substring tests on this are space-safe — Electron helpers like 'Foo Helper (GPU)' and bundle paths with spaces are matched correctly, unlike args.split()[0] which breaks at the first space.""" try: r = subprocess.run(["ps", "-p", str(pid), "-o", "args="], capture_output=True, text=True, timeout=5) if r.returncode == 0 and r.stdout.strip(): return r.stdout.strip() except Exception: pass return ""
# Command-line markers identifying the REFERENCE app (the ground-truth app kept# running from stage3/4). It always runs from a pipeline-internal path; the# recreation never does. A process whose command line contains one of these must# never be scored — this is what stops a crashed/absent recreation from being# silently scored as the still-running reference._REFERENCE_PATH_MARKERS = (".pipeline_refapp", "/pipeline_work/")
def _is_reference_proc(pid): a = _get_process_args(pid) return any(m in a for m in _REFERENCE_PATH_MARKERS)
def _args_under_app(pid, app_path): """True iff the pid's EXECUTABLE runs from inside app_path (it IS the app) — NOT a launcher like `open -W <bundle>` whose ARGUMENT merely contains the bundle path.
A running .app's argv0 is <bundle>/Contents/MacOS/<binary>, so we require that inner executable path. The old bare-substring test (`app_path in args`) also matched the lingering `open -W <bundle>` process launch.sh leaves behind (`exec open -W …`); that launcher has NO AX tree, so the fixture bound to it → every element lookup returned nothing → reference-app baseline ~0% → the whole suite was pruned to 0.""" if not app_path: return False args = _get_process_args(pid) ap = app_path.rstrip("/") if ap.endswith(".app"): # The real GUI process: argv0 == <bundle>/Contents/MacOS/<binary>. return (ap + "/Contents/MacOS/") in args # Non-bundle executable: require it as argv0 (command starts with it), not merely # mentioned as a later argument (which is how `open <path>` would match). return args == ap or args.startswith(ap + " ")
# Electron/CEF helper subprocesses live inside the app bundle too but are NOT the# app. Identified by a --type= switch (renderer/gpu-process/utility) or a# "Helper (...)" executable — matched on the full command line (space-safe)._HELPER_MARKERS = ("--type=", " Helper", "(GPU)", "(Renderer)", "(Plugin)", "(CEF")
def _is_helper_proc(pid): a = _get_process_args(pid) return any(m in a for m in _HELPER_MARKERS)
def _name_matches(pid, names): pname = _get_process_name(pid) if not pname: return False for cand in names: if cand and (pname == cand or cand.lower() in pname.lower() or pname.lower() in cand.lower()): return True return False
def _resolve_target_pid(candidate_pids, app_path, binary_name, app_dir_name, app_name_env): """Pick the process of the APP UNDER TEST — never a sibling reference, never a helper.
app_path is the app we were told to test: the OFFICIAL app at stage2 baseline (built under ~/pipeline_work/<app>/source/App.app) and the RECREATION at stage5 eval. In both cases a process running from INSIDE app_path IS the target and must be selected — even though that path lives under /pipeline_work/.
Selection order: 1. the non-helper process running from INSIDE app_path (exact path match), checked BEFORE any reference-marker filtering — a process that literally runs from app_path can never be the "other" app, so it is always eligible. 2. name match, for launch.sh setups that run the app from a build/DerivedData path DIFFERENT from app_path (very common: OFFICIAL_APP points at source/build/.../Release/App.app while launch.sh starts source/App.app). The reference (.pipeline_refapp) and helpers are excluded here.
BUGFIX (baseline 0% root cause): the reference markers used to be a flat (".pipeline_refapp", "/pipeline_work/") pre-filter applied to ALL candidates. But the OFFICIAL app under test at stage2 baseline is itself built under ~/pipeline_work/<app>/... — so the "/pipeline_work/" marker excluded the only running instance, _resolve_target_pid returned None -> conftest raised `Could not find process` -> every baseline test errored -> the suite was pruned to 0 -> the app went unscored. And the exact-path match in step 1 does NOT save it, because launch.sh frequently starts the app from a /pipeline_work/ sub-path that differs from OFFICIAL_APP (source/App.app vs source/build/.../App.app). Fix: suppress the broad "/pipeline_work/" marker when the app under test is ITSELF under /pipeline_work/ (i.e. baseline). ".pipeline_refapp" is always excluded. At stage5 eval the recreation lives under ~/Recreation (NOT /pipeline_work/), so app_in_pw is False there and the "/pipeline_work/" marker still fires to keep the official reference from ever being scored — preserving commit 99d3cef's intent. """ if app_path: for p in candidate_pids: if _args_under_app(p, app_path) and not _is_helper_proc(p): return p app_in_pw = bool(app_path) and "/pipeline_work/" in app_path
def _is_ref_here(pid): a = _get_process_args(pid) if ".pipeline_refapp" in a: return True if not app_in_pw and "/pipeline_work/" in a: return True return False
names = (binary_name, app_dir_name, app_name_env) for p in candidate_pids: if (not _is_helper_proc(p) and not _is_ref_here(p) and _name_matches(p, names)): return p return None
def _get_binary_name(app_path): if app_path: info_plist = os.path.join(app_path, "Contents", "Info.plist") if os.path.exists(info_plist): result = subprocess.run( ["defaults", "read", info_plist, "CFBundleExecutable"], capture_output=True, text=True, timeout=5) if result.returncode == 0: return result.stdout.strip() return os.environ.get("APP_BINARY") or os.environ.get("APP_NAME") or None
def _get_bundle_id(app_path): info_plist = os.path.join(app_path, "Contents", "Info.plist") if os.path.exists(info_plist): result = subprocess.run( ["defaults", "read", info_plist, "CFBundleIdentifier"], capture_output=True, text=True, timeout=5) if result.returncode == 0: return result.stdout.strip() return None
def _grant_tcc_permissions(bundle_id): """Grant all common TCC permissions to the app so system dialogs don't block tests.""" if not bundle_id: return tcc_db = os.path.expanduser( "~/Library/Application Support/com.apple.TCC/TCC.db") if not os.path.exists(tcc_db): return services = [ "kTCCServiceAccessibility", "kTCCServiceScreenCapture", "kTCCServiceAppleEvents", "kTCCServicePostEvent", "kTCCServiceListenEvent", "kTCCServiceSystemPolicyAllFiles", "kTCCServiceDeveloperTool", "kTCCServiceCalendar", "kTCCServiceAddressBook", "kTCCServiceContactsFull", "kTCCServiceContactsLimited", "kTCCServiceReminders", "kTCCServicePhotos", "kTCCServicePhotosAdd", "kTCCServiceCamera", "kTCCServiceMicrophone", "kTCCServiceBluetoothAlways", "kTCCServiceMediaLibrary", "kTCCServiceSpeechRecognition", "kTCCServiceMotion", "kTCCServiceLocation", "kTCCServiceFocusStatus", "kTCCServiceSystemPolicyDesktopFolder", "kTCCServiceSystemPolicyDocumentsFolder", "kTCCServiceSystemPolicyDownloadsFolder", "kTCCServiceSystemPolicyNetworkVolumes", "kTCCServiceSystemPolicyRemovableVolumes", "kTCCServiceFileProviderDomain", "kTCCServiceFileProviderPresence", ] now = str(int(time.time())) for svc in services: subprocess.run( ["sqlite3", tcc_db, f"INSERT OR REPLACE INTO access" f" (service, client, client_type, auth_value, auth_reason, auth_version," f" csreq, policy_id, indirect_object_identifier_type," f" indirect_object_identifier, indirect_object_code_identity," f" flags, last_modified, pid, pid_version, boot_uuid, last_reminded)" f" VALUES ('{svc}', '{bundle_id}', 0, 2, 0, 1," f" NULL, NULL, NULL, 'UNUSED', NULL, NULL, {now}, NULL, NULL, 'UNUSED', {now});"], capture_output=True, timeout=5)
def _clear_autosaved_documents(app_path, bundle_id=""): """Drop the app's UNSAVED documents from ~/Library/Autosave Information/.
macOS restores an unsaved document of a document-based app on the NEXT launch, and neither `defaults delete` nor removing the .savedState touches that directory. A test that types into the editor therefore leaks its content into the FOLLOWING test's launch state. Measured on MaciASL: after one test set the editor text, every later test came up with an 'Untitled' window still holding that text (OEM ID "RBTEST") instead of the app opening the machine's System DSDT, which failed 4 of its own baseline tests. Clearing this directory restored window 'System DSDT', a 92 KB editor and OEM ID "BOCHS ".
Scoped to entries naming the app under test (bundle name / bundle id), so an unrelated app's autosave is never touched. """ base = os.path.expanduser("~/Library/Autosave Information") if not os.path.isdir(base): return names = set() stem = os.path.basename(app_path or "").replace(".app", "").strip() if stem: names.add(stem.lower()) if bundle_id: names.add(bundle_id.lower()) names.add(bundle_id.rsplit(".", 1)[-1].lower()) if not names: return try: entries = os.listdir(base) except OSError: return for entry in entries: low = entry.lower() if any(n in low for n in names): subprocess.run(["rm", "-rf", os.path.join(base, entry)], capture_output=True, timeout=5)
def _reset_app_state(app_path): bundle_id = _get_bundle_id(app_path) # Autosaved documents survive an app with no readable bundle id too, so clear first. _clear_autosaved_documents(app_path, bundle_id or "") if not bundle_id: return subprocess.run(["defaults", "delete", bundle_id], capture_output=True, timeout=5) saved_state = os.path.expanduser( f"~/Library/Saved Application State/{bundle_id}.savedState") if os.path.isdir(saved_state): subprocess.run(["rm", "-rf", saved_state], capture_output=True, timeout=5)
def _activate_app(pid): """Bring the launched app frontmost (by pid) so interaction/menu tests hit the RIGHT app. Tests that open menus, send System Events keystrokes, or drive the frontmost app fail spuriously when it is merely launched-but-background (the case under automated per-test relaunch — nothing foregrounds it).
Uses NSRunningApplication.activateWithOptions_ (robust, by pid) — verified on a sandbox VM to return True and set frontmost. NOT osascript: the System Events 'process whose unix id is N' selector is unreliable (errors -1719 on Electron helper pids etc.). AX reads via the app_ref work regardless, so best-effort.""" try: from AppKit import NSRunningApplication app = NSRunningApplication.runningApplicationWithProcessIdentifier_(int(pid)) if app is not None: app.activateWithOptions_(1 << 1) # NSApplicationActivateIgnoringOtherApps except Exception: pass
def _launch_app(app_path): binary_name = _get_binary_name(app_path) _kill_existing_app(binary_name) if app_path: _reset_app_state(app_path)
before_pids = set(_get_all_pids())
launch_sh = os.environ.get("LAUNCH_SH", "") launch_proc = None launch_err_path = None if launch_sh and os.path.isfile(launch_sh): launch_err_fd, launch_err_path = tempfile.mkstemp(suffix="_launch.log") launch_err_file = os.fdopen(launch_err_fd, "w") launch_proc = subprocess.Popen( ["bash", launch_sh], stdout=subprocess.DEVNULL, stderr=launch_err_file) launch_err_file.close() elif app_path: subprocess.run(["open", app_path], check=True) else: pytest.fail("No APP_PATH and no LAUNCH_SH — cannot launch app")
pid = None app_dir_name = os.path.basename(app_path).replace(".app", "") if app_path else "" app_name_env = os.environ.get("APP_NAME", "") # Bind to the RECREATION only. When app_path is known we require a process # running from inside that bundle (path match) — immune to the reference app # sharing the same binary name. Reference processes are always excluded, so a # crashed / never-launched recreation resolves to None → the test fails (score # 0) instead of silently scoring the still-running reference. for _ in range(30): new_pids = set(_get_all_pids()) - before_pids pid = _resolve_target_pid(new_pids, app_path, binary_name, app_dir_name, app_name_env) if pid: break time.sleep(0.5)
# Fallback: launch.sh may have activated a pre-launched instance (no new pid, # e.g. `open` without -n). Search ALL pids — still restricted to the recreation # bundle (path match) / reference-excluded. if pid is None: pid = _resolve_target_pid(_get_all_pids(), app_path, binary_name, app_dir_name, app_name_env)
if pid is None: launch_stderr = "" if launch_err_path: try: if launch_proc: launch_proc.wait(timeout=2) with open(launch_err_path) as f: launch_stderr = f.read()[:500] except Exception: pass _dbg = subprocess.run( ["ps", "-axo", "pid,comm,args"], capture_output=True, text=True ).stdout[:3000] assert False, ( f"Could not find process for {app_path or launch_sh} within 15s.\n" f"binary_name={binary_name}, app_dir_name={app_dir_name}, " f"app_name_env={app_name_env}\n" f"launch stderr: {launch_stderr or '(empty)'}\n" f"Active processes (pid,comm,args):\n{_dbg}" )
if launch_err_path: try: os.unlink(launch_err_path) except OSError: pass # Bring the app frontmost BEFORE settling/AX-ready: menu-bar reads, opened menus, # and System Events keystrokes all target the frontmost app; a launched-but- # background app makes those tests fail spuriously (root cause of the mass 0% # baselines). Best-effort — AX reads via app_ref are unaffected. _activate_app(pid) # Electron apps are launched (via launch.sh, which build/recreation inject with # --force-renderer-accessibility) so their Chromium AXWebArea builds a few seconds # after launch; the AXHelper `ax` fixture then waits for it. Give the process a # moment to come up first. time.sleep(2) return pid
@pytest.fixture(scope="session")def app_path(): path = os.environ.get("APP_PATH", "") launch_sh = os.environ.get("LAUNCH_SH", "") if not path or not os.path.isdir(path): if launch_sh and os.path.isfile(launch_sh): return "" assert False, ( f"APP_PATH not set or invalid: '{path}', and no LAUNCH_SH found. " "Set via: export APP_PATH=/path/to/App.app or export LAUNCH_SH=/path/to/launch.sh" ) bundle_id = _get_bundle_id(path) if bundle_id: _grant_tcc_permissions(bundle_id) return path
@pytest.fixturedef app_process(app_path): pid = _launch_app(app_path) yield pid _kill_pid(pid)
@pytest.fixturedef ax(app_process): from ax_helpers import AXHelper # wait_for_ready=True: AXHelper._wait_until_ready() polls the app's AX tree until # it reports AXChildren>0 before the first query (default True, 10s). This was # explicitly set to False, so every test queried an app that may not be AX-ready # yet — under per-test relaunch + VM load the tree is still empty → element lookups # return nothing → `assert False` → the test fails on the REFERENCE app → 0% # baseline → the whole suite gets pruned to 0. Same fixture is used by stage2 # baseline (over-prune) AND stage5 eval (recreated app scored spuriously low), so # this one flag corrupted both. Restore the wait (the _launch_app comment already # states the fixture "waits for it"). # ready_timeout=45 (was default 10): heavy apps (Qt video editors like olive, # large Electron) need >10s for AXChildren>0 after a per-test relaunch under VM # load. At 10s the wait warned-and-proceeded on a still-empty tree → element # lookups returned nothing → assert False → ALL tests fail baseline on the # OFFICIAL app → the whole suite is pruned to empty (observed: olive 53 real # tests all pruned). A working app reaches AXChildren>0 in <10s so this only # costs time on genuinely-slow apps; it never false-fails a working one. return AXHelper(app_process, wait_for_ready=True, ready_timeout=45)
@pytest.fixturedef ax_with_reset(ax): import verifier_helpers as helpers helpers.ensure_panel_open(ax) yield ax helpers.dismiss_menus(ax)
@pytest.fixture(autouse=True)def check_app_alive(app_process): yield try: os.kill(app_process, 0) except ProcessLookupError: pytest.fail(f"App process {app_process} crashed during test")
@pytest.fixture(scope="session", autouse=True)def check_ax_permission(): try: import ApplicationServices trusted = ApplicationServices.AXIsProcessTrusted() if not trusted: pytest.exit("Process does not have Accessibility permission") except ImportError: pass
@pytest.fixture(scope="session")def official_screenshots_dir(): """Path to the directory containing official app screenshots (ground truth). Set via OFFICIAL_SCREENSHOTS_DIR env var; defaults to ./official_screenshots/""" d = os.environ.get("OFFICIAL_SCREENSHOTS_DIR", os.path.join(os.path.dirname(__file__), "official_screenshots")) if not os.path.isdir(d): # A-ii: FAIL, don't skip. A missing official-screenshot baseline means this # visual test has no ground truth → it must be pruned (counted as failed), never # silently skipped. The runner treats skip as fail anyway; failing here is explicit # and keeps the "no skip — unimplemented/missing == fail" invariant. pytest.fail(f"Official screenshots dir not found: {d}") return d
@pytest.fixture(scope="session")def recreated_screenshots_dir(tmp_path_factory): """Temporary directory for recreated app screenshots during test run.""" return str(tmp_path_factory.mktemp("recreated_screenshots"))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575#!/usr/bin/env python3"""RB TestGen Kit (macOS/AX port of the Linux v7.5 kit) — a test's NAVIGATIONDEPTH and JUMP RIGOR are DECLARED (not inferred), uniformly recorded, andself-auditable.
DIFFERENCE FROM LINUX: macOS tests are **pytest** (methods on Test* classes takingthe `ax` fixture, plain asserts) — NOT standalone scripts calling R.record(). So theDECLARATION 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 andwrites {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 isdepth 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 astimport globimport jsonimport osimport 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]}")123pytestpytest-checkpyobjc123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681"""AX BUTTON tests for UVtools 4.4.2 (macos-sn4k3-uvtools).
Every test asserts the OBSERVED CONSEQUENCE of pressing a button (a value change, atext change, an enabled-state flip, a new surface) — never "the button exists".
Locators follow recon's AX QUIRKS: UVtools is Avalonia, so push buttons expose AXPressbut carry junk AXTitles ("Avalonia.Controls.PathIcon"). Buttons are therefore found bythe label rendered inside them (uv.find_button_by_label), by their real AXTitle wherethey have one (SB/LB/SN/LN -> uv.find_button_by_name) or by AXIdentifier(uv.find_by_identifier). Every widget lookup goes through the validated uv_helpers sothe SAME test drives the reference app and a recreation.
NEVER activated here (recon's destructive list): the Issues-tab `Detect` button, theBenchmark `Start` button, and every `Actions > ...` layer item (they mutate/export theloaded file). The Actions drop-down is only OPENED and inspected."""
import os, sys, timeimport pytestsys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))import rb_testgen_kit as kitimport uv_helpers as uv
RESULTS_DIR = os.environ.get("RESULTS_DIR", "/tmp")
def _outline_showing(ax): """rb_showing extended with the Outline popup's check items.
kit.rb_showing() walks to depth 12; the overlay check items inside the Outline drop-down sit well below that cap, so a plain snapshot cannot witness them appearing. Adding the (role-filtered, cheap) checkbox names keeps the before/after comparison honest without paying for a full deep tree walk. """ snap = set(kit.rb_showing(ax)) snap |= {"checkbox|%s" % name for name in uv.checkbox_map(ax)} return snap
# ── ground truth from recon (demo file auto-loaded: 10 layers, 2 thumbnails) ──THUMB_1 = "1/2"THUMB_2 = "2/2"THUMB_1_RES = "{Width: 400, Height: 400}"THUMB_2_RES = "{Width: 800, Height: 480}"LAYER0_TIP_MM = "0.100mm"LAYER0_TIP_PCT = "10%"LAYER9_TIP_MM = "1.000mm"LAYER9_TIP_PCT = "100%"LAYER0_PIXELS = "486195"LAYER9_PIXELS = "568399"LAYER0_VOLUME = "Volume: 121.55mm"LAYER9_VOLUME = "Volume: 142.10mm"ZOOM_UNROTATED = 0.55ZOOM_ROTATED = 0.43OUTLINE_CHECKBOXES = [ "Print volume boundary", "Layer boundary", "Blob boundary", "Enclosing circles", "Hollow areas", "Centroids", "Triangulate", "Edge detection", "Distance detection", "Skeletonize",]ACTION_ITEMS = [ "Import layers", "Clone layers", "Export layers to GIF", "Export layers to mesh",]
# ---------------------------------------------------------------------------# local read helpers — all built on the validated uv_helpers API# ---------------------------------------------------------------------------
def _poll(read, want, timeout=2.5, interval=0.3): """Re-read `read()` until it equals `want` or the timeout expires.
UVtools re-renders the layer/thumbnail asynchronously after a press, so a fixed sleep is both slower and flakier than polling. Returns the LAST observed value so the caller can assert on it truthfully (no skipping, no retry-until-pass). """ got = read() deadline = time.time() + timeout while got != want and time.time() < deadline: time.sleep(interval) got = read() return got
def _poll_change(read, before, timeout=2.5, interval=0.3): """Re-read `read()` until it DIFFERS from `before` (or the timeout expires).
Used where recon records a recompute whose exact new string is then asserted — polling only waits for the async update, it never decides the verdict. """ got = read() deadline = time.time() + timeout while got == before and time.time() < deadline: time.sleep(interval) got = read() return got
def _poll_truthy(read, timeout=2.5, interval=0.3): """Re-read `read()` until it is non-empty (or the timeout expires).""" got = read() deadline = time.time() + timeout while not got and time.time() < deadline: time.sleep(interval) got = read() return got
def _is_ratio(val): """True for an 'n/m' index label such as '1/2'.""" parts = str(val).split("/") return (len(parts) == 2 and parts[0].strip().isdigit() and parts[1].strip().isdigit())
def _thumb_index(ax): """The thumbnail index read-out ('1/2' / '2/2').
Primary locator is the Avalonia x:Name (PART_Text); the fallback is semantic — the 'n/m' label sitting horizontally BETWEEN the two thumbnail nav buttons — so a recreation that names the label differently is still matched. """ for el in uv.find_by_identifier(ax, "PART_Text", role="label", max_depth=26): val = str(el.value or "").strip() if _is_ratio(val): return val prev, nxt = _thumb_buttons(ax) lo, hi = None, None if prev is not None and nxt is not None: pb, nb = uv.frame(ax, prev.id), uv.frame(ax, nxt.id) if pb and nb: lo, hi = pb[0], nb[0] + nb[2] for el in ax.find(role="label", max_depth=22, max_results=400): val = str(el.value or "").strip() if not _is_ratio(val): continue if lo is None: return val box = uv.frame(ax, el.id) if box and lo <= box[0] <= hi: return val return None
def _thumb_resolution(ax): """The thumbnail resolution label, e.g. '{Width: 400, Height: 400}'.""" return uv.find_text(ax, "{Width: ")
def _thumb_state(ax): """(index label, resolution label) read together, so a poll never tears them apart.""" return (_thumb_index(ax), _thumb_resolution(ax))
def _thumb_buttons(ax): """(previous, next) buttons of the thumbnail index selector.""" prev = uv.find_by_identifier(ax, "PART_PreviousButton", role="button", max_depth=26) nxt = uv.find_by_identifier(ax, "PART_NextButton", role="button", max_depth=26) if prev and nxt: return prev[0], nxt[0] groups = uv.find_by_identifier(ax, "ThumbnailIndexSelector", max_depth=26) if groups: # container-scoped fallback btns = ax.find(role="button", root_id=groups[0].id, max_depth=8, max_results=8) btns.sort(key=lambda b: (uv.frame(ax, b.id) or (0, 0, 0, 0))[0]) if len(btns) >= 2: return btns[0], btns[-1] return (prev[0] if prev else None), (nxt[0] if nxt else None)
def _layer_tooltip(ax): """The layer-navigation read-out next to the slider ('1.000mm\\n9\\n100%').""" panels = uv.find_by_identifier(ax, "LayerNavigationTooltipPanel", max_depth=26) if panels: vals = uv.label_values(ax, root_id=panels[0].id, max_depth=10) for val in vals: if "mm" in val and "%" in val: return val if vals: return "\n".join(vals) return uv.layer_tooltip(ax)
def _pixels_volume(ax): """The 'Pixels: … / Volume: …' read-out under the layer preview, as ONE string.
The reference renders it as a single two-line label; a recreation may split it in two, so the 'Volume:' line is appended when it is not already included. """ pixels = uv.find_text(ax, "Pixels:") if pixels is None: return None if "volume" in pixels.lower(): return pixels volume = uv.find_text(ax, "Volume:") return pixels if volume is None else f"{pixels}\n{volume}"
def _layer_state(ax): """(layer index, layer navigation read-out) read together for a coherent snapshot.""" return (uv.layer_index(ax), _layer_tooltip(ax))
def _tooltip_lines(tip): """The layer read-out split into its individual lines, e.g. {'0.100mm','0','10%'}.
Line-exact matching matters: '10%' is a SUBSTRING of '100%', so a plain `in` test on the whole read-out would accept the layer-9 tooltip as the layer-0 one. """ return {line.strip() for line in str(tip or "").splitlines() if line.strip()}
def _bool_value(raw): """Normalize an AXValue that carries a checked state (bool, 0/1 or 'True'/'False').""" if raw is None: return None if isinstance(raw, str): low = raw.strip().lower() if low in ("true", "1", "yes", "on"): return True if low in ("false", "0", "no", "off", ""): return False return None try: return bool(int(raw)) except Exception: return bool(raw)
def _toggle_state(ax, element): """Fresh read of a toggle button's checked state (UVtools exposes it as AXValue).""" if element is None: return None return _bool_value(ax.get(element.id, ["AXValue"]).get("AXValue"))
def _pixel_editor_button(ax, previous=None): """The 'Pixel editor' toolbar toggle.
`previous` is the element returned by an earlier lookup: as long as that ref still answers AXValue it is reused, because re-finding by label after the toggle turned on could otherwise land on a 'Pixel editor' caption inside the newly-revealed editor panel. Only when the old ref goes stale is the button located again by its label. """ if previous is not None and _toggle_state(ax, previous) is not None: return previous return uv.find_button_by_label(ax, "Pixel editor")
def _enabled_pair(ax): """(previous.enabled, next.enabled) of the thumbnail selector, read fresh.""" prev, nxt = _thumb_buttons(ax) assert prev is not None and nxt is not None, ( "thumbnail previous/next buttons not found (PART_PreviousButton / PART_NextButton)") return bool(prev.enabled), bool(nxt.enabled)
def _dialog_button(ax, label, win): """A button inside a dialog window, found by its rendered label.
Dialog content sits deep in this app's AX tree, so the recon-validated default search depth is tried first and a deeper walk only as a fallback (a recreation may nest its dialog content further). """ btn = uv.find_button_by_label(ax, label, root_id=win.id) if btn is None: btn = uv.find_button_by_label(ax, label, root_id=win.id, max_depth=44) return btn
# ---------------------------------------------------------------------------# thumbnail index selector (Information tab)# ---------------------------------------------------------------------------
class TestThumbnailButtons:
@pytest.mark.rb(depth=0, jump_kind="value", expect="pressing the thumbnail next button selects thumbnail 2: " "PART_Text goes '1/2' -> '2/2' and the resolution label goes " "'{Width: 400, Height: 400}' -> '{Width: 800, Height: 480}'") def test_thumbnail_next_selects_second_thumbnail(self, ax): idx_before, res_before = _thumb_state(ax) assert idx_before == THUMB_1, f"thumbnail index before press: {idx_before!r}" assert res_before == THUMB_1_RES, f"resolution before press: {res_before!r}"
prev, nxt = _thumb_buttons(ax) assert nxt is not None, "thumbnail next button (PART_NextButton) not found" assert uv.press_button(ax, nxt), "AXPress on the thumbnail next button failed"
idx_after, res_after = _poll(lambda: _thumb_state(ax), (THUMB_2, THUMB_2_RES)) uv.screenshot_assert( "button_test_thumbnail_next_selects_second_thumbnail", "UVtools main window, Information tab: the thumbnail selector at the top of " "the narrow left panel now reads '2/2' with the left (previous) arrow " "enabled and the right (next) arrow greyed out; the label beside it reads " "'{Width: 800, Height: 480}' and the image below it is the WIDER second " "thumbnail (800x480 landscape preview of the sliced model) instead of the " "square 400x400 one. Below it the 'Properties: 154 | Groups: 4' line and the " "Properties/Layer-data tables are unchanged, and the big black layer preview " "on the right still shows the white UVtools logo slice.", RESULTS_DIR) assert kit.rb_value(idx_after, THUMB_2), ( f"thumbnail index after next: {idx_after!r} (expected {THUMB_2!r})") assert kit.rb_value(res_after, THUMB_2_RES), ( f"thumbnail resolution after next: {res_after!r} (expected {THUMB_2_RES!r})")
@pytest.mark.rb(depth=0, jump_kind="transition", expect="pressing previous after next flips the selector back: " "'2/2'/'{Width: 800, Height: 480}' -> " "'1/2'/'{Width: 400, Height: 400}'") def test_thumbnail_previous_returns_to_first_thumbnail(self, ax): prev, nxt = _thumb_buttons(ax) assert nxt is not None and prev is not None, "thumbnail nav buttons not found" assert uv.press_button(ax, nxt), "AXPress on the thumbnail next button failed" at_two = _poll(lambda: _thumb_state(ax), (THUMB_2, THUMB_2_RES)) assert at_two == (THUMB_2, THUMB_2_RES), f"state after next: {at_two!r}"
prev, nxt = _thumb_buttons(ax) assert uv.press_button(ax, prev), "AXPress on the thumbnail previous button failed" back = _poll(lambda: _thumb_state(ax), (THUMB_1, THUMB_1_RES))
assert kit.rb_flip(at_two, back), ( f"previous did not change the thumbnail state (still {back!r})") assert back == (THUMB_1, THUMB_1_RES), ( f"state after previous: {back!r} (expected {(THUMB_1, THUMB_1_RES)!r})")
@pytest.mark.rb(depth=0, jump_kind="transition", expect="the thumbnail nav buttons swap enabled state: at 1/2 previous " "is DISABLED and next ENABLED; after pressing next (2/2) " "previous is ENABLED and next DISABLED") def test_thumbnail_button_enabled_state_flips(self, ax): assert _thumb_index(ax) == THUMB_1, "expected the selector to start at 1/2" before = _enabled_pair(ax) assert before == (False, True), ( f"(previous.enabled, next.enabled) at 1/2 = {before!r}, expected (False, True)")
prev, nxt = _thumb_buttons(ax) assert uv.press_button(ax, nxt), "AXPress on the thumbnail next button failed" assert _poll(lambda: _thumb_index(ax), THUMB_2) == THUMB_2, ( "thumbnail did not advance to 2/2, so the enabled flip cannot be judged") after = _poll(lambda: _enabled_pair(ax), (True, False))
assert kit.rb_flip(before, after), ( f"thumbnail button enabled states did not change (still {after!r})") assert after == (True, False), ( f"(previous.enabled, next.enabled) at 2/2 = {after!r}, expected (True, False)")
# ---------------------------------------------------------------------------# layer navigation buttons SB / LB / SN / LN (right edge, real AXTitles)# ---------------------------------------------------------------------------
class TestLayerNavigationButtons:
@pytest.mark.rb(depth=0, jump_kind="value", expect="LB (largest bottom layer) jumps to layer 9: the layer index " "box reads 9 and the slider read-out shows 1.000mm / 100%") def test_lb_button_selects_layer_nine(self, ax): assert uv.layer_index(ax) == 0, "expected the app to start on layer 0" lb = uv.find_button_by_name(ax, "LB") assert lb is not None, "layer-navigation button 'LB' not found (AXTitle 'LB')" assert uv.press_button(ax, lb), "AXPress on the 'LB' button failed"
idx = _poll(lambda: uv.layer_index(ax), 9) tip = _layer_tooltip(ax) uv.screenshot_assert( "button_test_lb_button_selects_layer_nine", "UVtools main window after pressing the 'LB' button at the bottom of the " "right-hand layer column: layer 9 (the last/top layer) is selected — the " "vertical layer slider handle on the right edge sits at the TOP of its " "track, the read-out beside the handle shows '1.000mm', '9' and '100%', the " "small index box under the slider reads 9, and the black preview canvas " "shows the topmost slice of the model. The bottom-left read-out under the " "canvas reads 'Pixels: 568399 (13.71%)' / 'Volume: 142.10mm3'.", RESULTS_DIR) assert kit.rb_value(idx, 9), f"layer index after LB: {idx!r} (expected 9)" assert kit.rb_value(tip, LAYER9_TIP_MM), ( f"layer read-out after LB: {tip!r} (expected it to contain {LAYER9_TIP_MM!r})") assert LAYER9_TIP_PCT in _tooltip_lines(tip), ( f"layer read-out after LB: {tip!r} (expected a {LAYER9_TIP_PCT!r} line)")
@pytest.mark.rb(depth=0, jump_kind="value", expect="LB updates the preview read-out from " "'Pixels: 486195 / Volume: 121.55mm3' to " "'Pixels: 568399 / Volume: 142.10mm3'") def test_lb_button_updates_pixel_and_volume_readout(self, ax): before = _pixels_volume(ax) assert before is not None, "layer preview 'Pixels:' read-out not found" assert LAYER0_PIXELS in before, f"layer 0 read-out: {before!r}" assert LAYER0_VOLUME in before, f"layer 0 read-out: {before!r}"
lb = uv.find_button_by_name(ax, "LB") assert lb is not None, "layer-navigation button 'LB' not found" assert uv.press_button(ax, lb), "AXPress on the 'LB' button failed" assert _poll(lambda: uv.layer_index(ax), 9) == 9, "LB did not select layer 9"
after = _poll_change(lambda: _pixels_volume(ax), before) or "" assert kit.rb_value(after, LAYER9_PIXELS), ( f"'Pixels:' read-out after LB: {after!r} (expected {LAYER9_PIXELS!r})") assert kit.rb_value(after, LAYER9_VOLUME), ( f"volume read-out after LB: {after!r} (expected {LAYER9_VOLUME!r})") assert LAYER0_PIXELS not in after, ( f"read-out still shows the layer-0 pixel count: {after!r}")
@pytest.mark.rb(depth=0, jump_kind="value", expect="LB rewrites the CurrentLayerGrid: PositionZ '0.100mm' -> " "'1.000mm' and Index '0' -> '9'") def test_lb_button_updates_current_layer_grid(self, ax): before = uv.grid_rows(ax, "CurrentLayerGrid") assert before, "CurrentLayerGrid is empty (Information tab should be selected)" assert before.get("PositionZ") == "0.100mm", f"grid before LB: {before!r}" assert uv.numeric(before.get("Index")) == 0, f"grid before LB: {before!r}"
lb = uv.find_button_by_name(ax, "LB") assert lb is not None, "layer-navigation button 'LB' not found" assert uv.press_button(ax, lb), "AXPress on the 'LB' button failed" assert _poll(lambda: uv.layer_index(ax), 9) == 9, "LB did not select layer 9"
# poll on ONE cell (the grid is re-populated row by row), then read the whole # grid once so every assertion below sees the same coherent snapshot. _poll(lambda: uv.grid_rows(ax, "CurrentLayerGrid").get("PositionZ"), "1.000mm") after = uv.grid_rows(ax, "CurrentLayerGrid") assert after, "CurrentLayerGrid became empty after pressing LB" assert kit.rb_value(after.get("PositionZ"), "1.000mm"), ( f"CurrentLayerGrid[PositionZ] after LB: {after.get('PositionZ')!r} " f"(expected '1.000mm'); full grid {after!r}") assert kit.rb_value(str(after.get("Index")), "9"), ( f"CurrentLayerGrid[Index] after LB: {after.get('Index')!r}") assert uv.numeric(after.get("Index")) == 9, f"grid after LB: {after!r}" assert after.get("LayerHeight") == "0.100mm", ( f"layer height should stay 0.100mm, grid after LB: {after!r}")
@pytest.mark.rb(depth=0, jump_kind="transition", expect="SB (smallest bottom layer) undoes LB: layer index 9 -> 0 and " "the slider read-out returns to 0.100mm / 10%") def test_sb_button_returns_to_layer_zero(self, ax): lb = uv.find_button_by_name(ax, "LB") sb = uv.find_button_by_name(ax, "SB") assert lb is not None and sb is not None, "'LB'/'SB' buttons not found" assert uv.press_button(ax, lb), "AXPress on the 'LB' button failed" assert _poll(lambda: uv.layer_index(ax), 9) == 9, "LB did not select layer 9" at_nine = _layer_state(ax)
sb = uv.find_button_by_name(ax, "SB") assert uv.press_button(ax, sb), "AXPress on the 'SB' button failed" _poll(lambda: uv.layer_index(ax), 0) # wait out the async re-render at_zero = _layer_state(ax)
assert kit.rb_flip(at_nine, at_zero), ( f"SB did not change the selected layer (still {at_zero!r})") assert at_zero[0] == 0, f"layer index after SB: {at_zero[0]!r} (expected 0)" assert LAYER0_TIP_MM in (at_zero[1] or ""), ( f"layer read-out after SB: {at_zero[1]!r} (expected {LAYER0_TIP_MM!r})") assert LAYER0_TIP_PCT in _tooltip_lines(at_zero[1]), ( f"layer read-out after SB: {at_zero[1]!r} (expected a {LAYER0_TIP_PCT!r} line)")
@pytest.mark.rb(depth=0, jump_kind="value", expect="SN/LN present and enabled; layer stays 0 because all 10 layers " "are bottom layers") def test_sn_and_ln_buttons_are_noops_without_normal_layers(self, ax): sn = uv.find_button_by_name(ax, "SN") ln = uv.find_button_by_name(ax, "LN") assert sn is not None, "layer-navigation button 'SN' not found (AXTitle 'SN')" assert ln is not None, "layer-navigation button 'LN' not found (AXTitle 'LN')" assert bool(sn.enabled), "'SN' button is disabled" assert bool(ln.enabled), "'LN' button is disabled" assert uv.layer_index(ax) == 0, "expected the app to start on layer 0"
bottom = uv.find_text(ax, "Bottom layers:") assert bottom is not None, "status bar 'Bottom layers:' info not found" assert uv.numeric(bottom) == 10, ( f"status bar bottom-layer info: {bottom!r} (expected 10 bottom layers — every " f"layer of the demo file is a bottom layer, which is why SN/LN cannot move)")
assert uv.press_button(ax, ln), "AXPress on the 'LN' button failed" time.sleep(0.4) after_ln = uv.layer_index(ax) assert kit.rb_value(after_ln, 0), ( f"layer index after LN: {after_ln!r} (expected 0 — no normal layers exist)")
sn = uv.find_button_by_name(ax, "SN") assert uv.press_button(ax, sn), "AXPress on the 'SN' button failed" time.sleep(0.4) after_sn = uv.layer_index(ax) assert kit.rb_value(after_sn, 0), ( f"layer index after SN: {after_sn!r} (expected 0 — no normal layers exist)")
# ---------------------------------------------------------------------------# layer-preview toolbar buttons (labels rendered inside the button)# ---------------------------------------------------------------------------
class TestPreviewToolbarButtons:
@pytest.mark.rb(depth=0, jump_kind="value", expect="the Rotate toolbar button re-fits the preview: the 'Zoom:' " "read-out changes from 0.55x to 0.43x") def test_rotate_button_changes_zoom_readout(self, ax): zoom_before = uv.find_text(ax, "Zoom:") assert zoom_before is not None, "layer preview 'Zoom:' read-out not found" z_before = uv.numeric(zoom_before) assert z_before is not None, f"no number in the zoom read-out: {zoom_before!r}" assert round(z_before, 2) == ZOOM_UNROTATED, ( f"zoom before Rotate: {zoom_before!r} (expected {ZOOM_UNROTATED}x)")
rotate = uv.find_button_by_label(ax, "Rotate") assert rotate is not None, "toolbar button labelled 'Rotate' not found" assert uv.press_button(ax, rotate), "AXPress on the 'Rotate' button failed" time.sleep(0.5)
zoom_after = _poll_change(lambda: uv.find_text(ax, "Zoom:"), zoom_before) z_after = uv.numeric(zoom_after) assert z_after is not None, f"no number in the zoom read-out: {zoom_after!r}" assert z_after != z_before, ( f"Rotate did not change the zoom read-out (still {zoom_after!r})") assert kit.rb_value(round(z_after, 2), ZOOM_ROTATED), ( f"zoom after Rotate: {zoom_after!r} (expected {ZOOM_ROTATED}x)")
@pytest.mark.rb(depth=0, jump_kind="transition", expect="the Pixel editor toggle's AXValue flips False -> True and a " "TabPixelEditor radio appears; pressing again returns False " "and the radio disappears") def test_pixel_editor_toggle_flips_on_and_off(self, ax): btn = _pixel_editor_button(ax) assert btn is not None, "toolbar toggle labelled 'Pixel editor' not found" off_state = _toggle_state(ax, btn) assert off_state is False, ( f"'Pixel editor' AXValue on launch: {off_state!r} (expected False)") assert not uv.find_by_identifier(ax, "TabPixelEditor", role="radio", max_depth=26), ( "a TabPixelEditor tab exists before the toggle was pressed")
assert uv.press_button(ax, btn), "AXPress on the 'Pixel editor' toggle failed" time.sleep(0.6) btn_on = _pixel_editor_button(ax, previous=btn) assert btn_on is not None, "'Pixel editor' toggle vanished after being pressed" on_state = _poll(lambda: _toggle_state(ax, btn_on), True) pixel_tab = _poll_truthy( lambda: uv.find_by_identifier(ax, "TabPixelEditor", role="radio", max_depth=26))
assert kit.rb_flip(off_state, on_state), ( f"'Pixel editor' AXValue did not change (still {on_state!r})") assert on_state is True, ( f"'Pixel editor' AXValue after 1st press: {on_state!r} (expected True)") assert pixel_tab, ( "no radio with AXIdentifier 'TabPixelEditor' appeared in the left tab strip") assert uv.is_selected(ax, pixel_tab[0].id), ( "the new TabPixelEditor tab is not selected")
assert uv.press_button(ax, btn_on), "2nd AXPress on the 'Pixel editor' toggle failed" time.sleep(0.6) btn_off = _pixel_editor_button(ax, previous=btn_on) assert btn_off is not None, "'Pixel editor' toggle vanished after the 2nd press" off_again = _poll(lambda: _toggle_state(ax, btn_off), False)
assert kit.rb_flip(on_state, off_again), ( f"'Pixel editor' AXValue did not toggle back (still {off_again!r})") assert off_again is False, ( f"'Pixel editor' AXValue after 2nd press: {off_again!r} (expected False)") assert not uv.find_by_identifier(ax, "TabPixelEditor", role="radio", max_depth=26), ( "the TabPixelEditor tab is still present after toggling the editor off")
# ---------------------------------------------------------------------------# drop-down buttons (a real depth-1 surface jump)# ---------------------------------------------------------------------------
class TestDropdownButtons:
@pytest.mark.rb(depth=1, jump_kind="reach", expect="pressing the 'Actions' drop-down button opens a layer-actions " "menu containing Import layers, Clone layers, Export layers to " "GIF and Export layers to mesh (none of them activated)") def test_actions_dropdown_opens_layer_actions_menu(self, ax): # depth 16 so the popup window's items are inside the snapshot (recon: a menu # popup is a separate AXWindow whose items sit ~12 levels down). before = kit.rb_showing(ax, max_depth=16) assert not any("Import layers" in key for key in before), ( "the layer-action items are reachable before the drop-down was pressed")
opened = uv.rb_enter_dropdown(ax, "LayerActionsButton") names = uv.menu_item_names(ax) if "Import layers" not in names: # the very first AXPress on an Avalonia drop-down is sometimes swallowed; # the menu is then still closed, so re-press it (rb_enter_dropdown is a # no-op-safe open that reports whether new items appeared). uv.rb_enter_dropdown(ax, "LayerActionsButton") names = uv.menu_item_names(ax) after = kit.rb_showing(ax, max_depth=16)
for want in ACTION_ITEMS: assert want in names, ( f"menu item {want!r} missing from the Actions drop-down; opened={opened!r}, " f"visible items={names!r}") assert len(names) >= 13, ( f"the Actions drop-down should add 9 items to the 4 menu-bar items, " f"got {len(names)}: {names!r}") assert kit.rb_reach(before, after, target="Import layers"), ( "the Actions drop-down surface did not appear (no new 'Import layers' node)")
@pytest.mark.rb(depth=1, jump_kind="reach", expect="pressing the 'Outline' drop-down button reveals 10 named " "overlay checkboxes including 'Print volume boundary' " "(checked) and 'Skeletonize' (unchecked)") def test_outline_dropdown_reveals_overlay_checkboxes(self, ax): pre = uv.checkbox_map(ax) assert not any(name in pre for name in OUTLINE_CHECKBOXES), ( f"overlay checkboxes are reachable before the Outline drop-down was " f"pressed: {sorted(pre)!r}") before = _outline_showing(ax)
opened = uv.rb_enter_dropdown(ax, "LayerPreviewOutlineButton") boxes = uv.checkbox_map(ax) if not boxes: uv.rb_enter_dropdown(ax, "LayerPreviewOutlineButton") boxes = uv.checkbox_map(ax) after = _outline_showing(ax)
uv.screenshot_assert( "button_test_outline_dropdown_reveals_overlay_checkboxes", "The 'Outline' drop-down button in the toolbar above the black layer preview " "(between 'Issues' and 'Pixel editor') is open: a popup panel hangs under it " "listing ten check-box overlay options in this order — Print volume boundary " "(the ONLY one ticked), Layer boundary, Blob boundary, Enclosing circles, " "Hollow areas, Centroids, Triangulate, Edge detection, Distance detection, " "Skeletonize. The main window behind it is unchanged (Information tab with " "the thumbnail on the left, layer slider on the right).", RESULTS_DIR)
assert boxes, f"no checkboxes appeared after pressing 'Outline'; opened={opened!r}" assert len(boxes) >= 10, ( f"expected 10 overlay checkboxes, got {len(boxes)}: {sorted(boxes)!r}") for want in OUTLINE_CHECKBOXES: assert want in boxes, ( f"overlay checkbox {want!r} missing; got {sorted(boxes)!r}") assert boxes["Print volume boundary"] is True, ( "'Print volume boundary' should be the one checked-by-default overlay, " f"got {boxes['Print volume boundary']!r}") assert boxes["Skeletonize"] is False, ( f"'Skeletonize' should be unchecked, got {boxes['Skeletonize']!r}") assert kit.rb_reach(before, after, target="Print volume boundary"), ( "the Outline drop-down surface did not appear (no new " "'Print volume boundary' node)")
# ---------------------------------------------------------------------------# buttons inside a dialog (depth 1)# ---------------------------------------------------------------------------
class TestDialogButtons:
@pytest.mark.rb(depth=1, jump_kind="reach", expect="Help > About opens the 'About UVtools v4.4.2' window which " "carries the 'Copy information' and 'Close' buttons") def test_about_dialog_exposes_copy_information_and_close_buttons(self, ax): before = kit.rb_showing(ax, max_depth=12) win = uv.open_dialog(ax, "Help", "About", "About") after = kit.rb_showing(ax, max_depth=12)
assert win is not None, "Help > About did not open an 'About ...' window" assert "4.4.2" in (win.name or ""), ( f"About window title: {win.name!r} (expected it to contain '4.4.2')") assert kit.rb_reach(before, after, target="About UVtools"), ( "the About window surface did not appear in the AX tree")
copy_btn = _dialog_button(ax, "Copy information", win) close_btn = _dialog_button(ax, "Close", win) assert copy_btn is not None, ( "button labelled 'Copy information' not found inside the About window") assert close_btn is not None, ( "button labelled 'Close' not found inside the About window") assert "AXPress" in (copy_btn.actions or []), ( f"'Copy information' exposes no AXPress action: {copy_btn.actions!r}") assert bool(copy_btn.enabled) and bool(close_btn.enabled), ( "the About dialog buttons should both be enabled") # deliberately NOT pressed: 'Close' would tear the dialog down and the harness # kills the app after every test anyway.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667import os, sys, timeimport pytestsys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))import rb_testgen_kit as kitimport uv_helpers as uv
RESULTS_DIR = os.environ.get("RESULTS_DIR", "/tmp")
# ---------------------------------------------------------------------------# AX COMPUTATION tests for UVtools 4.4.2 (Avalonia / .NET).## Everything asserted here is DERIVED arithmetic that the app itself performs:## * `Tools > Calculator` > "Millimeters to pixels" implements# Pixels = Resolution / Display * Millimeters. The dialog is seeded from the# loaded demo file (1620x2560 px over an 81x128 mm display => 20 px/mm on# both axes) and the `Input millimeters:` spinner steps by 0.5 mm, so every# press must move `X Pixels` / `Y Pixels` by 20 * 0.5 = 10 px.# * the layer slider's AXMaxValue must equal (layer count - 1) parsed out of# the status bar, and the last layer's `PositionZ` must equal# count * layer height.# * the preview read-outs ({Width=1620, Height=2560} px /# {Width=81, Height=128} mm and `Pixel: 50um`) must agree:# 1 / (1620/81) mm = 0.05 mm = 50 um.## Expected values are COMPUTED inside the test from the inputs the app displays,# never copy-pasted from the output side alone. Nothing DYNAMIC (used material,# material cost, RAM/LO in the window title, render time) is asserted. The# Calculator's "Optimal model tilt" tab renders System.InvalidCastException into# two of its output labels on this build, so those two outputs are never touched.## The app's numeric fields are NOT settable over AX (set_value silently lies), so# every number is driven exclusively through the NumericUpDown spinner buttons.# ---------------------------------------------------------------------------
import re
# the NumericUpDown recomputes its dependent outputs right after a pressSTEP_SETTLE = 0.8# step of the "Input millimeters:" spinner, as observed on the referenceMM_STEP = 0.5# geometric tolerance when pairing a row label with the widget on its rowROW_TOL = 14.0
# ---------------------------------------------------------------------------# verdict helpers -- rb_value_* wrappers around kit.rb_value (RB TestGen kit)# ---------------------------------------------------------------------------
def rb_value_close(observed, expected, tol=1e-6): """VALUE verdict for a numeric read-out: `observed` == the value we COMPUTED.
Backed by kit.rb_value on the rounded pair plus an explicit tolerance check so kit's tolerant substring fallback can never accept e.g. 2.0 in place of 20.0. """ if observed is None or expected is None: return False try: obs, exp = float(observed), float(expected) except (TypeError, ValueError): return False if abs(obs - exp) > tol: return False return bool(kit.rb_value(round(obs, 4), round(exp, 4)))
def rb_value_text(observed, expected): """VALUE verdict for a displayed string (exact, or containing `expected`).""" return bool(kit.rb_value(observed, expected))
# ---------------------------------------------------------------------------# locators -- semantic (row label + role), never by child index or tree path# ---------------------------------------------------------------------------
def _ready(ax, timeout=8.0): """UVtools' main window, revealing the UI first should it not be up yet.""" deadline = time.time() + timeout while time.time() < deadline: win = uv.main_window(ax) if win is not None: return win try: ax.ensure_ui_visible() except Exception: pass time.sleep(0.5) return uv.main_window(ax)
def _label_variants(label): """Tolerate a missing / extra trailing colon on a row label.""" base = label.strip().rstrip(":") return list(dict.fromkeys([label, base, base + ":"]))
def _field(ax, win, label): """The numeric field on the row labelled `label` inside the dialog `win`.""" for cand in _label_variants(label): el = uv.field_for_label(ax, cand, root_id=win.id) if el is not None: return el return None
def _spinner(ax, win, label): """(increase, decrease) buttons of the NumericUpDown on `label`'s row.""" for cand in _label_variants(label): inc, dec = uv.spinner_buttons(ax, cand, root_id=win.id) if inc is not None or dec is not None: return inc, dec return None, None
def _row_text(ax, win, label): """Fallback read-out: the nearest NUMBER-carrying label on `label`'s row.
A recreation may render a computed row as plain text instead of a read-only NumericUpDown; the value asserted is the same either way. A cell to the RIGHT of the row label wins (that is UVtools' layout); otherwise the closest one on the row is used. """ for cand in _label_variants(label): want = cand.strip().lower() anchor, cells = None, [] for el in ax.find(role="label", root_id=win.id, max_depth=44, max_results=400): box = uv.frame(ax, el.id) if not box: continue val = str(el.value or "") cells.append((box, val)) if anchor is None and val.strip().lower() == want: anchor = box if anchor is None: continue a_mid = anchor[1] + anchor[3] / 2.0 right, right_dx = None, 1e9 near, near_dx = None, 1e9 for box, val in cells: if val.strip().lower() == want or uv.numeric(val) is None: continue mid = box[1] + box[3] / 2.0 if abs(mid - a_mid) > ROW_TOL: continue dx = box[0] - anchor[0] if dx > 1.0 and dx < right_dx: right, right_dx = val, dx if abs(dx) < near_dx: near, near_dx = val, abs(dx) if right is not None: return right if near is not None: return near return None
def _num(ax, el): """Freshly re-read AXValue of an already resolved element, as a number.""" if el is None: return None got = ax.get(el.id, ["AXValue"]) return uv.numeric(got.get("AXValue"))
def _read_num(ax, win, label): """Number shown on the row labelled `label` (field first, then plain text).""" val = _num(ax, _field(ax, win, label)) if val is None: val = uv.numeric(_row_text(ax, win, label)) assert val is not None, ( f"the Calculator row '{label}' was not found, or shows no numeric value") return val
def _num_at(ax, win, label, cached, prev=None): """`label`'s number, preferring the cached widget.
Re-resolves the row from the tree when the cached read is empty, or when it still reports `prev` (a widget Avalonia replaced would otherwise look frozen). """ val = _num(ax, cached) if val is None or (prev is not None and val == prev): again = _num(ax, _field(ax, win, label)) if again is not None: return again if val is None: again = uv.numeric(_row_text(ax, win, label)) assert again is not None, ( f"the Calculator row '{label}' was not found, or shows no numeric value") return again if again is not None else val return val
def _current_layer_index(ax, grid_rows): """Selected layer index: the grid's Index row, else the index box, else tooltip.""" if "Index" in grid_rows: val = uv.numeric(grid_rows["Index"]) if val is not None: return val val = uv.layer_index(ax) if val is not None: return val tip = uv.layer_tooltip(ax) or "" parts = [p.strip() for p in str(tip).splitlines() if p.strip()] if len(parts) >= 2: return uv.numeric(parts[1]) return None
def _status_layers(ax): """(count, height_mm, raw) parsed out of the status bar 'Layers: 10 @ 0.1mm'.""" for txt in uv.status_bar_texts(ax): s = str(txt).strip() if s.lower().startswith("layers:"): count = uv.numeric(s) m = re.search(r"@\s*([0-9]+(?:\.[0-9]+)?)\s*mm", s) height = float(m.group(1)) if m else None return (int(count) if count is not None else None), height, s return None, None, ""
def _preview_blob(ax): """All main-window label text joined (the layer-preview read-outs live here).""" return "\n".join(uv.label_values(ax, max_depth=26, max_results=600))
# ---------------------------------------------------------------------------# A. Tools > Calculator -- "Millimeters to pixels" (depth 1)# ---------------------------------------------------------------------------
class TestCalculatorMillimetersToPixels:
@pytest.mark.rb(depth=1, jump_kind="value", expect="Calculator seeded from the loaded file: Resolution X=1620, " "Resolution Y=2560, Display width=81.00, Display height=128.00, " "Input millimeters=1.00") def test_calculator_inputs_seeded_from_file(self, ax): _ready(ax) win = uv.open_dialog(ax, "Tools", "Calculator", "Calculator", settle=3.0) assert win is not None, ( "Tools > Calculator did not open a window titled 'Calculator' -- the " "Calculator surface is unreachable")
res_x = _read_num(ax, win, "Resolution X:") res_y = _read_num(ax, win, "Resolution Y:") disp_w = _read_num(ax, win, "Display width:") disp_h = _read_num(ax, win, "Display height:") mm = _read_num(ax, win, "Input millimeters:")
assert rb_value_close(res_x, 1620.0), f"'Resolution X:' shows {res_x!r}, expected 1620" assert rb_value_close(res_y, 2560.0), f"'Resolution Y:' shows {res_y!r}, expected 2560" assert rb_value_close(disp_w, 81.0), ( f"'Display width:' shows {disp_w!r}, expected 81.00") assert rb_value_close(disp_h, 128.0), ( f"'Display height:' shows {disp_h!r}, expected 128.00") assert rb_value_close(mm, 1.0), f"'Input millimeters:' shows {mm!r}, expected 1.00"
@pytest.mark.rb(depth=1, jump_kind="value", expect="X pixels per millimeter = 1620/81 = 20 and " "Y pixels per millimeter = 2560/128 = 20") def test_pixels_per_millimeter_is_resolution_over_display(self, ax): _ready(ax) win = uv.open_dialog(ax, "Tools", "Calculator", "Calculator", settle=3.0) assert win is not None, ( "Tools > Calculator did not open a window titled 'Calculator' -- the " "Calculator surface is unreachable")
res_x = _read_num(ax, win, "Resolution X:") disp_w = _read_num(ax, win, "Display width:") res_y = _read_num(ax, win, "Resolution Y:") disp_h = _read_num(ax, win, "Display height:")
# derive both quotients ourselves from the two pairs of INPUT rows expect_x = res_x / disp_w # 1620 / 81 = 20.0 expect_y = res_y / disp_h # 2560 / 128 = 20.0 assert rb_value_close(expect_x, 20.0), f"derived X px/mm {expect_x}, expected 20" assert rb_value_close(expect_y, 20.0), f"derived Y px/mm {expect_y}, expected 20"
ppmm_x = _read_num(ax, win, "X pixels per millimeter:") ppmm_y = _read_num(ax, win, "Y pixels per millimeter:")
assert rb_value_close(ppmm_x, expect_x), ( f"'X pixels per millimeter:' shows {ppmm_x!r} but {res_x}/{disp_w} = {expect_x}") assert rb_value_close(ppmm_y, expect_y), ( f"'Y pixels per millimeter:' shows {ppmm_y!r} but {res_y}/{disp_h} = {expect_y}")
@pytest.mark.rb(depth=1, jump_kind="value", expect="at Input millimeters=1.00 the calculator shows X Pixels=20 and " "Y Pixels=20 (= 20 px/mm * 1 mm)") def test_baseline_one_millimeter_is_twenty_pixels(self, ax): _ready(ax) win = uv.open_dialog(ax, "Tools", "Calculator", "Calculator", settle=3.0) assert win is not None, ( "Tools > Calculator did not open a window titled 'Calculator' -- the " "Calculator surface is unreachable")
mm = _read_num(ax, win, "Input millimeters:") ppmm_x = _read_num(ax, win, "X pixels per millimeter:") ppmm_y = _read_num(ax, win, "Y pixels per millimeter:") assert rb_value_close(mm, 1.0), f"'Input millimeters:' shows {mm!r}, expected 1.00" assert rb_value_close(ppmm_x, 20.0), f"'X pixels per millimeter:' {ppmm_x!r} != 20" assert rb_value_close(ppmm_y, 20.0), f"'Y pixels per millimeter:' {ppmm_y!r} != 20"
expect_x = ppmm_x * mm # 20 px/mm * 1.00 mm = 20.0 expect_y = ppmm_y * mm # 20 px/mm * 1.00 mm = 20.0
px_x = _read_num(ax, win, "X Pixels") px_y = _read_num(ax, win, "Y Pixels")
assert rb_value_close(px_x, expect_x), ( f"'X Pixels' shows {px_x!r}, expected {ppmm_x} px/mm * {mm} mm = {expect_x}") assert rb_value_close(px_y, expect_y), ( f"'Y Pixels' shows {px_y!r}, expected {ppmm_y} px/mm * {mm} mm = {expect_y}")
@pytest.mark.rb(depth=1, jump_kind="value", expect="one spinner increase -> Input millimeters=1.50, X Pixels=30.0, " "Y Pixels=30.0") def test_one_spinner_step_gives_thirty_pixels(self, ax): _ready(ax) win = uv.open_dialog(ax, "Tools", "Calculator", "Calculator", settle=3.0) assert win is not None, ( "Tools > Calculator did not open a window titled 'Calculator' -- the " "Calculator surface is unreachable")
mm_field = _field(ax, win, "Input millimeters:") x_field = _field(ax, win, "X Pixels") y_field = _field(ax, win, "Y Pixels")
inc, _dec = _spinner(ax, win, "Input millimeters:") assert inc is not None, ( "the increase spinner button of the 'Input millimeters:' row was not found")
start_mm = _num_at(ax, win, "Input millimeters:", mm_field) start_x = _num_at(ax, win, "X Pixels", x_field) start_y = _num_at(ax, win, "Y Pixels", y_field) assert rb_value_close(start_mm, 1.0), ( f"'Input millimeters:' starts at {start_mm!r}, expected 1.00")
assert uv.press_button(ax, inc), ( "pressing the 'Input millimeters:' increase button failed") time.sleep(STEP_SETTLE)
expect_mm = start_mm + MM_STEP # 1.00 + 0.5 = 1.50 expect_px = 20.0 * expect_mm # 20 px/mm * 1.50 mm = 30.0
got_mm = _num_at(ax, win, "Input millimeters:", mm_field, prev=start_mm) got_x = _num_at(ax, win, "X Pixels", x_field, prev=start_x) got_y = _num_at(ax, win, "Y Pixels", y_field, prev=start_y)
assert rb_value_close(got_mm, expect_mm), ( f"after +1 step 'Input millimeters:' shows {got_mm!r}, expected {expect_mm}") assert rb_value_close(got_x, expect_px), ( f"after +1 step 'X Pixels' shows {got_x!r}, expected {expect_px}") assert rb_value_close(got_y, expect_px), ( f"after +1 step 'Y Pixels' shows {got_y!r}, expected {expect_px}")
@pytest.mark.rb(depth=1, jump_kind="value", expect="two spinner increases -> Input millimeters=2.00 and X Pixels=40.0") def test_two_spinner_steps_give_forty_pixels(self, ax): _ready(ax) win = uv.open_dialog(ax, "Tools", "Calculator", "Calculator", settle=3.0) assert win is not None, ( "Tools > Calculator did not open a window titled 'Calculator' -- the " "Calculator surface is unreachable")
mm_field = _field(ax, win, "Input millimeters:") x_field = _field(ax, win, "X Pixels")
inc, _dec = _spinner(ax, win, "Input millimeters:") assert inc is not None, ( "the increase spinner button of the 'Input millimeters:' row was not found")
start_mm = _num_at(ax, win, "Input millimeters:", mm_field) start_x = _num_at(ax, win, "X Pixels", x_field) for _ in range(2): assert uv.press_button(ax, inc), ( "pressing the 'Input millimeters:' increase button failed") time.sleep(STEP_SETTLE)
expect_mm = start_mm + 2 * MM_STEP # 1.00 + 1.00 = 2.00 expect_px = 20.0 * expect_mm # 20 px/mm * 2.00 mm = 40.0
got_mm = _num_at(ax, win, "Input millimeters:", mm_field, prev=start_mm) got_x = _num_at(ax, win, "X Pixels", x_field, prev=start_x)
uv.screenshot_assert( "computation_test_calculator_mm_to_pixels", "The UVtools 'Calculator' dialog is open in front of the main window on its " "'Millimeters to pixels' tab, which shows 'Converts from Millimeters to " "Pixels' and 'Formula: Pixels = Resolution / Display * Millimeters'. The " "numeric rows read Resolution X: 1620, Resolution Y: 2560, Display width: " "81.00, Display height: 128.00 and Input millimeters: 2.00 (after two 0.5 mm " "spinner increments from 1.00). The derived rows read X pixels per " "millimeter: 20 and Y pixels per millimeter: 20, and the computed outputs " "read X Pixels: 40.0 and Y Pixels: 40.0. A Cancel button sits at the bottom " "of the dialog.", RESULTS_DIR)
assert rb_value_close(got_mm, expect_mm), ( f"after +2 steps 'Input millimeters:' shows {got_mm!r}, expected {expect_mm}") assert rb_value_close(got_x, expect_px), ( f"after +2 steps 'X Pixels' shows {got_x!r}, expected {expect_px}")
@pytest.mark.rb(depth=1, jump_kind="value", expect="three increases -> 2.50 mm with X Pixels=50.0, then one decrease " "-> 2.00 mm with X Pixels=40.0") def test_three_steps_up_then_one_down(self, ax): _ready(ax) win = uv.open_dialog(ax, "Tools", "Calculator", "Calculator", settle=3.0) assert win is not None, ( "Tools > Calculator did not open a window titled 'Calculator' -- the " "Calculator surface is unreachable")
mm_field = _field(ax, win, "Input millimeters:") x_field = _field(ax, win, "X Pixels")
inc, dec = _spinner(ax, win, "Input millimeters:") assert inc is not None, ( "the increase spinner button of the 'Input millimeters:' row was not found") assert dec is not None, ( "the decrease spinner button of the 'Input millimeters:' row was not found")
start_mm = _num_at(ax, win, "Input millimeters:", mm_field) start_x = _num_at(ax, win, "X Pixels", x_field) assert rb_value_close(start_mm, 1.0), ( f"'Input millimeters:' starts at {start_mm!r}, expected 1.00")
for _ in range(3): assert uv.press_button(ax, inc), ( "pressing the 'Input millimeters:' increase button failed") time.sleep(STEP_SETTLE)
up_mm = start_mm + 3 * MM_STEP # 1.00 -> 2.50 up_px = 20.0 * up_mm # 20 px/mm * 2.50 mm = 50.0 got_up_mm = _num_at(ax, win, "Input millimeters:", mm_field, prev=start_mm) got_up_px = _num_at(ax, win, "X Pixels", x_field, prev=start_x) assert rb_value_close(got_up_mm, up_mm), ( f"after +3 steps 'Input millimeters:' shows {got_up_mm!r}, expected {up_mm}") assert rb_value_close(got_up_px, up_px), ( f"after +3 steps 'X Pixels' shows {got_up_px!r}, expected {up_px}")
assert uv.press_button(ax, dec), ( "pressing the 'Input millimeters:' decrease button failed") time.sleep(STEP_SETTLE)
down_mm = up_mm - MM_STEP # 2.50 -> 2.00 down_px = 20.0 * down_mm # 20 px/mm * 2.00 mm = 40.0 got_down_mm = _num_at(ax, win, "Input millimeters:", mm_field, prev=got_up_mm) got_down_px = _num_at(ax, win, "X Pixels", x_field, prev=got_up_px) assert rb_value_close(got_down_mm, down_mm), ( f"after the decrease 'Input millimeters:' shows {got_down_mm!r}, " f"expected {down_mm}") assert rb_value_close(got_down_px, down_px), ( f"after the decrease 'X Pixels' shows {got_down_px!r}, expected {down_px}")
@pytest.mark.rb(depth=1, jump_kind="value", expect="X Pixels grows by ppmm*0.5 = 10 per spinner step") def test_one_step_changes_x_pixels_by_ten(self, ax): _ready(ax) win = uv.open_dialog(ax, "Tools", "Calculator", "Calculator", settle=3.0) assert win is not None, ( "Tools > Calculator did not open a window titled 'Calculator' -- the " "Calculator surface is unreachable")
ppmm_x = _read_num(ax, win, "X pixels per millimeter:") assert rb_value_close(ppmm_x, 20.0), f"'X pixels per millimeter:' {ppmm_x!r} != 20"
x_field = _field(ax, win, "X Pixels") inc, _dec = _spinner(ax, win, "Input millimeters:") assert inc is not None, ( "the increase spinner button of the 'Input millimeters:' row was not found")
before = _num_at(ax, win, "X Pixels", x_field)
assert uv.press_button(ax, inc), ( "pressing the 'Input millimeters:' increase button failed") time.sleep(STEP_SETTLE)
after = _num_at(ax, win, "X Pixels", x_field, prev=before)
expect_delta = ppmm_x * MM_STEP # 20 px/mm * 0.5 mm = 10.0 assert rb_value_close(expect_delta, 10.0), ( f"derived per-step delta {expect_delta}, expected 10.0") assert rb_value_close(after - before, expect_delta), ( f"'X Pixels' went {before!r} -> {after!r} (delta {after - before}), expected " f"+{expect_delta} for one {MM_STEP} mm step at {ppmm_x} px/mm")
# ---------------------------------------------------------------------------# A2. Calculator > second tab "Optimal model tilt" (depth 2)# ---------------------------------------------------------------------------
class TestCalculatorOptimalTilt:
@pytest.mark.rb(depth=2, jump_kind="value", expect="'Optimal model tilt' tab selected; its description contains " "'Formula: Angle = arctan(Layer height / XYResolution)' and the " "'Layer height:' row reads 0.100") def test_optimal_model_tilt_tab(self, ax): _ready(ax) win = uv.open_dialog(ax, "Tools", "Calculator", "Calculator", settle=3.0) assert win is not None, ( "Tools > Calculator did not open a window titled 'Calculator' -- the " "Calculator surface is unreachable")
switched = uv.select_tab(ax, "Optimal model tilt", root_id=win.id) assert switched, ( "selecting the Calculator's 'Optimal model tilt' tab did not flip the radio " "selection")
desc = uv.find_text(ax, "arctan", root_id=win.id, max_depth=44) assert desc is not None, ( "the 'Optimal model tilt' tab shows no description text containing 'arctan'") assert rb_value_text(desc, "Formula:"), ( f"the tilt tab description {desc!r} does not contain 'Formula:'") assert rb_value_text(desc, "arctan(Layer height / XYResolution)"), ( f"the tilt tab description {desc!r} does not contain " f"'arctan(Layer height / XYResolution)'")
# NOTE: this build renders System.InvalidCastException into the tab's two # COMPUTED output labels, so only the input row is asserted here. layer_height = _read_num(ax, win, "Layer height:")
uv.screenshot_assert( "computation_test_calculator_optimal_tilt", "The UVtools 'Calculator' dialog is open with its SECOND tab, 'Optimal model " "tilt', now selected (the 'Millimeters to pixels' tab is no longer the " "selected one). The panel shows the description 'Calculates the optimal model " "tilt angle for printing and to minimize the visual layer effect.' followed " "by the line 'Formula: Angle = arctan(Layer height / XYResolution) * (180 / " "PI)'. Rows labelled 'Layer height:' (showing 0.100), 'XY resolution:' and " "'Optimal tilt angle:' are visible; on this build the two computed output " "rows display a System.InvalidCastException message instead of a number. A " "Cancel button sits at the bottom of the dialog.", RESULTS_DIR)
assert rb_value_close(layer_height, 0.1), ( f"the tilt tab's 'Layer height:' row shows {layer_height!r}, expected 0.100")
# ---------------------------------------------------------------------------# B. Layer arithmetic in the main window (depth 0)# ---------------------------------------------------------------------------
class TestLayerArithmetic:
@pytest.mark.rb(depth=0, jump_kind="value", expect="LayerSlider AXMaxValue 9.0 == the layer count (10, parsed from " "the status bar 'Layers: 10 @ 0.1mm') minus 1") def test_layer_slider_max_is_layer_count_minus_one(self, ax): _ready(ax)
count, height, status = _status_layers(ax) assert count is not None, ( f"no 'Layers: N @ Hmm' label found on the status bar (got {status!r})") assert rb_value_close(count, 10.0), ( f"the status bar reports {count!r} layers, expected 10 ({status!r})") assert rb_value_close(height, 0.1), ( f"the status bar reports a layer height of {height!r}, expected 0.1 ({status!r})")
slider = uv.layer_slider(ax) assert slider is not None, "the layer navigation slider (LayerSlider) was not found" got = ax.get(slider.id, ["AXMinValue", "AXMaxValue"]) min_v = uv.numeric(got.get("AXMinValue")) max_v = uv.numeric(got.get("AXMaxValue"))
expect_max = count - 1 # 10 layers -> indices 0..9 assert rb_value_close(expect_max, 9.0), f"derived max index {expect_max}, expected 9" assert rb_value_close(min_v, 0.0), f"LayerSlider AXMinValue {min_v!r}, expected 0.0" assert rb_value_close(max_v, expect_max), ( f"LayerSlider AXMaxValue {max_v!r} != layer count {count} - 1 = {expect_max}")
@pytest.mark.rb(depth=0, jump_kind="value", expect="after pressing LB the CurrentLayerGrid PositionZ reads 1.000mm " "== 10 layers * 0.100mm") def test_last_layer_z_equals_count_times_height(self, ax): _ready(ax)
lb = uv.find_button_by_name(ax, "LB") assert lb is not None, ( "the 'LB' (largest bottom layer) navigation button was not found") assert uv.press_button(ax, lb), "pressing the 'LB' button failed" time.sleep(1.5)
rows = uv.grid_rows(ax, "CurrentLayerGrid") assert rows, "CurrentLayerGrid is empty after pressing LB" assert "LayerHeight" in rows, ( f"CurrentLayerGrid has no LayerHeight row: {sorted(rows)}") assert "PositionZ" in rows, f"CurrentLayerGrid has no PositionZ row: {sorted(rows)}"
grid_height = uv.numeric(rows["LayerHeight"]) count, _bar_height, status = _status_layers(ax) assert count is not None, ( f"no 'Layers: N @ Hmm' label found on the status bar (got {status!r})") assert rb_value_close(grid_height, 0.1), ( f"CurrentLayerGrid LayerHeight {rows['LayerHeight']!r}, expected 0.100mm")
expect_z = count * grid_height # 10 layers * 0.100 mm = 1.000 mm expect_text = "{:.3f}mm".format(expect_z) got_z = rows["PositionZ"]
assert rb_value_close(uv.numeric(got_z), expect_z), ( f"PositionZ {got_z!r} != {count} layers * {grid_height}mm = {expect_z}") assert rb_value_text(got_z, expect_text), ( f"PositionZ {got_z!r} is not rendered as {expect_text!r}")
idx = _current_layer_index(ax, rows) assert rb_value_close(idx, count - 1), ( f"after LB the selected layer index is {idx!r}, expected {count - 1}")
# ---------------------------------------------------------------------------# C. Preview resolution / pixel-size arithmetic (depth 0)# ---------------------------------------------------------------------------
class TestPreviewPixelSize:
@pytest.mark.rb(depth=0, jump_kind="value", expect="1 / (1620 px / 81 mm) = 0.05 mm = the displayed 'Pixel: 50um'") def test_pixel_size_matches_resolution_over_display(self, ax): _ready(ax)
blob = _preview_blob(ax)
px = re.search( r"\{Width=([0-9]+(?:\.[0-9]+)?),\s*Height=([0-9]+(?:\.[0-9]+)?)\}\s*px", blob) mm = re.search( r"\{Width=([0-9]+(?:\.[0-9]+)?),\s*Height=([0-9]+(?:\.[0-9]+)?)\}\s*mm", blob) assert px is not None, ( "the '{Width=..., Height=...} px' preview read-out was not found") assert mm is not None, ( "the '{Width=..., Height=...} mm' preview read-out was not found")
px_w, px_h = float(px.group(1)), float(px.group(2)) mm_w, mm_h = float(mm.group(1)), float(mm.group(2)) assert rb_value_close(px_w, 1620.0), f"preview resolution width {px_w}, expected 1620" assert rb_value_close(px_h, 2560.0), f"preview resolution height {px_h}, expected 2560" assert rb_value_close(mm_w, 81.0), f"preview display width {mm_w}, expected 81" assert rb_value_close(mm_h, 128.0), f"preview display height {mm_h}, expected 128"
ppmm_x = px_w / mm_w # 1620 / 81 = 20.0 px/mm ppmm_y = px_h / mm_h # 2560 / 128 = 20.0 px/mm assert rb_value_close(ppmm_x, ppmm_y), ( f"X {ppmm_x} px/mm and Y {ppmm_y} px/mm disagree -> pixels are not square")
expect_um = (1.0 / ppmm_x) * 1000.0 # 1/20 mm = 0.05 mm = 50.0 um assert rb_value_close(expect_um, 50.0), ( f"derived pixel size {expect_um} um, expected 50 um")
shown = re.search(r"Pixel:\s*([0-9]+(?:\.[0-9]+)?)\s*(\S+)", blob) assert shown is not None, "the 'Zoom: ... Pixel: <n>um' read-out was not found" shown_val = float(shown.group(1)) unit = shown.group(2).strip() # normalise the micro sign (U+00B5) and greek mu (U+03BC) to a plain 'u' unit_norm = unit.replace("µ", "u").replace("μ", "u")
assert unit_norm == "um", ( f"the pixel-size read-out uses the unit {unit!r}, expected micrometres (um)") assert rb_value_close(shown_val, expect_um), ( f"the display shows 'Pixel: {shown_val}{unit}' but 1/({px_w} px / {mm_w} mm) " f"= {expect_um} um")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604"""AX MENU tests for UVtools 4.4.2 (Avalonia/.NET) — generated from recon.md `## MENUS`.
Everything asserted here was observed on the reference app through the same `ax`pytest fixture (fresh launch per test, demo file auto-loaded).
App-specific AX quirks honoured throughout (recon `## AX_TREE` → AX QUIRKS): * the menu bar is drawn INSIDE the window and its menu items expose NO AX actions while AXUIElementPerformAction still reports success -> menus are ALWAYS driven with uv.rb_enter_menu / uv.click_menu (a real synthesized click), never AXPress. * the macOS Apple/app menu is in this app's AX tree with 0-height frames -> menu items are only ever counted through uv.visible_menu_items()/uv.menu_item_names(). * only 4 activations are safe (Help>About, File>Settings, Tools>Calculator, Help>Benchmark); every other item is asserted for presence/enabled-state INSIDE the opened menu and never clicked. Benchmark is modal -> opened last, never Start."""import os, sys, timeimport pytestsys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))import rb_testgen_kit as kitimport uv_helpers as uv
RESULTS_DIR = os.environ.get("RESULTS_DIR", "/tmp")
def _outline_showing(ax): """rb_showing extended with the Outline popup's check items.
kit.rb_showing() walks to depth 12; the overlay check items inside the Outline drop-down sit well below that cap, so a plain snapshot cannot witness them appearing. Adding the (role-filtered, cheap) checkbox names keeps the before/after comparison honest without paying for a full deep tree walk. """ snap = set(kit.rb_showing(ax)) snap |= {"checkbox|%s" % name for name in uv.checkbox_map(ax)} return snap
# ---------------------------------------------------------------------------# Expected menu content (recon `## MENUS`, in order)# ---------------------------------------------------------------------------TOP_MENUS = ["File", "Tools", "Calibration", "Help"]
FILE_ITEMS = [ "Open", "Open in new window", "Open recent", "Open in partial mode", "Reload", "Save", "Save as", "Rename", "Convert to", "Close", "Reset layers properties", "I printed this file", "Open containing folder", "Extract file contents", "Copy parameters to files", "Terminal", "Fullscreen", "Settings", "Exit",]
TOOLS_ITEMS = [ "Edit print parameters", "Repair layers and issues", "Move", "Resize", "Flip", "Rotate", "Solidify", "Morph", "Raft relief", "Redraw model/supports", "Layer arithmetic", "Pixel arithmetic", "Mask", "Light bleed compensation", "Infill", "Blur", "Pattern", "Fade exposure time", "Phased exposure", "Dynamic lifts", "Dynamic layer height", "Adjust layer height", "Raise platform on print finish", "Change print resolution", "Timelapse", "Lithophane", "PCB exposure", "Stir resin", "Scripting", "Calculator",]TOOLS_DISABLED = [ "Fade exposure time", "Phased exposure", "Dynamic lifts", "Dynamic layer height", "Raise platform on print finish", "Timelapse",]
CALIBRATION_ITEMS = [ "Exposure time finder", "Elephant foot", "XYZ Accuracy", "Lift height", "Blooming effect", "Tolerance", "Grayscale", "Stress tower", "External tests",]CALIBRATION_DISABLED = ["Blooming effect"]
HELP_ITEMS = [ "About", "Website", "Wiki & tutorials", "Community forums", "Donate", "Material manager", "Install profiles into PrusaSlicer", "Report an issue", "Ask a question", "Suggest an improvement or new features", "Open settings folder", "Free unused RAM", "Benchmark",]
CONVERT_FORMATS = [ "Prusa", "Chitubox", "Anycubic Photon Workshop", "CWS", "Anet", "Longer3D", "Voxeldance", "CXDLP", "NanoDLP", "Klipper", "Elegoo GOO", "Phrozen Sonic Mini 8K S (PRZ)", "UnizMaker IBEE (ZCode)", "Uniformation GKone (JXS)", "Z-Suite ZCodex", "Makerbase MDLP v1", "GR1 Workshop", "Flashforge SVGX", "Emake3D Galaxy 1 (QDT)", "Open SLA universal binary file (OSLA)", "Vlare Open File Format (OSF)", "Vendor-neutral format (UVJ)", "Generic Zip / Phrozen Zip",]
LAYER_ACTION_ITEMS = [ "Import layers", "Clone layers", "Remove layers", "Export layers to images", "Export layers to GIF", "Export layers to HTML", "Export layers to skeleton", "Export layers to heat map", "Export layers to mesh",]
OUTLINE_CHECKBOXES = [ "Print volume boundary", "Layer boundary", "Blob boundary", "Enclosing circles", "Hollow areas", "Centroids", "Triangulate", "Edge detection", "Distance detection", "Skeletonize",]
SETTINGS_CATEGORIES = [ "General", "Layer preview", "Issues", "Pixel editor", "Layer repair", "Tools", "Automations", "Network",]
# ---------------------------------------------------------------------------# local read helpers — all built on the validated uv_helpers menu readers# ---------------------------------------------------------------------------def _norm(name): """Menu label with a trailing ellipsis / padding removed ('Open...' -> 'Open').""" s = str(name or "").strip() for suffix in ("...", "…"): if s.endswith(suffix): s = s[: -len(suffix)].strip() return s
def _names(ax): """Names of the menu items really on screen (uv filters the 0-height Apple menu).""" return [_norm(n) for n in uv.menu_item_names(ax)]
def _item_map(ax): """{visible menu item name: AXElement} in ONE tree pass (keeps tests inside budget).""" out = {} for el in uv.visible_menu_items(ax): key = _norm(el.name) if key and key not in out: out[key] = el return out
def _menu_item(ax, name): """A visible menu item by name, ellipsis-tolerant.""" el = uv.menu_item(ax, name) if el is not None: return el want = _norm(name).lower() for cand in uv.visible_menu_items(ax): if _norm(cand.name).lower() == want: return cand return None
def _radio_names(ax, root_id, max_depth=40): """Names of the tab/category radios inside a dialog window (scoped to that window).""" return {str(r.name or "").strip() for r in ax.find(role="radio", root_id=root_id, max_depth=max_depth, max_results=60)}
def _blob(ax, root_id, max_depth=44): """All rendered text under a dialog window, joined for containment checks.
Uses label + text_field + text_area values (UVtools renders some dialog rows as read-only text fields). UVtools' dialog content sits DEEP (recon: ~44 levels from the app root), so the depth is deliberately generous — lowering it empties the read. """ return " | ".join(uv.text_values(ax, root_id=root_id, max_depth=max_depth, max_results=400))
def _show(names, limit=900): s = ", ".join(sorted(set(names))) return s if len(s) <= limit else s[:limit] + " ..."
def _missing(wanted, names): got = set(names) return [w for w in wanted if w not in got]
# ---------------------------------------------------------------------------# 1. every top-level menu opens (depth-1 surface jump) and carries its items# ---------------------------------------------------------------------------class TestTopLevelMenus:
@pytest.mark.rb(depth=1, jump_kind="reach", expect="File menu popup appears (Convert to / Save as / Settings / Exit newly showing); " "visible menu items grow from the 4 menu-bar titles to ~23") def test_file_menu_opens_with_expected_items(self, ax): before = kit.rb_showing(ax) assert uv.rb_enter_menu(ax, "File"), "File menu did not open on click" after = kit.rb_showing(ax) assert kit.rb_reach(before, after, target="Convert to"), ( "opening File did not surface its popup: no 'Convert to' item appeared " "in the AX tree") names = _names(ax) uv.screenshot_assert( "menu_test_file_menu", "UVtools main window with the File drop-down open under the 'File' title of the " "in-window menu bar (File Tools Calibration Help, top-left). The menu lists, with " "icons: Open, Open in new window, Open recent, Open in partial mode, Reload, Save " "(greyed out/disabled), Save as, Rename, Convert to (with a submenu arrow), Close, " "Reset layers properties (greyed out), I printed this file, Open containing folder, " "Extract file contents, Copy parameters to files, Terminal, Fullscreen, Settings, " "Exit. Behind it: the black layer-preview canvas with the white UVtools logo slice.", RESULTS_DIR) expected = ["Open", "Open recent", "Reload", "Save", "Save as", "Rename", "Convert to", "Close", "Terminal", "Fullscreen", "Settings", "Exit"] assert not _missing(expected, names), ( f"File menu missing {_missing(expected, names)}; visible = {_show(names)}") present = [i for i in FILE_ITEMS if i in set(names)] assert len(present) >= len(FILE_ITEMS) - 2, ( f"only {len(present)}/{len(FILE_ITEMS)} recon File items present; " f"missing {_missing(FILE_ITEMS, names)}") for absent in ("Calculator", "About", "Benchmark", "Elephant foot"): assert absent not in names, f"{absent!r} must not live in the File menu" assert 20 <= len(names) <= 27, ( f"expected ~23 visible menu items with File open (4 titles + 19 items), " f"got {len(names)}: {_show(names)}")
@pytest.mark.rb(depth=1, jump_kind="reach", expect="Tools menu popup appears (Layer arithmetic / Pixel arithmetic / Calculator newly " "showing); visible menu items grow from 4 to ~34") def test_tools_menu_opens_with_expected_items(self, ax): before = kit.rb_showing(ax) assert uv.rb_enter_menu(ax, "Tools"), "Tools menu did not open on click" after = kit.rb_showing(ax) assert kit.rb_reach(before, after, target="Layer arithmetic"), ( "opening Tools did not surface its popup: no 'Layer arithmetic' item appeared") names = _names(ax) uv.screenshot_assert( "menu_test_tools_menu", "UVtools with the long Tools drop-down open under the 'Tools' menu-bar title: about " "30 tool names from 'Edit print parameters' and 'Repair layers and issues' at the top " "through Move, Resize, Flip, Rotate, Solidify, Morph, Infill, Blur, Pattern down to " "Lithophane, PCB exposure, Stir resin, Scripting and Calculator at the bottom; a " "group of entries in the lower half (Fade exposure time, Phased exposure, Dynamic " "lifts, Dynamic layer height, Raise platform on print finish, Timelapse) is greyed " "out/disabled.", RESULTS_DIR) expected = ["Edit print parameters", "Repair layers and issues", "Move", "Resize", "Rotate", "Solidify", "Morph", "Layer arithmetic", "Infill", "Blur", "Pattern", "Lithophane", "PCB exposure", "Scripting", "Calculator"] assert not _missing(expected, names), ( f"Tools menu missing {_missing(expected, names)}; visible = {_show(names)}") present = [i for i in TOOLS_ITEMS if i in set(names)] assert len(present) >= len(TOOLS_ITEMS) - 3, ( f"only {len(present)}/{len(TOOLS_ITEMS)} recon Tools items present; " f"missing {_missing(TOOLS_ITEMS, names)}") for absent in ("Exit", "About", "Save as", "Elephant foot"): assert absent not in names, f"{absent!r} must not live in the Tools menu" assert 30 <= len(names) <= 38, ( f"expected ~34 visible menu items with Tools open (4 titles + 30 items), " f"got {len(names)}: {_show(names)}")
@pytest.mark.rb(depth=1, jump_kind="reach", expect="Calibration menu popup appears (Elephant foot / XYZ Accuracy / Stress tower newly " "showing); visible menu items grow from 4 to ~13") def test_calibration_menu_opens_with_expected_items(self, ax): before = kit.rb_showing(ax) assert uv.rb_enter_menu(ax, "Calibration"), "Calibration menu did not open on click" after = kit.rb_showing(ax) assert kit.rb_reach(before, after, target="Elephant foot"), ( "opening Calibration did not surface its popup: no 'Elephant foot' item appeared") names = _names(ax) assert not _missing(CALIBRATION_ITEMS, names), ( f"Calibration menu missing {_missing(CALIBRATION_ITEMS, names)}; " f"visible = {_show(names)}") for absent in ("Exit", "Settings", "Calculator", "About"): assert absent not in names, f"{absent!r} must not live in the Calibration menu" assert 11 <= len(names) <= 16, ( f"expected ~13 visible menu items with Calibration open (4 titles + 9 items), " f"got {len(names)}: {_show(names)}")
@pytest.mark.rb(depth=1, jump_kind="reach", expect="Help menu popup appears (Material manager / Wiki & tutorials / Benchmark newly " "showing); visible menu items grow from 4 to ~17") def test_help_menu_opens_with_expected_items(self, ax): before = kit.rb_showing(ax) assert uv.rb_enter_menu(ax, "Help"), "Help menu did not open on click" after = kit.rb_showing(ax) assert kit.rb_reach(before, after, target="Material manager"), ( "opening Help did not surface its popup: no 'Material manager' item appeared") names = _names(ax) expected = ["About", "Website", "Community forums", "Donate", "Material manager", "Report an issue", "Ask a question", "Free unused RAM", "Benchmark"] assert not _missing(expected, names), ( f"Help menu missing {_missing(expected, names)}; visible = {_show(names)}") present = [i for i in HELP_ITEMS if i in set(names)] assert len(present) >= len(HELP_ITEMS) - 2, ( f"only {len(present)}/{len(HELP_ITEMS)} recon Help items present; " f"missing {_missing(HELP_ITEMS, names)}") for absent in ("Exit", "Settings", "Save", "Calculator"): assert absent not in names, f"{absent!r} must not live in the Help menu" assert 15 <= len(names) <= 20, ( f"expected ~17 visible menu items with Help open (4 titles + 13 items), " f"got {len(names)}: {_show(names)}")
# ---------------------------------------------------------------------------# 2. enabled/disabled truth READ INSIDE the opened menu (nothing is activated)# ---------------------------------------------------------------------------class TestMenuItemEnabledState:
@pytest.mark.rb(depth=1, jump_kind="value", expect="Inside the File menu on the freshly loaded demo file: 'Save' DISABLED, " "'Save as' ENABLED, 'Reset layers properties' DISABLED") def test_file_save_disabled_save_as_enabled(self, ax): assert uv.rb_enter_menu(ax, "File"), "File menu did not open on click" items = _item_map(ax) wanted = ["Save", "Save as", "Reset layers properties"] assert not _missing(wanted, items), ( f"File menu missing {_missing(wanted, items)}; visible = {_show(items)}") observed = {n: bool(items[n].enabled) for n in wanted} expected = {"Save": False, "Save as": True, "Reset layers properties": False} assert kit.rb_value(observed, expected), ( f"File menu enabled-state mismatch: observed {observed}, expected {expected}")
@pytest.mark.rb(depth=1, jump_kind="value", expect="Inside the Tools menu exactly 6 items are disabled (Fade exposure time, Phased " "exposure, Dynamic lifts, Dynamic layer height, Raise platform on print finish, " "Timelapse) while Move / Resize / Calculator / Blur are enabled") def test_tools_menu_disabled_items(self, ax): assert uv.rb_enter_menu(ax, "Tools"), "Tools menu did not open on click" items = _item_map(ax) assert not _missing(TOOLS_DISABLED, items), ( f"Tools menu missing {_missing(TOOLS_DISABLED, items)}; visible = {_show(items)}") observed = sorted(n for n, el in items.items() if not el.enabled and n not in TOP_MENUS) assert kit.rb_value(observed, sorted(TOOLS_DISABLED)), ( f"disabled Tools items: observed {observed}, expected {sorted(TOOLS_DISABLED)}") for name in ("Move", "Resize", "Calculator", "Blur"): assert name in items, f"Tools menu missing {name!r}" assert items[name].enabled, f"Tools > {name} should be ENABLED but reads disabled"
@pytest.mark.rb(depth=1, jump_kind="value", expect="Inside the Calibration menu 'Blooming effect' is DISABLED and the other 8 " "calibration entries are ENABLED") def test_calibration_blooming_effect_disabled(self, ax): assert uv.rb_enter_menu(ax, "Calibration"), "Calibration menu did not open on click" items = _item_map(ax) assert not _missing(CALIBRATION_ITEMS, items), ( f"Calibration menu missing {_missing(CALIBRATION_ITEMS, items)}; " f"visible = {_show(items)}") observed = {n: bool(items[n].enabled) for n in CALIBRATION_ITEMS} expected = {n: (n not in CALIBRATION_DISABLED) for n in CALIBRATION_ITEMS} assert kit.rb_value(observed, expected), ( f"Calibration enabled-state mismatch: observed {observed}, expected {expected}")
# ---------------------------------------------------------------------------# 3. submenu = a second surface (depth 2)# ---------------------------------------------------------------------------class TestSubmenus:
@pytest.mark.rb(depth=2, jump_kind="reach", expect="File > Convert to expands a second-level menu of 23 printer/file formats " "(Prusa, Chitubox, CWS, CXDLP, Klipper, Elegoo GOO, UVJ ...); visible menu items " "grow from 23 (File open) to ~46") def test_convert_to_submenu_lists_formats(self, ax): before = kit.rb_showing(ax) assert uv.rb_enter_submenu(ax, "File", "Convert to"), ( "File > Convert to submenu did not expand") after = kit.rb_showing(ax) assert kit.rb_reach(before, after, target="Chitubox"), ( "the Convert to submenu did not surface its format list " "(no 'Chitubox' item appeared)") names = _names(ax) uv.screenshot_assert( "menu_test_convert_to_submenu", "UVtools with the File menu open AND its 'Convert to' entry expanded into a " "second-level submenu displayed beside the File drop-down. The submenu lists printer / " "file-format targets: Prusa, Chitubox, Anycubic Photon Workshop, CWS, Anet, Longer3D, " "Voxeldance, CXDLP, NanoDLP, Klipper, Elegoo GOO, Phrozen Sonic Mini 8K S (PRZ), " "UnizMaker IBEE (ZCode), Z-Suite ZCodex, GR1 Workshop, Flashforge SVGX, " "Vendor-neutral format (UVJ), Generic Zip / Phrozen Zip and more.", RESULTS_DIR) expected = ["Prusa", "Chitubox", "Anycubic Photon Workshop", "CWS", "Anet", "CXDLP", "Klipper", "Elegoo GOO", "Vendor-neutral format (UVJ)"] assert not _missing(expected, names), ( f"Convert to submenu missing {_missing(expected, names)}; visible = {_show(names)}") present = [f for f in CONVERT_FORMATS if f in set(names)] assert len(present) >= 8, ( f"only {len(present)}/{len(CONVERT_FORMATS)} recon Convert-to formats present: " f"{_show(names)}") assert len(names) > 23, ( f"the submenu must ADD items on top of the plain File menu (23 visible with " f"File alone), got {len(names)}") assert len(names) >= 38, ( f"expected the File menu (23 items) plus the Convert-to format list to be " f"visible, got only {len(names)}: {_show(names)}")
# ---------------------------------------------------------------------------# 4. the four recon-verified SAFE activations — menu item -> dialog window# (one dialog per test; the dialog is deliberately left open, the harness# kills the app after every test)# ---------------------------------------------------------------------------class TestMenuDialogs:
@pytest.mark.rb(depth=1, jump_kind="reach", expect="Help > About replaces the Help popup with the window 'About UVtools v4.4.2' " "showing the copyright/licence text and Description/OpenCV/Assemblies tabs") def test_help_about_opens_about_window(self, ax): assert uv.rb_enter_menu(ax, "Help"), "Help menu did not open on click" before = kit.rb_showing(ax) item = _menu_item(ax, "About") assert item is not None, f"Help > About not found; visible = {_show(_names(ax))}" uv.click_menu(ax, item, settle=2.6) win = uv.rb_enter_window(ax, "About UVtools") assert win is not None, ( f"no 'About UVtools' window appeared; windows = {uv.window_titles(ax)}") after = kit.rb_showing(ax) # source discriminator = another Help-popup entry: 'menu_item|About' would also # match the macOS app/Apple menu entries ('About UVtools', 'About This Mac'). assert kit.rb_reach(before, after, target="About UVtools", source="menu_item|Material manager"), ( "About did not read as a surface jump (About window appearing while the Help " "menu popup disappears)") uv.screenshot_assert( "menu_test_about_dialog", "The 'About UVtools v4.4.2' window is open in front of the main window: it shows the " "UVtools logo, the app name and version '4.4.2 X64', the AGPL licence line and " "'Copyright 2020-2026 PTRTECH' / author 'Tiago Conceicao', a Terms of Use link, a " "Description / OpenCV / Assemblies tab strip, a table of system fields (Operative " "System, Processor, Processor cores, Memory RAM, Runtime, OpenCV, Framework, " "AvaloniaUI) and 'Copy information' + 'Close' buttons at the bottom.", RESULTS_DIR) assert "About UVtools" in str(win.name or ""), ( f"unexpected About window title: {win.name!r}") text = _blob(ax, win.id) for needle in ("UVtools", "4.4.2", "Copyright 2020-2026", "PTRTECH", "Terms of Use"): assert needle in text, f"About dialog text missing {needle!r}; got: {text[:600]}" radios = _radio_names(ax, win.id) for tab in ("Description", "OpenCV", "Assemblies"): assert tab in radios, f"About dialog missing the {tab!r} tab; got {sorted(radios)}"
@pytest.mark.rb(depth=1, jump_kind="reach", expect="File > Settings replaces the File popup with the window 'UVtools - Settings' " "listing the 8 category tabs General ... Network") def test_file_settings_opens_settings_window(self, ax): assert uv.rb_enter_menu(ax, "File"), "File menu did not open on click" before = kit.rb_showing(ax) item = _menu_item(ax, "Settings") assert item is not None, f"File > Settings not found; visible = {_show(_names(ax))}" uv.click_menu(ax, item, settle=2.6) win = uv.rb_enter_window(ax, "UVtools - Settings") assert win is not None, ( f"no 'UVtools - Settings' window appeared; windows = {uv.window_titles(ax)}") after = kit.rb_showing(ax) # source discriminator = a File-popup-only entry (a bare 'Settings' could also # match a macOS-level app-menu item). assert kit.rb_reach(before, after, target="UVtools - Settings", source="menu_item|Convert to"), ( "Settings did not read as a surface jump (Settings window appearing while the " "File menu popup disappears)") radios = _radio_names(ax, win.id) missing = [c for c in SETTINGS_CATEGORIES if c not in radios] assert not missing, ( f"Settings window missing category tabs {missing}; got {sorted(radios)}") # never touch a Save button here — it would persist usersettings.xml.
@pytest.mark.rb(depth=1, jump_kind="reach", expect="Tools > Calculator replaces the Tools popup with the window 'Calculator' offering " "the 'Millimeters to pixels' and 'Optimal model tilt' tabs") def test_tools_calculator_opens_calculator_window(self, ax): assert uv.rb_enter_menu(ax, "Tools"), "Tools menu did not open on click" before = kit.rb_showing(ax) item = _menu_item(ax, "Calculator") assert item is not None, f"Tools > Calculator not found; visible = {_show(_names(ax))}" uv.click_menu(ax, item, settle=2.6) win = uv.rb_enter_window(ax, "Calculator") assert win is not None, ( f"no 'Calculator' window appeared; windows = {uv.window_titles(ax)}") after = kit.rb_showing(ax) # source discriminator = a Tools-popup-only entry, so the proof cannot be # satisfied by the 'Calculator' item/window sharing a name. assert kit.rb_reach(before, after, target="Calculator", source="menu_item|Layer arithmetic"), ( "Calculator did not read as a surface jump (Calculator window appearing while " "the Tools menu popup disappears)") radios = _radio_names(ax, win.id) for tab in ("Millimeters to pixels", "Optimal model tilt"): assert tab in radios, ( f"Calculator window missing the {tab!r} tab; got {sorted(radios)}") text = _blob(ax, win.id) assert "Calculator" in text, f"Calculator dialog header text missing: {text[:400]}"
@pytest.mark.rb(depth=1, jump_kind="reach", expect="Help > Benchmark replaces the Help popup with the modal window 'Benchmark' showing " "'Your CPU:' / 'Your results:' and an un-pressed 'Start' button") def test_help_benchmark_opens_benchmark_window(self, ax): # Benchmark is MODAL and Escape does not close it -> opening it is the LAST # action of this test; everything after is read-only AX inspection. assert uv.rb_enter_menu(ax, "Help"), "Help menu did not open on click" before = kit.rb_showing(ax) item = _menu_item(ax, "Benchmark") assert item is not None, f"Help > Benchmark not found; visible = {_show(_names(ax))}" uv.click_menu(ax, item, settle=2.6) win = uv.rb_enter_window(ax, "Benchmark") assert win is not None, ( f"no 'Benchmark' window appeared; windows = {uv.window_titles(ax)}") after = kit.rb_showing(ax) # source discriminator = a Help-popup-only entry: the new window is itself titled # 'Benchmark', so 'menu_item|Benchmark' alone would be an ambiguous source. assert kit.rb_reach(before, after, target="Benchmark", source="menu_item|Material manager"), ( "Benchmark did not read as a surface jump (Benchmark window appearing while " "the Help menu popup disappears)") text = _blob(ax, win.id) for needle in ("Your CPU:", "Your results:"): assert needle in text, f"Benchmark window missing {needle!r}; got: {text[:600]}" start = uv.find_button_by_name(ax, "Start", root_id=win.id) assert start is not None, "Benchmark window has no 'Start' button" # never pressed
# ---------------------------------------------------------------------------# 5. dismissal — the popup surface collapses again# ---------------------------------------------------------------------------class TestMenuDismissal:
@pytest.mark.rb(depth=1, jump_kind="transition", expect="Escape collapses the open Help menu: the visible menu-item set flips from the 17 " "entries back to exactly the 4 menu-bar titles File/Tools/Calibration/Help and " "About/Benchmark/Donate are gone") def test_escape_dismisses_open_help_menu(self, ax): assert uv.rb_enter_menu(ax, "Help"), "Help menu did not open on click" before_names = sorted(_names(ax)) assert "About" in before_names and "Benchmark" in before_names, ( f"Help popup content not visible before dismissal: {_show(before_names)}") uv.press_escape() time.sleep(0.6) after_names = sorted(_names(ax)) assert kit.rb_flip(before_names, after_names), ( f"Escape did not change the visible menu-item set (still {_show(after_names)})") assert set(after_names) == set(TOP_MENUS), ( f"after Escape only the 4 menu-bar titles should remain, got {_show(after_names)}") assert len(after_names) == 4, ( f"expected 4 visible menu items after Escape, got {len(after_names)}: " f"{_show(after_names)}") for gone in ("About", "Benchmark", "Donate", "Material manager", "Free unused RAM"): assert gone not in after_names, f"{gone!r} still visible after dismissing Help"
# ---------------------------------------------------------------------------# 6. the layer-preview drop-down menus (Actions / Outline)# ---------------------------------------------------------------------------class TestLayerPreviewDropdowns:
@pytest.mark.rb(depth=1, jump_kind="reach", expect="The 'Actions' drop-down opens a menu of the 9 layer actions (Import/Clone/Remove " "layers + 6 'Export layers to ...' entries); visible menu items grow from 4 to ~13") def test_layer_actions_dropdown_lists_layer_items(self, ax): before = kit.rb_showing(ax) opened = uv.rb_enter_dropdown(ax, "LayerActionsButton") after = kit.rb_showing(ax) assert kit.rb_reach(before, after, target="Export layers to mesh"), ( f"the Actions drop-down did not surface its layer items (rb_enter_dropdown " f"returned {opened})") names = _names(ax) assert not _missing(LAYER_ACTION_ITEMS, names), ( f"Actions drop-down missing {_missing(LAYER_ACTION_ITEMS, names)}; " f"visible = {_show(names)}") assert 11 <= len(names) <= 16, ( f"expected ~13 visible menu items with the Actions drop-down open " f"(4 titles + 9 actions), got {len(names)}: {_show(names)}") # never activated: every Actions entry mutates or exports the loaded file.
@pytest.mark.rb(depth=1, jump_kind="reach", expect="The 'Outline' drop-down opens a menu of exactly the 10 named overlay checkboxes " "(Print volume boundary, Layer boundary ... Skeletonize); none is pressed") def test_layer_outline_dropdown_lists_checkboxes(self, ax): before = _outline_showing(ax) opened = uv.rb_enter_dropdown(ax, "LayerPreviewOutlineButton") after = _outline_showing(ax) assert kit.rb_reach(before, after, target="Print volume boundary"), ( f"the Outline drop-down did not surface its overlay options (rb_enter_dropdown " f"returned {opened})") boxes = uv.checkbox_map(ax) missing = [c for c in OUTLINE_CHECKBOXES if c not in boxes] assert not missing, ( f"Outline drop-down missing checkboxes {missing}; got {_show(list(boxes))}") assert len(boxes) == len(OUTLINE_CHECKBOXES), ( f"expected exactly {len(OUTLINE_CHECKBOXES)} overlay checkboxes, got " f"{len(boxes)}: {_show(list(boxes))}") # state (which box is ticked) belongs to the STATE lane — nothing is pressed here.
# ---------------------------------------------------------------------------# 7. depth-2 angle: the expanded Convert-to submenu is not just present, every# format target it lists is actually offerable (enabled) for the loaded file.# ---------------------------------------------------------------------------class TestSubmenuItemState:
@pytest.mark.rb(depth=2, jump_kind="value", expect="inside the expanded File > Convert to submenu every listed format target " "(Prusa, Chitubox, CWS, CXDLP, Klipper, Elegoo GOO, Vendor-neutral format (UVJ)) " "is ENABLED for the loaded sl1s file") def test_convert_to_formats_are_enabled(self, ax): assert uv.rb_enter_submenu(ax, "File", "Convert to"), ( "File > Convert to submenu did not expand") checked = ["Prusa", "Chitubox", "CWS", "CXDLP", "Klipper", "Elegoo GOO", "Vendor-neutral format (UVJ)"] states = {} for name in checked: item = _menu_item(ax, name) assert item is not None, ( f"Convert to > {name!r} not visible; got {_show(_names(ax))}") states[name] = bool(item.enabled) expected = {name: True for name in checked} assert kit.rb_value(states, expected), ( f"every Convert-to target should be enabled for the loaded file, got {states}") # nothing is activated: a conversion leaf writes a new file.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855import os, sys, timeimport pytestsys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))import rb_testgen_kit as kitimport uv_helpers as uv
RESULTS_DIR = os.environ.get("RESULTS_DIR", "/tmp")
# ---------------------------------------------------------------------------# AX STATE lane — CHECKED / SELECTED / ENABLED / frame-active for UVtools 4.4.2.## Everything asserted here was observed on the reference app (recon.md ## STATE):# * main left-panel tabs expose their selection as AXSelected -> uv.is_selected()# * toggle buttons + checkboxes expose their checked state as AXValue# ('True'/'False' strings inside the Settings window) -> uv.checkbox_map()# * enabled state is AXEnabled -> element.enabled# Widgets are located by their visible label / AXIdentifier (Avalonia x:Name),# never by child index or tree path, so the SAME test drives a recreation.## NB: the Settings window is NEVER saved (Escape only) — pressing Save would# persist usersettings.xml and poison every later run.# ---------------------------------------------------------------------------
TAB_IDS = ("TabInformation", "TabIssues", "TabSuggestions", "TabClipboard")
# uv.grid_rows(ax, "CurrentLayerGrid") on the freshly loaded demo file, layer 0.LAYER_GRID_ROWS = { "Index", "LayerHeight", "PositionZ", "IsBottomLayer", "ExposureTime", "MaterialMilliliters",}
# Outline drop-down: 10 checkboxes, only the first one ticked by default.OUTLINE_DEFAULTS = { "Print volume boundary": True, "Layer boundary": False, "Blob boundary": False, "Enclosing circles": False, "Hollow areas": False, "Centroids": False, "Triangulate": False, "Edge detection": False, "Distance detection": False, "Skeletonize": False,}
FILE_MENU_ENABLED = { "Save": False, "Save as": True, "Reset layers properties": False, "Settings": True, "Exit": True,}
TOOLS_DISABLED = ( "Fade exposure time", "Phased exposure", "Dynamic lifts", "Dynamic layer height", "Raise platform on print finish", "Timelapse",)TOOLS_ENABLED = ("Move", "Resize", "Blur", "Calculator")
CALIBRATION_DISABLED = ("Blooming effect",)CALIBRATION_ENABLED = ( "Exposure time finder", "Elephant foot", "XYZ Accuracy", "Lift height", "Tolerance", "Grayscale", "Stress tower", "External tests",)
SETTINGS_GENERAL_CHECKS = { "Start maximized": True, "Check for updates on startup": True, "Loads a demo file on startup if no file was specified": True, "Restore window last position": False, "Restore window last size": False, "Loads the last recent file on startup if no file was specified": False,}
SETTINGS_LAYER_PREVIEW_CHECKS = { "Show triangle count": True, "Show layer difference by default": False, "Clear ROI when adding masks": True,}
# ---------------------------------------------------------------------------# small readers (semantic locators only — label / AXIdentifier / role)# ---------------------------------------------------------------------------
def _norm(s): """Normalise a visible label for comparison (whitespace / case / trailing '…').""" return " ".join(str(s or "").split()).strip().rstrip(".…").strip().lower()
def _lookup(mapping, name): """Value of `name` in a {label: state} map, matched on the normalised label.
Deliberately NOT a prefix match, so 'Save' can never pick up 'Save as'. """ want = _norm(name) for key, val in mapping.items(): if _norm(key) == want: return val return None
def _lookup_loose(mapping, name): """_lookup, plus an UNAMBIGUOUS long-label prefix fallback.
Long settings labels get truncated/reworded differently by other toolkits, so a prefix match is allowed — but only when exactly one key matches, so the two 'Loads … on startup if no file was specified' options can never be confused. """ got = _lookup(mapping, name) if got is not None: return got want = _norm(name) if len(want) < 14: return None hits = [val for key, val in mapping.items() if len(_norm(key)) >= 14 and (_norm(key).startswith(want) or want.startswith(_norm(key)))] return hits[0] if len(hits) == 1 else None
def _bool_state(value): """AXValue of a toggle/checkbox -> bool (UVtools reports bool OR 'True'/'False').""" if value is None: return None if isinstance(value, str): low = value.strip().lower() if low in ("true", "1", "yes"): return True if low in ("false", "0", "no", ""): return False return None return bool(value)
def _wait_ready(ax, timeout=6.0): """Settle until the app's left tab strip is in the AX tree (never asserted).""" deadline = time.time() + timeout while True: try: if ax.find(role="radio", max_depth=26, max_results=1): return True except Exception: pass if time.time() >= deadline: return False time.sleep(0.4)
def _tab_selection(ax): """{AXIdentifier: AXSelected} for the four main left-panel tab radios.
Primary locator is the exported name (AXIdentifier). If a build exports no identifiers at all, fall back to the left tab strip's reading order (Information, Issues, Suggestions, Clipboard from left to right) — the tab radios carry no usable AXTitle in this app, so order is the only semantics left. """ out = {tab: None for tab in TAB_IDS} radios = ax.find(role="radio", max_depth=26, max_results=24) for el in radios: ident = uv.identifier(ax, el.id) if ident in out and out[ident] is None: out[ident] = uv.is_selected(ax, el.id) if all(v is None for v in out.values()): strip = _tab_strip_radios(ax) for tab, el in zip(TAB_IDS, strip[:len(TAB_IDS)]): out[tab] = uv.is_selected(ax, el.id) return out
def _radio_selection(ax, root_id=None): """{visible label: AXSelected} for radios under root (dialog category tabs).""" out = {} for el in ax.find(role="radio", root_id=root_id, max_depth=34, max_results=40): name = (el.name or "").strip() if name and name not in out: out[name] = uv.is_selected(ax, el.id) return out
def _menu_enabled_map(ax): """{visible menu-item label: AXEnabled} for every on-screen menu item (ONE walk).""" out = {} for el in uv.visible_menu_items(ax): name = (el.name or "").strip() if name and name not in out: out[name] = bool(el.enabled) return out
def _wait_grid(ax, grid_identifier, want_rows=True, timeout=4.0): """Poll a data grid until it is populated (or empty), then return what it reads.
Only smooths out the async re-render after a tab switch — never changes the verdict, because the caller still asserts on the returned value. """ deadline = time.time() + timeout rows = uv.grid_rows(ax, grid_identifier) while time.time() < deadline and bool(rows) != bool(want_rows): time.sleep(0.4) rows = uv.grid_rows(ax, grid_identifier) return rows
def _find_checkbox(ax, name, root_id=None): """Checkbox located by its visible label (AXTitle/AXDescription).""" want = _norm(name) for el in ax.find(role="checkbox", root_id=root_id, max_depth=40, max_results=80): if _norm(el.name) == want: return el return None
def _outline_button(ax): """The layer-preview 'Outline' drop-down button (exported name, else its label).""" got = uv.find_by_identifier(ax, "LayerPreviewOutlineButton", role="button", max_depth=26) if got: return got[0] return uv.find_button_by_label(ax, "Outline")
def _open_outline(ax, settle=1.5): """Cheap re-open of the Outline drop-down (a toggled entry closes the popup).""" btn = _outline_button(ax) if btn is None: return False uv.press_button(ax, btn) time.sleep(settle) return True
def rb_enter_outline_dropdown(ax, attempts=3): """Open the layer-preview 'Outline' drop-down (a real depth-1 surface).
Verified by the drop-down's OWN content: at rest the app exposes NO checkbox at all, so `uv.checkbox_map` becoming non-empty IS the proof the popup is up. The return value of `uv.rb_enter_dropdown` is deliberately ignored — it reports the menu-item-name delta, and the Outline entries are check items, so it can read False while the popup is perfectly open. """ uv.rb_enter_dropdown(ax, "LayerPreviewOutlineButton") if uv.checkbox_map(ax): return True for _ in range(max(0, attempts - 1)): if not _open_outline(ax): return False if uv.checkbox_map(ax): return True return False
def _outline_checkbox(ax, name): """The Outline drop-down checkbox `name`, reopening the drop-down ONCE if closed.
Toggling a check entry may or may not dismiss the popup depending on the toolkit, so reopen only when the entry is genuinely gone (never blind-press the Outline button — that would CLOSE a popup that is already open). """ el = _find_checkbox(ax, name) if el is not None: return el if not _open_outline(ax): return None return _find_checkbox(ax, name)
def _outline_state(ax, name): el = _outline_checkbox(ax, name) return None if el is None else _bool_state(el.value)
def _poll_outline_state(ax, name, want, timeout=2.0): """Read an Outline checkbox until it reports `want` (or the timeout expires).
Pure waiting: the first read may reopen the drop-down if the press dismissed it, the later reads only re-walk the tree — nothing is ever pressed again, so the returned value stays the app's honest state and the caller's assert keeps meaning. """ got = _outline_state(ax, name) deadline = time.time() + timeout while got is not want and time.time() < deadline: time.sleep(0.4) el = _find_checkbox(ax, name) if el is None: break got = _bool_state(el.value) return got
def _pixel_editor_state(ax): """AXValue of the 'Pixel editor' toolbar toggle (re-located every read).""" btn = uv.find_button_by_label(ax, "Pixel editor") return None if btn is None else _bool_state(btn.value)
def _poll_pixel_editor(ax, want, timeout=3.0): """Read the 'Pixel editor' toggle until it reports `want` (waiting only).""" deadline = time.time() + timeout got = _pixel_editor_state(ax) while got is not want and time.time() < deadline: time.sleep(0.4) got = _pixel_editor_state(ax) return got
def _tab_strip_radios(ax): """The left icon-tab strip radios, ordered left-to-right.
The strip is the TOP-MOST row of radios in the narrow left panel; restricting to that row keeps the pixel editor's own sub-tabs (further down the panel) out. """ cands = [] for el in ax.find(role="radio", max_depth=26, max_results=24): box = uv.frame(ax, el.id) if box and box[2] > 0 and box[3] > 0 and box[0] < 400 and box[1] < 260: cands.append((box[0], box[1] + box[3] / 2.0, el)) if not cands: return [] row_y = min(mid for _x, mid, _el in cands) strip = [(x, el) for x, mid, el in cands if abs(mid - row_y) <= 12] strip.sort(key=lambda pair: pair[0]) return [el for _x, el in strip]
def _pixel_editor_tab(ax): """The pixel-editor tab radio that appears while the toggle is on.
Preferred locator is its exported name (AXIdentifier 'TabPixelEditor'); if a build exports no identifier, fall back to "the left tab strip grew past its 4 default tabs and the extra, currently-selected tab IS the pixel-editor tab". """ got = uv.find_by_identifier(ax, "TabPixelEditor", role="radio", max_depth=26) if got: return got[0] strip = _tab_strip_radios(ax) if len(strip) <= len(TAB_IDS): return None for el in strip: if uv.is_selected(ax, el.id): return el return None
def _looks_like_index(text): val = "".join(str(text or "").split()) return val.count("/") == 1 and val.replace("/", "").isdigit() and val != ""
def _thumb_index_label(ax): """The thumbnail index read-out label element ('1/2'), identifier first.""" for el in uv.find_by_identifier(ax, "PART_Text", role="label", max_depth=26, max_results=8): if _looks_like_index(el.value): return el for el in ax.find(role="label", max_depth=26, max_results=300): if not _looks_like_index(el.value): continue box = uv.frame(ax, el.id) if box and box[0] < 400 and box[1] < 400: # inside the left info panel return el return None
def _thumb_index_text(ax): el = _thumb_index_label(ax) return None if el is None else "".join(str(el.value).split())
def _thumb_buttons(ax): """(previous, next) thumbnail navigation buttons.
Preferred locator is the exported name (PART_PreviousButton / PART_NextButton). Fallback semantics: the two buttons flanking the '1/2' index read-out on the same row — left of it is previous, right of it is next. """ prev = uv.find_by_identifier(ax, "PART_PreviousButton", role="button", max_depth=26, max_results=2) nxt = uv.find_by_identifier(ax, "PART_NextButton", role="button", max_depth=26, max_results=2) if prev and nxt: return (prev[0], nxt[0]) label = _thumb_index_label(ax) lbox = uv.frame(ax, label.id) if label is not None else None if not lbox: return (prev[0] if prev else None, nxt[0] if nxt else None) l_mid = lbox[1] + lbox[3] / 2.0 left, right = [], [] for el in ax.find(role="button", max_depth=26, max_results=300): box = uv.frame(ax, el.id) if not box or box[3] <= 0 or abs(box[1] + box[3] / 2.0 - l_mid) > 20: continue if box[0] + box[2] <= lbox[0]: left.append((box[0], el)) elif box[0] >= lbox[0] + lbox[2]: right.append((box[0], el)) left.sort(key=lambda p: -p[0]) # nearest on the left right.sort(key=lambda p: p[0]) # nearest on the right return ((prev[0] if prev else (left[0][1] if left else None)), (nxt[0] if nxt else (right[0][1] if right else None)))
def _thumb_enabled(ax): """(prev.AXEnabled, next.AXEnabled) for the thumbnail navigation buttons.""" prev_btn, next_btn = _thumb_buttons(ax) if prev_btn is None or next_btn is None: return None return (bool(prev_btn.enabled), bool(next_btn.enabled))
def _poll_thumb_enabled(ax, want, timeout=3.0): """Read the thumbnail buttons' enabled pair until it equals `want` (waiting only).""" deadline = time.time() + timeout got = _thumb_enabled(ax) while got != want and time.time() < deadline: time.sleep(0.4) got = _thumb_enabled(ax) return got
def _frame_active(ax): """True when a window of the app reports itself main/focused (frame ACTIVE).""" for win in ax.find(role="window", max_results=16, max_depth=2): got = ax.get(win.id, ["AXMain", "AXFocused"]) if _bool_state(got.get("AXMain")) or _bool_state(got.get("AXFocused")): return True return False
def rb_enter_main_tab(ax, tab_identifier): """Select a main left-panel tab — a real surface change (its content swaps).
Primary path is the exported name (`uv.rb_enter_tab` clicks the radio whose AXIdentifier matches). Fallback for a build that exports no identifiers: click the tab at that position in the left icon-tab strip (Information, Issues, Suggestions, Clipboard, left to right) and confirm via AXSelected. """ if uv.rb_enter_tab(ax, tab_identifier): return True if tab_identifier not in TAB_IDS: return False strip = _tab_strip_radios(ax) idx = TAB_IDS.index(tab_identifier) if len(strip) <= idx: return False ax.click_element_cg(strip[idx].id) time.sleep(1.4) again = _tab_strip_radios(ax) return len(again) > idx and uv.is_selected(ax, again[idx].id)
# ---------------------------------------------------------------------------# 1-4 main left-panel tab SELECTED state# ---------------------------------------------------------------------------
class TestTabSelectionState:
@pytest.mark.rb(depth=0, jump_kind="value", expect="fresh launch: TabInformation AXSelected=True, " "TabIssues/TabSuggestions/TabClipboard=False, frame active") def test_fresh_launch_tab_selection(self, ax): _wait_ready(ax) sel = _tab_selection(ax) assert sel["TabInformation"] is not None, ( f"no tab radio with AXIdentifier TabInformation; found {sel}") assert kit.rb_value(sel.get("TabInformation"), True), ( f"TabInformation should be AXSelected=True on launch, got {sel}") assert sel["TabInformation"] is True assert sel["TabIssues"] is False, f"TabIssues should not be selected: {sel}" assert sel["TabSuggestions"] is False, f"TabSuggestions should not be selected: {sel}" assert sel["TabClipboard"] is False, f"TabClipboard should not be selected: {sel}" assert sum(1 for v in sel.values() if v is True) == 1, ( f"exactly one tab radio may be selected, got {sel}") assert _frame_active(ax), "no window reports AXMain/AXFocused — frame not active"
@pytest.mark.rb(depth=1, jump_kind="transition", expect="click Issues tab: TabIssues AXSelected False->True while " "TabInformation flips True->False") def test_tab_switch_flips_selection(self, ax): _wait_ready(ax) before = _tab_selection(ax) assert before["TabInformation"] is True, f"unexpected start state {before}" assert before["TabIssues"] is False, f"unexpected start state {before}" assert rb_enter_main_tab(ax, "TabIssues"), "could not select the Issues tab" after = _tab_selection(ax) assert kit.rb_flip(before, after), f"tab selection did not change: {before} -> {after}" assert after["TabIssues"] is True, f"TabIssues must be selected after the click: {after}" assert after["TabInformation"] is False, ( f"TabInformation must be deselected after the click: {after}") assert sum(1 for v in after.values() if v is True) == 1, ( f"exactly one tab radio may be selected, got {after}")
@pytest.mark.rb(depth=1, jump_kind="transition", expect="selecting Issues drops the 6-row CurrentLayerGrid to {} and " "brings up a non-empty IssuesGrid") def test_tab_switch_content_consequence(self, ax): _wait_ready(ax) before_rows = _wait_grid(ax, "CurrentLayerGrid", want_rows=True) assert LAYER_GRID_ROWS <= set(before_rows), ( f"Information tab should show the layer-data grid rows {sorted(LAYER_GRID_ROWS)}, " f"got {sorted(before_rows)}") assert rb_enter_main_tab(ax, "TabIssues"), "could not select the Issues tab" after_rows = _wait_grid(ax, "CurrentLayerGrid", want_rows=False, timeout=3.0) assert kit.rb_flip(before_rows, after_rows), ( f"CurrentLayerGrid unchanged across the tab switch: {after_rows}") assert after_rows == {}, ( f"CurrentLayerGrid must be gone on the Issues tab, got {after_rows}") issues = _wait_grid(ax, "IssuesGrid", want_rows=True, timeout=4.0) assert issues != {}, "IssuesGrid should be populated once the Issues tab is selected"
@pytest.mark.rb(depth=1, jump_kind="transition", expect="Information -> Clipboard -> Information restores " "TabInformation AXSelected=True and the layer-data grid") def test_tab_round_trip_restores_selection(self, ax): _wait_ready(ax) start = _tab_selection(ax) assert start["TabInformation"] is True, f"unexpected start state {start}" assert rb_enter_main_tab(ax, "TabClipboard"), "could not select the Clipboard tab" mid = _tab_selection(ax) assert kit.rb_flip(start, mid), f"selection did not move to Clipboard: {mid}" assert mid["TabClipboard"] is True, f"TabClipboard must be selected: {mid}" assert mid["TabInformation"] is False, f"TabInformation must be deselected: {mid}" assert _wait_grid(ax, "CurrentLayerGrid", want_rows=False, timeout=3.0) == {}, ( "the layer-data grid must disappear on the Clipboard tab") assert rb_enter_main_tab(ax, "TabInformation"), "could not go back to the Information tab" end = _tab_selection(ax) assert kit.rb_flip(mid, end), f"selection did not return to Information: {end}" assert end["TabInformation"] is True, f"TabInformation must be selected again: {end}" assert end["TabClipboard"] is False, f"TabClipboard must be deselected again: {end}" assert LAYER_GRID_ROWS <= set(_wait_grid(ax, "CurrentLayerGrid", want_rows=True)), ( "the layer-data grid must come back with the Information tab")
# ---------------------------------------------------------------------------# 5-7 CHECKED state of the Outline drop-down + the Pixel editor toggle# ---------------------------------------------------------------------------
class TestToggleAndCheckState:
@pytest.mark.rb(depth=1, jump_kind="value", expect="Outline drop-down exposes exactly 10 checkboxes with only " "'Print volume boundary' AXValue=True") def test_outline_dropdown_default_checked_state(self, ax): _wait_ready(ax) assert rb_enter_outline_dropdown(ax), "the Outline drop-down did not open" checks = uv.checkbox_map(ax) assert set(checks) == set(OUTLINE_DEFAULTS), ( f"Outline options should be {sorted(OUTLINE_DEFAULTS)}, got {sorted(checks)}") assert kit.rb_value(checks.get("Print volume boundary"), True), ( f"'Print volume boundary' must be checked by default, got {checks}") assert sorted(name for name, val in checks.items() if val) == ["Print volume boundary"], ( f"only 'Print volume boundary' may be checked, got {checks}") assert checks == OUTLINE_DEFAULTS, f"unexpected Outline default states: {checks}" uv.screenshot_assert( "state_test_outline_dropdown_defaults", "The layer-preview 'Outline' drop-down menu is open below the toolbar. It lists " "10 check-box entries: Print volume boundary, Layer boundary, Blob boundary, " "Enclosing circles, Hollow areas, Centroids, Triangulate, Edge detection, " "Distance detection, Skeletonize. ONLY the first entry, 'Print volume boundary', " "shows a tick/checked box; all nine other boxes are empty/unchecked.", RESULTS_DIR)
@pytest.mark.rb(depth=1, jump_kind="transition", expect="'Layer boundary' checkbox AXValue False->True on press and " "True->False when pressed again (restored)") def test_outline_checkbox_flip_and_restore(self, ax): _wait_ready(ax) assert rb_enter_outline_dropdown(ax), "the Outline drop-down did not open" target = _find_checkbox(ax, "Layer boundary") assert target is not None, "no 'Layer boundary' checkbox in the Outline drop-down" before = _bool_state(target.value) assert before is False, f"'Layer boundary' should start unchecked, got {before!r}" assert uv.press_button(ax, target), "could not press the 'Layer boundary' checkbox" time.sleep(0.6) mid = _poll_outline_state(ax, "Layer boundary", True) assert kit.rb_flip(before, mid), ( f"'Layer boundary' AXValue did not change on press: {before!r} -> {mid!r}") assert mid is True, f"'Layer boundary' must be checked after the press, got {mid!r}" again = _outline_checkbox(ax, "Layer boundary") assert again is not None, "'Layer boundary' checkbox vanished before the restore press" assert uv.press_button(ax, again), "could not press the 'Layer boundary' checkbox again" time.sleep(0.6) after = _poll_outline_state(ax, "Layer boundary", False) assert kit.rb_flip(mid, after), ( f"'Layer boundary' AXValue did not flip back: {mid!r} -> {after!r}") assert after is False, f"'Layer boundary' must be restored to unchecked, got {after!r}"
@pytest.mark.rb(depth=0, jump_kind="transition", expect="'Pixel editor' toggle AXValue False->True (TabPixelEditor radio " "appears selected) ->False on the second press") def test_pixel_editor_toggle_state(self, ax): _wait_ready(ax) toggle = uv.find_button_by_label(ax, "Pixel editor") assert toggle is not None, "no toolbar button labelled 'Pixel editor'" before = _bool_state(toggle.value) assert before is False, f"'Pixel editor' should start off, got {before!r}" assert uv.press_button(ax, toggle), "could not press the 'Pixel editor' toggle" time.sleep(1.0) mid = _poll_pixel_editor(ax, True) assert kit.rb_flip(before, mid), ( f"'Pixel editor' AXValue did not change: {before!r} -> {mid!r}") assert mid is True, f"'Pixel editor' must report AXValue=True when on, got {mid!r}" pe_tab = _pixel_editor_tab(ax) assert pe_tab is not None, ( "no extra pixel-editor tab radio appeared while the pixel editor is on") assert uv.is_selected(ax, pe_tab.id) is True, ( "the pixel-editor tab must be AXSelected while the pixel editor is on") uv.screenshot_assert( "state_test_pixel_editor_enabled", "Pixel editor mode is ON: the 'Pixel editor' button in the toolbar above the black " "layer-preview canvas is pressed/highlighted (toggled on), and a 5th icon tab has " "appeared in the narrow left-hand tab strip and is selected, showing the pixel " "editor panel with its row of drawing sub-tabs instead of the thumbnail/property " "tables.", RESULTS_DIR) back = uv.find_button_by_label(ax, "Pixel editor") assert back is not None, "the 'Pixel editor' toggle disappeared" assert uv.press_button(ax, back), "could not press the 'Pixel editor' toggle again" time.sleep(1.0) after = _poll_pixel_editor(ax, False) assert kit.rb_flip(mid, after), ( f"'Pixel editor' AXValue did not flip back: {mid!r} -> {after!r}") assert after is False, f"'Pixel editor' must return to AXValue=False, got {after!r}"
# ---------------------------------------------------------------------------# 8-10 menu-item ENABLED state on the freshly loaded demo file# ---------------------------------------------------------------------------
class TestMenuEnabledState:
@pytest.mark.rb(depth=1, jump_kind="value", expect="File menu: Save + Reset layers properties DISABLED, " "Save as / Settings / Exit ENABLED") def test_file_menu_enabled_states(self, ax): _wait_ready(ax) assert uv.rb_enter_menu(ax, "File"), "the File menu did not open" states = _menu_enabled_map(ax) observed = {} for name in FILE_MENU_ENABLED: got = _lookup(states, name) assert got is not None, f"File menu item '{name}' not found (items: {sorted(states)})" observed[name] = got assert kit.rb_value(observed, FILE_MENU_ENABLED), ( f"File menu enabled-states {observed} != expected {FILE_MENU_ENABLED}") assert observed["Save"] is False, "File > Save must be DISABLED before any edit" assert observed["Reset layers properties"] is False, ( "File > Reset layers properties must be DISABLED") assert observed["Save as"] is True, "File > Save as must be ENABLED" assert observed["Settings"] is True, "File > Settings must be ENABLED" assert observed["Exit"] is True, "File > Exit must be ENABLED"
@pytest.mark.rb(depth=1, jump_kind="value", expect="Tools menu: the 6 format-unsupported items DISABLED while " "Move/Resize/Blur/Calculator are ENABLED") def test_tools_menu_enabled_partition(self, ax): _wait_ready(ax) assert uv.rb_enter_menu(ax, "Tools"), "the Tools menu did not open" states = _menu_enabled_map(ax) expected = {name: False for name in TOOLS_DISABLED} expected.update({name: True for name in TOOLS_ENABLED}) observed = {} for name in expected: got = _lookup(states, name) assert got is not None, f"Tools menu item '{name}' not found (items: {sorted(states)})" observed[name] = got assert kit.rb_value(observed, expected), ( f"Tools menu enabled-states {observed} != expected {expected}") for name in TOOLS_DISABLED: assert observed[name] is False, f"Tools > {name} must be DISABLED for this file" for name in TOOLS_ENABLED: assert observed[name] is True, f"Tools > {name} must be ENABLED"
@pytest.mark.rb(depth=1, jump_kind="value", expect="Calibration menu: 'Blooming effect' DISABLED, the other 8 " "calibration items ENABLED") def test_calibration_menu_enabled_states(self, ax): _wait_ready(ax) assert uv.rb_enter_menu(ax, "Calibration"), "the Calibration menu did not open" states = _menu_enabled_map(ax) expected = {name: False for name in CALIBRATION_DISABLED} expected.update({name: True for name in CALIBRATION_ENABLED}) observed = {} for name in expected: got = _lookup(states, name) assert got is not None, ( f"Calibration menu item '{name}' not found (items: {sorted(states)})") observed[name] = got assert kit.rb_value(observed, expected), ( f"Calibration enabled-states {observed} != expected {expected}") assert observed["Blooming effect"] is False, ( "Calibration > Blooming effect must be DISABLED") for name in CALIBRATION_ENABLED: assert observed[name] is True, f"Calibration > {name} must be ENABLED"
# ---------------------------------------------------------------------------# 11 button ENABLED state flips (thumbnail navigation)# ---------------------------------------------------------------------------
class TestButtonEnabledState:
@pytest.mark.rb(depth=0, jump_kind="transition", expect="thumbnail 1/2: prev DISABLED + next ENABLED -> after Next " "(2/2) prev ENABLED + next DISABLED") def test_thumbnail_nav_enabled_flip(self, ax): _wait_ready(ax) prev_btn, next_btn = _thumb_buttons(ax) assert prev_btn is not None, "no thumbnail previous button" assert next_btn is not None, "no thumbnail next button" index = _thumb_index_text(ax) assert index == "1/2", f"thumbnail selector should start at 1/2, got {index!r}" before = (bool(prev_btn.enabled), bool(next_btn.enabled)) assert before == (False, True), ( f"at 1/2 prev must be DISABLED and next ENABLED, got prev/next={before}") assert uv.press_button(ax, next_btn), "could not press the thumbnail Next button" time.sleep(0.8) after = _poll_thumb_enabled(ax, (True, False)) assert after is not None, ( "the thumbnail navigation buttons disappeared after pressing Next") assert kit.rb_flip(before, after), ( f"thumbnail button enabled-state did not change: {before} -> {after}") assert after == (True, False), ( f"at 2/2 prev must be ENABLED and next DISABLED, got prev/next={after}") assert _thumb_index_text(ax) == "2/2", "the thumbnail index should read 2/2"
# ---------------------------------------------------------------------------# 12-13 Settings window CHECKED state + category selection (read-only, Escape only)# ---------------------------------------------------------------------------
class TestSettingsWindowState:
@pytest.mark.rb(depth=1, jump_kind="value", expect="Settings > General: Start maximized / Check for updates / demo " "file = True; restore position, restore size, last recent = False") def test_settings_general_checkbox_states(self, ax): _wait_ready(ax, timeout=4.0) win = uv.open_dialog(ax, "File", "Settings", "UVtools - Settings") assert win is not None, "File > Settings did not open the 'UVtools - Settings' window" checks = uv.checkbox_map(ax, root_id=win.id) assert checks, "no checkboxes found in the Settings window" observed = {} for name in SETTINGS_GENERAL_CHECKS: got = _lookup_loose(checks, name) assert got is not None, ( f"Settings checkbox '{name}' not found (found: {sorted(checks)})") observed[name] = got assert kit.rb_value(observed, SETTINGS_GENERAL_CHECKS), ( f"Settings General checked-states {observed} != expected {SETTINGS_GENERAL_CHECKS}") assert observed["Start maximized"] is True assert observed["Check for updates on startup"] is True assert observed["Loads a demo file on startup if no file was specified"] is True assert observed["Restore window last position"] is False assert observed["Restore window last size"] is False assert observed["Loads the last recent file on startup if no file was specified"] is False uv.screenshot_assert( "state_test_settings_general_page", "The 'UVtools - Settings' window is open on top of the main window, showing the " "General category page: the left column lists the categories General (selected/" "highlighted), Layer preview, Issues, Pixel editor, Layer repair, Tools, " "Automations, Network. The General page shows a 'Startup' section whose check " "boxes 'Start maximized', 'Check for updates on startup' and 'Loads a demo file " "on startup if no file was specified' are TICKED, while 'Restore window last " "position', 'Restore window last size' and 'Loads the last recent file on startup " "if no file was specified' are UNTICKED.", RESULTS_DIR) uv.press_escape() # never press Save — it would persist usersettings.xml
@pytest.mark.rb(depth=2, jump_kind="transition", expect="Settings category 'Layer preview' becomes AXSelected while " "'General' deselects, and the page shows Show triangle count=True, " "Show layer difference by default=False, Clear ROI when adding masks=True") def test_settings_category_tab_switch(self, ax): _wait_ready(ax, timeout=4.0) win = uv.open_dialog(ax, "File", "Settings", "UVtools - Settings") assert win is not None, "File > Settings did not open the 'UVtools - Settings' window" before_sel = _radio_selection(ax, root_id=win.id) before = (_lookup(before_sel, "General"), _lookup(before_sel, "Layer preview")) assert before == (True, False), ( f"Settings should open on the General category, got General/Layer preview={before} " f"(radios: {before_sel})") assert uv.select_tab(ax, "Layer preview", root_id=win.id), ( "could not select the 'Layer preview' settings category") after_sel = _radio_selection(ax, root_id=win.id) after = (_lookup(after_sel, "General"), _lookup(after_sel, "Layer preview")) assert kit.rb_flip(before, after), ( f"the settings category selection did not change: {before} -> {after}") assert after == (False, True), ( f"'Layer preview' must be selected and 'General' deselected, got {after}") checks = uv.checkbox_map(ax, root_id=win.id) observed = {} for name in SETTINGS_LAYER_PREVIEW_CHECKS: got = _lookup_loose(checks, name) assert got is not None, ( f"Layer preview checkbox '{name}' not found (found: {sorted(checks)})") observed[name] = got assert observed == SETTINGS_LAYER_PREVIEW_CHECKS, ( f"Layer preview checked-states {observed} != expected " f"{SETTINGS_LAYER_PREVIEW_CHECKS}") uv.press_escape() # never press Save — it would persist usersettings.xml
class TestSettingsCategoryContent: """depth-2 angle: a settings category is not just a radio — selecting it swaps the page underneath it, so the set of option names on screen must change too."""
@pytest.mark.rb(depth=2, jump_kind="transition", expect="selecting the 'Issues' settings category deselects 'General', selects 'Issues' " "and swaps the page: the set of option/label names on screen changes away from " "the General page (Start maximized / Check for updates on startup are gone)") def test_settings_issues_category_swaps_page(self, ax): _wait_ready(ax, timeout=4.0) win = uv.open_dialog(ax, "File", "Settings", "UVtools - Settings") assert win is not None, "File > Settings did not open the 'UVtools - Settings' window" before_sel = _radio_selection(ax, root_id=win.id) assert _lookup(before_sel, "General") is True, ( f"Settings should open on the General category, got {before_sel}") before_page = frozenset(uv.label_values(ax, root_id=win.id, max_results=300)) assert any("Start maximized" in t for t in before_page) or \ any("Startup" in t for t in before_page), ( f"the General page content was not readable: {sorted(before_page)[:15]}")
assert uv.select_tab(ax, "Issues", root_id=win.id), ( "could not select the 'Issues' settings category")
after_sel = _radio_selection(ax, root_id=win.id) assert kit.rb_flip(before_sel, after_sel), ( f"the settings category selection did not change: {before_sel} -> {after_sel}") assert _lookup(after_sel, "Issues") is True, ( f"'Issues' must be selected after the switch, got {after_sel}") assert _lookup(after_sel, "General") is False, ( f"'General' must be deselected after the switch, got {after_sel}") after_page = frozenset(uv.label_values(ax, root_id=win.id, max_results=300)) assert kit.rb_flip(before_page, after_page), ( "the settings page content did not change when the category was switched") assert not any("Start maximized" in t for t in after_page), ( f"the General page is still showing after switching to Issues: " f"{sorted(after_page)[:15]}") uv.press_escape() # never press Save — it would persist usersettings.xml123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421"""AX STRUCTURE tests for UVtools 4.4.2 (macos-sn4k3-uvtools).
Every fact asserted here was observed on the running reference app and is recorded inrecon.md (## APP / ## AX_TREE / ## STRUCTURE). Nothing is hard-coded about where the applives: the `ax` fixture (conftest.py) launches it and hands over an AXHelper, and everyelement lookup goes through the validated helpers in uv_helpers.py, so the SAME moduledrives the reference app and a recreation.
Shape of the suite (13 tests): * 3 existence-GATE tests (depth 0, jump_kind="none") — SPECIFIC named surfaces * 9 shape-delta tests (transition / reach) — the widget tree really changes on a trigger, with the measured "after" counts from recon * 1 value test — the layer-navigation column reports the demo file's 10 layers
The app auto-loads its bundled demo file (UVtools_demo_file.sl1s, 10 layers), so everytest starts from a fully populated workspace. DYNAMIC values from recon (RAM/LO in thewindow title, the render-time label, used material / material cost) are never asserted."""
import os, sys, timeimport pytestsys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))import rb_testgen_kit as kitimport uv_helpers as uv
RESULTS_DIR = os.environ.get("RESULTS_DIR", "/tmp")
# ── recon constants (## APP / ## AX_TREE / ## STRUCTURE) ───────────────────────TOP_MENUS = ["File", "Tools", "Calibration", "Help"]LEFT_TABS = ("TabInformation", "TabIssues", "TabSuggestions", "TabClipboard")PREVIEW_BUTTONS = ("Rotate", "Flip", "Difference", "Issues", "Outline", "Pixel editor", "Actions")SETTINGS_CATEGORIES = ("General", "Layer preview", "Issues", "Pixel editor", "Layer repair", "Tools", "Automations", "Network")OUTLINE_CHECKBOXES = ("Print volume boundary", "Layer boundary", "Blob boundary", "Enclosing circles", "Hollow areas", "Centroids", "Triangulate", "Edge detection", "Distance detection", "Skeletonize")# roles recon saw in the main window's treeCANDIDATE_ROLES = ("window", "menu_bar", "menu_item", "tab_group", "radio", "button", "label", "slider", "grid", "text_field", "image", "scroll_bar")# per-role minimums, kept below the observed counts so a faithful build passes without# being pinned to an exact treeROLE_MINIMUMS = {"window": 1, "menu_bar": 1, "tab_group": 1, "radio": 4, "button": 8, "label": 20, "slider": 1, "image": 1}# NB: the only text_field in the main window is the layer-index spin box, which sits at# depth ~20 — outside the depth-16 scan the totals are measured against. It is asserted# separately below through uv.layer_index(), which searches deep enough to reach it.# the two Information-tab data tables (PropertiesGrid + CurrentLayerGrid); a data grid# may be exported as AXGrid / AXTable / AXOutline, so those roles are pooledTABULAR_ROLES = ("grid", "table", "outline")
def _menu_bar_names(ax): """Top-level menu titles. Primary locator is the validated uv.top_menu_names() (UVtools draws its menu bar INSIDE the window as AXMenuItem nodes and the macOS Apple/app menu pollutes that role with 0-height frames). Semantics-first fallback: a build that exposes the same four titles through a native AXMenuBarItem row.""" names = uv.top_menu_names(ax) if names != TOP_MENUS: alt = [(m.name or "").strip() for m in ax.find(role="menu_bar_item", max_depth=6, max_results=24)] if set(TOP_MENUS).issubset(set(alt)): names = [n for n in alt if n in TOP_MENUS] return names
class TestAXStructureGate: """Existence gate — the named top-level surfaces of a freshly launched app."""
@pytest.mark.rb(depth=0, jump_kind="none") def test_gate_main_window_and_menu_bar(self, ax): win = uv.main_window(ax) assert win is not None, "no top-level window in the app's AX tree" title = win.name or "" for want in ("UVtools", "4.4.2", "UVtools_demo_file.sl1s"): assert want in title, ( f"main window title must contain {want!r} (the bundled demo file " f"auto-loads on startup); got {title!r}") box = uv.frame(ax, win.id) assert box is not None, f"main window has no frame; title={title!r}" assert box[2] >= 800 and box[3] >= 500, ( f"main window too small to be the UVtools workspace " f"(recon: 1920x966); got {box}") names = _menu_bar_names(ax) assert names == TOP_MENUS, f"menu bar must be exactly {TOP_MENUS}; got {names}" uv.screenshot_assert( "structure_test_main_window", "The UVtools main window, maximized. Top-left: a menu bar with exactly four " "menus - File, Tools, Calibration, Help. Left: a narrow panel with 4 small " "icon tabs, a square thumbnail image of the sliced model, a '1/2' thumbnail " "index with prev/next arrows, and two property tables with Name/Value/Group " "columns under a 'Layer data' heading. Centre: a large black layer-preview " "canvas showing the white 'UVtools' logo slice, with a row of buttons above " "it. Right edge: a vertical layer slider with a numeric layer box and SB/LB/" "SN/LN buttons beneath. Bottom: a one-line status bar reading 'Layers: 10 @ " "0.1mm', 'Bottom layers: 10/1mm', 'Exposure: 20/3s', 'Print time: 09m', " "'Used material', 'Material cost', 'Material: ERYONE Water Washable Grey " "@0.10' and 'Machine: UVtools Prusa SL1S SPEED'. The title bar reads " "'UVtools 4.4.2 X64 File: UVtools_demo_file.sl1s (493.06 KB) ...'.", RESULTS_DIR)
@pytest.mark.rb(depth=0, jump_kind="none") def test_gate_left_tabs_and_preview_toolbar(self, ax): radios = ax.find(role="radio", max_depth=26, max_results=40) idents = [uv.identifier(ax, r.id) for r in radios] for ident in LEFT_TABS: assert ident in idents, ( f"left-panel tab {ident} missing; radio identifiers present: {idents}") info = radios[idents.index("TabInformation")] assert uv.is_selected(ax, info.id), ( "TabInformation must be the selected left-panel tab on a fresh launch") for label in PREVIEW_BUTTONS: assert uv.find_button_by_label(ax, label) is not None, ( f"layer-preview toolbar button labelled {label!r} not found " f"(expected all of {list(PREVIEW_BUTTONS)})")
@pytest.mark.rb(depth=0, jump_kind="none") def test_gate_tree_scale_and_role_diversity(self, ax): els = ax.find(max_depth=16, max_results=4000) total = len(els) assert total >= 250, ( f"AX tree far too small for the UVtools workspace: {total} elements " f"(recon measured 432 at max_depth=16)") roles = {} for el in els: roles[el.role] = roles.get(el.role, 0) + 1 present = sorted(r for r in CANDIDATE_ROLES if r in roles) assert len(present) >= 8, ( f"expected >= 8 of the recon roles {list(CANDIDATE_ROLES)}; only got " f"{present} (all roles seen: {sorted(roles)})") for must in ("window", "menu_bar", "button", "label"): assert must in roles, ( f"role {must!r} absent from the tree; roles={sorted(roles)}") for role, need in ROLE_MINIMUMS.items(): assert roles.get(role, 0) >= need, ( f"role {role!r}: {roles.get(role, 0)} element(s), recon requires " f">= {need} (roles seen: {sorted(roles)})") # the editable layer-index field lives deeper than the scan above assert uv.layer_index(ax) == 0, ( f"the layer-index spin box should read 0 on a freshly loaded file, got " f"{uv.layer_index(ax)!r}") tabular = sum(roles.get(r, 0) for r in TABULAR_ROLES) assert tabular >= 2, ( f"expected at least the 2 Information-tab data grids (PropertiesGrid + " f"CurrentLayerGrid), found {tabular} of {list(TABULAR_ROLES)}; " f"roles seen: {sorted(roles)}")
class TestAXStructureMenuShape: """Opening a menu is a real surface jump — the visible menu-item tree must grow by the measured amount and shrink again."""
@pytest.mark.rb(depth=1, jump_kind="transition", expect="File menu popup: visible menu items 4 -> 23 (>= 20 after, " "+19 File items incl. Open/Convert to/Settings/Exit), back " "to 4 on Escape") def test_file_menu_expands_and_collapses(self, ax): before = len(uv.menu_item_names(ax)) assert before <= 6, ( f"only the 4 top-level menus should be visible at rest, got {before}") assert uv.rb_enter_menu(ax, "File"), "the File menu did not open on click" names = uv.menu_item_names(ax) after = len(names) assert kit.rb_flip(before, after), ( f"opening File did not change the visible menu-item count " f"({before} -> {after})") assert after >= 20, ( f"File menu should expose 19 items (recon: 23 visible in total), got " f"{after}: {names}") gained = set(names) - set(TOP_MENUS) assert len(gained) >= 16, ( f"the File menu only added {len(gained)} item(s): {sorted(gained)}") for want in ("Open", "Reload", "Save", "Save as", "Convert to", "Settings", "Exit"): assert want in names, f"File menu missing {want!r}; got {names}" uv.screenshot_assert( "structure_test_file_menu_open", "The File drop-down menu is open directly under the 'File' entry at the top " "left of the UVtools window. It lists, with small icons: Open, Open in new " "window, Open recent, Open in partial mode, Reload, Save (greyed out), Save " "as, Rename, Convert to, Close, Reset layers properties (greyed out), I " "printed this file, Open containing folder, Extract file contents, Copy " "parameters to files, Terminal, Fullscreen, Settings, Exit. The main window " "with its black layer preview, right-hand layer slider and bottom status bar " "is still visible behind the open menu.", RESULTS_DIR) uv.press_escape(2) collapsed = len(uv.menu_item_names(ax)) assert collapsed <= 6, ( f"Escape must collapse the File menu back to the 4 top-level menu items, " f"still seeing {collapsed}")
@pytest.mark.rb(depth=1, jump_kind="transition", expect="Tools menu popup: visible menu items 4 -> 34 (>= 30 after, " "+30 tool items incl. Move/Resize/PCB exposure/Calculator)") def test_tools_menu_expands(self, ax): before = len(uv.menu_item_names(ax)) assert before <= 6, ( f"only the 4 top-level menus should be visible at rest, got {before}") assert uv.rb_enter_menu(ax, "Tools"), "the Tools menu did not open on click" names = uv.menu_item_names(ax) after = len(names) assert kit.rb_flip(before, after), ( f"opening Tools did not change the visible menu-item count " f"({before} -> {after})") assert after >= 30, ( f"Tools menu should expose 30 items (recon: 34 visible in total), got " f"{after}: {names}") for want in ("Edit print parameters", "Repair layers and issues", "Move", "Resize", "Pixel arithmetic", "PCB exposure", "Scripting", "Calculator"): assert want in names, f"Tools menu missing {want!r}; got {names}"
@pytest.mark.rb(depth=1, jump_kind="transition", expect="Calibration menu popup: visible menu items 4 -> 13 (+9 " "calibration items incl. Exposure time finder/External tests)") def test_calibration_menu_expands(self, ax): before = len(uv.menu_item_names(ax)) assert before <= 6, ( f"only the 4 top-level menus should be visible at rest, got {before}") assert uv.rb_enter_menu(ax, "Calibration"), ( "the Calibration menu did not open on click") names = uv.menu_item_names(ax) after = len(names) assert kit.rb_flip(before, after), ( f"opening Calibration did not change the visible menu-item count " f"({before} -> {after})") assert after >= 12, ( f"Calibration menu should expose 9 items (recon: 13 visible in total), got " f"{after}: {names}") for want in ("Exposure time finder", "Elephant foot", "XYZ Accuracy", "Lift height", "Tolerance", "Grayscale", "Stress tower", "External tests"): assert want in names, f"Calibration menu missing {want!r}; got {names}"
@pytest.mark.rb(depth=1, jump_kind="transition", expect="Help menu popup: visible menu items 4 -> 17 (+13 help items " "incl. About/Material manager/Free unused RAM/Benchmark)") def test_help_menu_expands(self, ax): before = len(uv.menu_item_names(ax)) assert before <= 6, ( f"only the 4 top-level menus should be visible at rest, got {before}") assert uv.rb_enter_menu(ax, "Help"), "the Help menu did not open on click" names = uv.menu_item_names(ax) after = len(names) assert kit.rb_flip(before, after), ( f"opening Help did not change the visible menu-item count " f"({before} -> {after})") assert after >= 15, ( f"Help menu should expose 13 items (recon: 17 visible in total), got " f"{after}: {names}") for want in ("About", "Website", "Material manager", "Free unused RAM", "Benchmark"): assert want in names, f"Help menu missing {want!r}; got {names}"
@pytest.mark.rb(depth=2, jump_kind="transition", expect="File > Convert to submenu: visible menu items 4 -> 46 " "(>= 40, past the File menu's own 23) incl. Prusa/Chitubox/" "CWS/NanoDLP/Klipper") def test_convert_to_submenu_is_second_level(self, ax): before = len(uv.menu_item_names(ax)) assert before <= 6, ( f"only the 4 top-level menus should be visible at rest, got {before}") assert uv.rb_enter_submenu(ax, "File", "Convert to"), ( "File > Convert to did not expand into a second-level menu") names = uv.menu_item_names(ax) after = len(names) assert kit.rb_flip(before, after), ( f"the Convert to submenu did not change the visible menu-item count " f"({before} -> {after})") assert after >= 40, ( f"File (23 visible) plus its Convert to submenu (23 formats) should be 46 " f"visible menu items, got {after}: {names}") for want in ("Convert to", "Prusa", "Chitubox", "CWS", "NanoDLP", "Klipper", "Elegoo GOO"): assert want in names, ( f"the Convert to submenu is missing {want!r}; got {names}")
class TestAXStructureSurfaces: """Drop-downs, in-window mode switches and secondary windows."""
@pytest.mark.rb(depth=1, jump_kind="transition", expect="Actions drop-down (id=LayerActionsButton): visible menu " "items 4 -> 13, +9 layer actions incl. Import layers/Clone " "layers/Remove layers/Export layers to images") def test_layer_actions_dropdown_expands(self, ax): before = len(uv.menu_item_names(ax)) assert before <= 6, ( f"only the 4 top-level menus should be visible at rest, got {before}") assert uv.rb_enter_dropdown(ax, "LayerActionsButton"), ( "the 'Actions' drop-down (id=LayerActionsButton) did not open") names = uv.menu_item_names(ax) after = len(names) assert kit.rb_flip(before, after), ( f"the Actions drop-down did not change the visible menu-item count " f"({before} -> {after})") assert after >= 12, ( f"the Actions drop-down should add 9 items (recon: 13 visible in total), " f"got {after}: {names}") for want in ("Import layers", "Clone layers", "Remove layers", "Export layers to images", "Export layers to mesh"): assert want in names, f"the Actions drop-down is missing {want!r}; got {names}"
@pytest.mark.rb(depth=1, jump_kind="transition", expect="Outline drop-down (id=LayerPreviewOutlineButton): 0 -> 10 " "overlay checkboxes (Print volume boundary, Layer boundary, " "Blob boundary, Enclosing circles, Hollow areas, Centroids, " "Triangulate, Edge detection, Distance detection, Skeletonize)") def test_outline_dropdown_exposes_overlay_checkboxes(self, ax): before_map = uv.checkbox_map(ax) before = len(before_map) assert before == 0, ( f"no checkbox should be reachable before the Outline drop-down is opened, " f"got {sorted(before_map)}") assert uv.rb_enter_dropdown(ax, "LayerPreviewOutlineButton"), ( "the 'Outline' drop-down (id=LayerPreviewOutlineButton) did not open") after_map = uv.checkbox_map(ax) after = len(after_map) assert kit.rb_flip(before, after), ( f"the Outline drop-down did not add any checkbox to the tree " f"({before} -> {after})") assert after >= 10, ( f"the Outline drop-down must expose 10 overlay checkboxes, got {after}: " f"{sorted(after_map)}") for want in OUTLINE_CHECKBOXES: assert want in after_map, ( f"the Outline drop-down is missing the {want!r} checkbox; got " f"{sorted(after_map)}")
@pytest.mark.rb(depth=0, jump_kind="transition", expect="Pixel editor toggle: left-strip radios 4 -> 10 with a " "selected TabPixelEditor tab, then back to 4 on a 2nd press") def test_pixel_editor_toggle_changes_tab_strip(self, ax): btn = uv.find_button_by_label(ax, "Pixel editor") assert btn is not None, "no layer-preview toolbar button labelled 'Pixel editor'" before = len(ax.find(role="radio", max_depth=26, max_results=40)) assert before == 4, ( f"expected the 4 left-panel tab radios before enabling the pixel editor, " f"got {before}") assert uv.press_button(ax, btn), "pressing the 'Pixel editor' toggle failed" time.sleep(1.6) after = len(ax.find(role="radio", max_depth=26, max_results=40)) assert kit.rb_flip(before, after), ( f"the Pixel editor toggle did not change the radio count " f"({before} -> {after})") assert after >= 9, ( f"enabling the pixel editor must add the TabPixelEditor tab plus its 5 " f"drawing sub-tabs (recon: 10 radios), got {after}") pe = uv.find_by_identifier(ax, "TabPixelEditor", role="radio", max_depth=26) assert pe, "no radio with AXIdentifier 'TabPixelEditor' appeared in the tab strip" assert uv.is_selected(ax, pe[0].id), ( "the new TabPixelEditor tab must be selected once the pixel editor is on") assert uv.press_button(ax, btn), ( "pressing the 'Pixel editor' toggle a second time failed") time.sleep(1.6) restored = len(ax.find(role="radio", max_depth=26, max_results=40)) assert restored < after and restored <= 5, ( f"turning the pixel editor off must restore the 4-tab strip, got " f"{restored} radios")
@pytest.mark.rb(depth=1, jump_kind="reach", expect="new window 'UVtools - Settings' with the 8 category radios " "General/Layer preview/Issues/Pixel editor/Layer repair/" "Tools/Automations/Network; the File menu popup disappears") def test_settings_window_is_a_new_surface(self, ax): # uv.open_dialog(ax,"File","Settings","UVtools - Settings") unrolled, so the # `before` snapshot is taken while the File popup (the SOURCE surface) is up. assert uv.rb_enter_menu(ax, "File"), "the File menu did not open on click" before = kit.rb_showing(ax) item = uv.menu_item(ax, "Settings") assert item is not None, "no 'Settings' item inside the File menu" uv.click_menu(ax, item, settle=2.6) win = uv.rb_enter_window(ax, "UVtools - Settings") assert win is not None, ( f"File > Settings opened no window titled 'UVtools - Settings'; windows " f"now: {uv.window_titles(ax)}") after = kit.rb_showing(ax) assert kit.rb_reach(before, after, target="UVtools - Settings", source="menu_item|Convert to"), ( "no real surface jump: the 'UVtools - Settings' window must APPEAR while " "the File menu popup (its 'Convert to' item) DISAPPEARS") names = [(r.name or "").strip() for r in ax.find(role="radio", root_id=win.id, max_depth=34, max_results=40)] for want in SETTINGS_CATEGORIES: assert want in names, ( f"the Settings window is missing the {want!r} category tab; radios " f"found: {names}") uv.screenshot_assert( "structure_test_settings_dialog", "A separate window titled 'UVtools - Settings' is in front of the main " "UVtools window. It shows a strip/list of 8 category tabs - General, Layer " "preview, Issues, Pixel editor, Layer repair, Tools, Automations, Network - " "with General selected, and a scrollable General page of grouped check " "boxes under headings such as Startup, Tasks and Windows / dialogs ('Start " "maximized' ticked, 'Check for updates on startup' ticked, 'Loads a demo " "file on startup if no file was specified' ticked). Parts of the main " "window - the black layer preview and the bottom status bar - remain " "visible behind the dialog.", RESULTS_DIR)
@pytest.mark.rb(depth=0, jump_kind="value", expect="LayerSlider max 9 for the 10-layer demo file") def test_layer_navigation_column_reports_10_layers(self, ax): sl = uv.layer_slider(ax) assert sl is not None, ( "no slider with AXIdentifier 'LayerSlider' in the right-hand layer column") got = ax.get(sl.id, ["AXMinValue", "AXMaxValue", "AXValue"]) vmin, vmax = uv.numeric(got.get("AXMinValue")), uv.numeric(got.get("AXMaxValue")) assert kit.rb_value(vmax, 9.0), ( f"LayerSlider AXMaxValue must be 9.0 (10 layers - 1) for " f"UVtools_demo_file.sl1s; got {got}") assert vmin == 0.0, f"LayerSlider AXMinValue must be 0.0; got {got}" assert kit.rb_value(uv.layer_index(ax), 0), ( f"the layer index box under the slider must read 0 on a fresh launch; got " f"{uv.layer_index(ax)!r}") for name in ("SB", "LB", "SN", "LN"): btn = uv.find_button_by_name(ax, name) assert btn is not None, ( f"layer-navigation button {name!r} missing from the right-hand column") assert btn.enabled, f"layer-navigation button {name!r} should be enabled"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695"""AX TEXT tests for UVtools 4.4.2 (macos-sn4k3-uvtools).
Every expected string below was observed on the running reference app and is recorded inrecon.md's ## TEXT section. The app auto-loads its bundled demo file(`UVtools_demo_file.sl1s`, 10 layers, Prusa SL1S SPEED) on every launch, and the pytest`ax` fixture launches a FRESH app per test — so each test starts from the samealready-reset state (Information tab selected, layer 0, thumbnail 1/2).
DYNAMIC values are never asserted by value: the `RAM: … MB` / `LO: …ms` tail of thewindow title, the render-time label, and the `Used material:` / `Material cost:`numbers (recomputed asynchronously) — for those only the label prefix + a positivenumber is checked. In the About dialog only the field LABELS are asserted, never themachine-specific values."""
import os, sys, timeimport pytestsys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))import rb_testgen_kit as kitimport uv_helpers as uv
RESULTS_DIR = os.environ.get("RESULTS_DIR", "/tmp")
# ---------------------------------------------------------------------------# small, portable text readers built on the validated uv_helpers API# ---------------------------------------------------------------------------
def _wait_main_window(ax, timeout=8.0): """The main window, waiting for the AX tree to expose a titled window.
UVtools needs no reveal step (recon: REVEAL_STEPS — none needed; the window is up as soon as the app launches and the `ax` fixture waits for the AX tree), but a slow VM can still hand us the tree a moment before the title is populated. """ win = None deadline = time.time() + timeout while time.time() < deadline: win = uv.main_window(ax) if win is not None and str(win.name or "").strip(): return win time.sleep(0.4) return win
def _stable_title(title): """The window title with the VOLATILE `RAM: … MB LO: …ms` tail removed.
Only this prefix is ever compared, so the constantly-ticking RAM/LO numbers can never make a title assertion flaky. """ out = str(title or "") for volatile in ("RAM:", "LO:"): out = out.split(volatile)[0] return out.strip()
def _lines(value): """Non-empty stripped lines of a multi-line AX text value.""" return [p.strip() for p in str(value or "").replace("\r", "\n").split("\n") if p.strip()]
def _entry_starting(values, prefix): for val in values: if str(val).strip().startswith(prefix): return str(val).strip() return None
def _entry_containing(values, needle): for val in values: if needle in str(val): return str(val).strip() return None
def _entry_with_lines(values, wanted): wanted = list(wanted) for val in values: if _lines(val) == wanted: return str(val) return None
def _texts(ax, root_id=None, max_depth=34): """Every non-empty label value under `root_id`, read in ONE tree walk.
All the read-outs this module asserts (status bar, thumbnail, preview, layer navigation, tab counters, dialog rows) are AXStaticText, so a single `label` pass is enough and keeps every test far inside the 30 s budget. Dialog content sits deep, so callers rooted at a dialog window pass a larger max_depth. """ return [str(v) for v in uv.label_values(ax, root_id=root_id, max_depth=max_depth, max_results=400)]
def _is_counter(text): """True for a `<n>/<n>` counter such as '1/2' or '0/2'.""" parts = str(text).strip().split("/") return len(parts) == 2 and all(p.strip().isdigit() for p in parts)
def _thumbnail_index_text(ax, texts=None): """The `1/2` thumbnail counter (label id=PART_Text of ThumbnailIndexSelector).
Located by identifier first (Avalonia x:Name), preferring the label whose value has the `<n>/<n>` counter shape, then by that same visible shape anywhere in the panel — so a recreation that names the label differently still matches. """ candidates = [str(el.value).strip() for el in uv.find_by_identifier(ax, "PART_Text", role="label", max_depth=26) if el.value not in (None, "")] for text in candidates: if _is_counter(text): return text if candidates: return candidates[0] for val in (texts if texts is not None else _texts(ax)): if _is_counter(val): return str(val).strip() return None
def _thumbnail_resolution_text(ax, texts=None): """The thumbnail resolution label `{Width: 400, Height: 400}`.
Matched on the `{Width:` (colon) spelling — the layer-preview resolution read-out uses `{Width=` (equals), so the two never collide. """ return _entry_starting(texts if texts is not None else _texts(ax), "{Width:")
def _radio_states(ax, root_id): """{radio name: AXSelected} inside a dialog (About/Settings/Calculator tab strips).""" out = {} for el in ax.find(role="radio", root_id=root_id, max_depth=34, max_results=40): name = str(el.name or "").strip() if name: out[name] = uv.is_selected(ax, el.id) return out
# ---------------------------------------------------------------------------# 1. window title# ---------------------------------------------------------------------------
class TestWindowTitleText:
@pytest.mark.rb(depth=0, jump_kind="value", expect="main window title reads 'UVtools 4.4.2 X64 File: " "UVtools_demo_file.sl1s (493.06 KB)' (RAM:/LO: tail excluded)") def test_window_title_content(self, ax): win = _wait_main_window(ax) assert win is not None, "no main window exposed over AX" title = str(win.name or "") assert title.strip(), "main window has an empty AXTitle"
stable = _stable_title(title) # The volatile RAM/LO read-outs are cut off BEFORE any comparison happens. assert "RAM:" not in stable, f"volatile RAM read-out leaked into {stable!r}" assert "LO:" not in stable, f"volatile LO read-out leaked into {stable!r}"
for needle in ("UVtools", "4.4.2", "File:", "UVtools_demo_file.sl1s", "493.06 KB"): assert kit.rb_value(stable, needle), \ f"window title {stable!r} is missing {needle!r} (full title {title!r})"
# ---------------------------------------------------------------------------# 2-5. status bar# ---------------------------------------------------------------------------
class TestStatusBarText:
@pytest.mark.rb(depth=0, jump_kind="value", expect="status bar reads 'Layers: 10 @ 0.1mm' and 'Bottom layers: 10/1mm'") def test_status_bar_file_geometry(self, ax): assert _wait_main_window(ax) is not None, "no main window exposed over AX" texts = uv.status_bar_texts(ax) assert texts, "the bottom status bar exposes no text over AX" # text widgets WITH content on the status bar (8 info labels + separators) assert len([t for t in texts if str(t).strip()]) >= 8, \ f"status bar has too few non-empty labels: {texts}"
layers = _entry_starting(texts, "Layers:") assert kit.rb_value(layers, "Layers: 10 @ 0.1mm"), \ f"expected 'Layers: 10 @ 0.1mm', got {layers!r} (status bar {texts})" assert layers == "Layers: 10 @ 0.1mm", f"not an exact match: {layers!r}" # character count matches the expected text length exactly assert len(layers) == len("Layers: 10 @ 0.1mm"), \ f"unexpected length {len(layers)} for {layers!r}"
bottom = _entry_starting(texts, "Bottom layers:") assert kit.rb_value(bottom, "Bottom layers: 10/1mm"), \ f"expected 'Bottom layers: 10/1mm', got {bottom!r} (status bar {texts})" assert bottom == "Bottom layers: 10/1mm", f"not an exact match: {bottom!r}"
uv.screenshot_assert( "text_test_status_bar_file_info", "UVtools main window, maximized. The one-line status bar along the bottom " "edge reads, left to right separated by ' | ': 'Layers: 10 @ 0.1mm', " "'Bottom layers: 10/1mm', 'Exposure: 20/3s', 'Print time: 09m', " "'Used material: ~1.0ml', 'Material cost: $0.05', " "'Material: ERYONE Water Washable Grey @0.10', " "'Machine: UVtools Prusa SL1S SPEED'. The title bar reads " "'UVtools 4.4.2 X64 File: UVtools_demo_file.sl1s (493.06 KB)' followed by " "live RAM/LO counters. Top-left menu bar: File Tools Calibration Help. The " "narrow left panel shows 4 icon tabs, a square thumbnail image and two " "property tables; the large black layer-preview canvas in the middle shows " "the white 'UVtools' logo slice; a vertical layer slider with SB/LB/SN/LN " "buttons sits on the right edge.", RESULTS_DIR)
@pytest.mark.rb(depth=0, jump_kind="value", expect="status bar reads 'Exposure: 20/3s' and 'Print time: 09m'") def test_status_bar_print_settings(self, ax): assert _wait_main_window(ax) is not None, "no main window exposed over AX" texts = uv.status_bar_texts(ax) assert texts, "the bottom status bar exposes no text over AX"
exposure = _entry_starting(texts, "Exposure:") assert kit.rb_value(exposure, "Exposure: 20/3s"), \ f"expected 'Exposure: 20/3s', got {exposure!r} (status bar {texts})" assert exposure == "Exposure: 20/3s", f"not an exact match: {exposure!r}"
print_time = _entry_starting(texts, "Print time:") assert kit.rb_value(print_time, "Print time: 09m"), \ f"expected 'Print time: 09m', got {print_time!r} (status bar {texts})" assert print_time == "Print time: 09m", f"not an exact match: {print_time!r}"
@pytest.mark.rb(depth=0, jump_kind="value", expect="status bar reads 'Material: ERYONE Water Washable Grey @0.10' " "and 'Machine: UVtools Prusa SL1S SPEED'") def test_status_bar_machine_and_material(self, ax): assert _wait_main_window(ax) is not None, "no main window exposed over AX" texts = uv.status_bar_texts(ax) assert texts, "the bottom status bar exposes no text over AX"
material = _entry_starting(texts, "Material:") assert kit.rb_value(material, "Material: ERYONE Water Washable Grey @0.10"), \ f"expected the ERYONE material name, got {material!r} (status bar {texts})" assert material == "Material: ERYONE Water Washable Grey @0.10", \ f"not an exact match: {material!r}"
machine = _entry_starting(texts, "Machine:") assert kit.rb_value(machine, "Machine: UVtools Prusa SL1S SPEED"), \ f"expected 'Machine: UVtools Prusa SL1S SPEED', got {machine!r} " \ f"(status bar {texts})" assert machine == "Machine: UVtools Prusa SL1S SPEED", \ f"not an exact match: {machine!r}"
@pytest.mark.rb(depth=0, jump_kind="value", expect="Used material / Material cost labels present with a positive number") def test_status_bar_dynamic_material_pair(self, ax): # The two numbers here are recomputed asynchronously after the layer decode # (1.037ml -> 1.175ml, $0.05 -> $0.06), so ONLY the label prefix is compared and # the number is merely required to be positive. assert _wait_main_window(ax) is not None, "no main window exposed over AX" texts = uv.status_bar_texts(ax) assert texts, "the bottom status bar exposes no text over AX"
used = _entry_starting(texts, "Used material:") assert kit.rb_value(used, "Used material:"), \ f"no 'Used material:' entry on the status bar: {texts}" used_n = uv.numeric(used) assert used_n is not None and used_n > 0, \ f"'Used material:' carries no positive volume: {used!r}" assert "ml" in used, f"'Used material:' is not in millilitres: {used!r}"
cost = _entry_starting(texts, "Material cost:") assert kit.rb_value(cost, "Material cost:"), \ f"no 'Material cost:' entry on the status bar: {texts}" cost_n = uv.numeric(cost) assert cost_n is not None and cost_n > 0, \ f"'Material cost:' carries no positive amount: {cost!r}" assert "$" in cost, f"'Material cost:' shows no currency symbol: {cost!r}"
# ---------------------------------------------------------------------------# 6-8. Information tab (summary labels + the two data grids)# ---------------------------------------------------------------------------
class TestInformationTabText:
@pytest.mark.rb(depth=0, jump_kind="value", expect="Information tab shows '1/2', '{Width: 400, Height: 400}', " "'Properties: 154', 'Groups: 4', 'Layer data'") def test_information_tab_summary_labels(self, ax): assert _wait_main_window(ax) is not None, "no main window exposed over AX" # ONE tree walk over every AXStaticText, then split into "has content" / # "has no content" — the text-accessibility census asked for by the contract. all_labels = ax.find(role="label", max_depth=34, max_results=400) assert all_labels, "the app exposes no AXStaticText nodes at all" texts = [str(el.value).strip() for el in all_labels if str(el.value or "").strip()] without_content = [el for el in all_labels if not str(el.value or "").strip()] assert len(texts) >= 20, \ f"only {len(texts)} text widgets carry content ({len(without_content)} empty)" # every reported value's character count equals its real (stripped) length assert all(len(t) == len(t.strip()) and len(t) > 0 for t in texts), \ "a reported text value has a length mismatch" joined = "\n".join(texts)
index_text = _thumbnail_index_text(ax, texts) assert kit.rb_value(index_text, "1/2"), \ f"thumbnail counter should read '1/2', got {index_text!r}" assert index_text == "1/2", f"not an exact match: {index_text!r}" # character count matches the actual text length assert len(index_text) == len("1/2"), \ f"unexpected length {len(index_text)} for {index_text!r}"
resolution = _thumbnail_resolution_text(ax, texts) assert kit.rb_value(resolution, "{Width: 400, Height: 400}"), \ f"thumbnail resolution should read '{{Width: 400, Height: 400}}', got {resolution!r}"
for needle in ("Properties: 154", "Groups: 4"): assert kit.rb_value(joined, needle), \ f"Information tab is missing the label {needle!r}" assert kit.rb_value(joined, "Layer data"), \ "Information tab is missing the 'Layer data' section label" assert "Layer data" in texts, \ f"'Layer data' is not a standalone label: {texts}"
@pytest.mark.rb(depth=0, jump_kind="value", expect="PropertiesGrid maps HostType->octoprint, PrinterSettingsId->" "UVtools Prusa SL1S SPEED, PrinterTechnology->SLA, PrinterModel->SL1S") def test_properties_grid_content(self, ax): assert _wait_main_window(ax) is not None, "no main window exposed over AX" rows = uv.grid_rows(ax, "PropertiesGrid") assert rows, "PropertiesGrid exposes no rows (Information tab must be selected)" expected = { "HostType": "octoprint", "PrinterSettingsId": "UVtools Prusa SL1S SPEED", "PrinterTechnology": "SLA", "PrinterModel": "SL1S", } for name, value in expected.items(): got = rows.get(name) assert kit.rb_value(got, value), \ f"PropertiesGrid[{name}] should read {value!r}, got {got!r} (rows {rows})" assert str(got).strip() == value, \ f"PropertiesGrid[{name}] is not an exact match: {got!r}"
@pytest.mark.rb(depth=0, jump_kind="value", expect="CurrentLayerGrid at layer 0: Index=0, LayerHeight=0.100mm, " "PositionZ=0.100mm, IsBottomLayer=True, ExposureTime=20.00s, " "MaterialMilliliters=0.1215ml (10.34%)") def test_current_layer_grid_content(self, ax): assert _wait_main_window(ax) is not None, "no main window exposed over AX" rows = uv.grid_rows(ax, "CurrentLayerGrid") assert rows, "CurrentLayerGrid exposes no rows (Information tab must be selected)" expected = { "Index": "0", "LayerHeight": "0.100mm", "PositionZ": "0.100mm", "IsBottomLayer": "True", "ExposureTime": "20.00s", } for name, value in expected.items(): got = rows.get(name) assert kit.rb_value(got, value), \ f"CurrentLayerGrid[{name}] should read {value!r}, got {got!r} (rows {rows})" assert str(got).strip() == value, \ f"CurrentLayerGrid[{name}] is not an exact match: {got!r}"
millilitres = rows.get("MaterialMilliliters") assert kit.rb_value(millilitres, "0.1215ml"), \ f"CurrentLayerGrid[MaterialMilliliters] should start with '0.1215ml', " \ f"got {millilitres!r}" assert str(millilitres).strip().startswith("0.1215ml"), \ f"MaterialMilliliters does not start with '0.1215ml': {millilitres!r}"
# ---------------------------------------------------------------------------# 9. layer preview + layer navigation read-outs# ---------------------------------------------------------------------------
class TestLayerPreviewText:
@pytest.mark.rb(depth=0, jump_kind="value", expect="layer preview reads 'Pixels: 486195 (11.72%)' / " "'Volume: 121.55mm³', 'ROI: NS', 'Zoom: [ 0.55x ]' / " "'Pixel: 50µm', '{Width=1620, Height=2560} px' / " "'{Width=81, Height=128} mm', layer nav '1mm/9', '0.100mm/0/10%', '0.1mm/0'") def test_layer_preview_readouts(self, ax): assert _wait_main_window(ax) is not None, "no main window exposed over AX" texts = _texts(ax) assert texts, "the app exposes no text values over AX"
pixels = _entry_containing(texts, "Pixels:") assert kit.rb_value(pixels, "Pixels: 486195 (11.72%)"), \ f"layer-0 pixel read-out should be 'Pixels: 486195 (11.72%)', got {pixels!r}" assert kit.rb_value(pixels, "Volume: 121.55mm³"), \ f"layer-0 volume read-out should be 'Volume: 121.55mm³', got {pixels!r}"
roi = _entry_starting(texts, "ROI:") or uv.find_text(ax, "ROI:") assert kit.rb_value(roi, "ROI: NS"), f"ROI read-out should be 'ROI: NS', got {roi!r}"
zoom = _entry_containing(texts, "Zoom:") assert kit.rb_value(zoom, "Zoom: [ 0.55x ]"), \ f"zoom read-out should be 'Zoom: [ 0.55x ]', got {zoom!r}" assert kit.rb_value(zoom, "Pixel: 50µm"), \ f"pixel-size read-out should be 'Pixel: 50µm', got {zoom!r}"
resolution = _entry_containing(texts, "{Width=") assert kit.rb_value(resolution, "{Width=1620, Height=2560} px"), \ f"resolution read-out should be '{{Width=1620, Height=2560}} px', got {resolution!r}" assert kit.rb_value(resolution, "{Width=81, Height=128} mm"), \ f"display-size read-out should be '{{Width=81, Height=128}} mm', got {resolution!r}"
# layer-navigation column: top layer, current-layer tooltip, bottom layer top = _entry_with_lines(texts, ("1mm", "9")) assert top is not None, \ f"top-of-slider read-out '1mm / 9' not found among {[str(t) for t in texts][:40]}" assert kit.rb_value(top, "1mm") and kit.rb_value(top, "9"), \ f"top-of-slider read-out is wrong: {top!r}"
tooltip = uv.layer_tooltip(ax) assert kit.rb_value(tooltip, "0.100mm"), \ f"layer tooltip should start with '0.100mm', got {tooltip!r}" assert _lines(tooltip) == ["0.100mm", "0", "10%"], \ f"layer tooltip should read '0.100mm / 0 / 10%', got {tooltip!r}"
bottom = _entry_with_lines(texts, ("0.1mm", "0")) assert bottom is not None, \ f"bottom-of-slider read-out '0.1mm / 0' not found among " \ f"{[str(t) for t in texts][:40]}" assert kit.rb_value(bottom, "0.1mm"), \ f"bottom-of-slider read-out is wrong: {bottom!r}"
# ---------------------------------------------------------------------------# 10. Issues tab (depth 1 — the tab is navigated to in this test)# ---------------------------------------------------------------------------
class TestIssuesTabText:
@pytest.mark.rb(depth=1, jump_kind="value", expect="Issues tab shows counter '0/2', a 'Detect' button and two " "IssuesGrid rows 'SuctionCup' / '0-9 (10)'") def test_issues_tab_text(self, ax): assert _wait_main_window(ax) is not None, "no main window exposed over AX" assert uv.rb_enter_tab(ax, "TabIssues"), "could not select the Issues tab"
texts = [str(t).strip() for t in _texts(ax)] assert texts, "the Issues tab exposes no text values over AX"
counter = next((t for t in texts if t == "0/2"), None) assert kit.rb_value(counter, "0/2"), \ f"Issues tab should show the counter '0/2', got {counter!r} (texts {texts[:40]})"
# 'Detect' is rendered as the label INSIDE the button (Avalonia buttons carry a # junk AXTitle), so accept either the bare label or the enclosing button. assert "Detect" in texts or uv.find_button_by_label(ax, "Detect") is not None, \ f"Issues tab is missing the 'Detect' label/button: {texts[:40]}"
# the grid groups issues by type, so the first line under the column header is a # one-cell group caption ('SuctionCup'); the data rows carry Type/Layer(s)/Area. all_rows = uv.grid_row_list(ax, "IssuesGrid") rows = [r for r in all_rows if len(r) >= 2] assert len(rows) >= 2, ( f"IssuesGrid should list at least 2 issue rows, got {rows} (all lines {all_rows})") for row in rows[:2]: assert len(row) >= 2, f"issue row has too few cells: {row}" assert kit.rb_value(row[0], "SuctionCup"), \ f"issue type should be 'SuctionCup', got {row[0]!r} (row {row})" assert kit.rb_value(row[1], "0-9"), \ f"issue layer range should contain '0-9', got {row[1]!r} (row {row})"
uv.screenshot_assert( "text_test_issues_tab_table", "UVtools main window with the Issues tab selected in the narrow left panel. " "The panel shows an issues table with the column headers Type / Layer(s) / " "Area and exactly two rows, both of type 'SuctionCup', both spanning layers " "'0-9 (10)', with areas '291,816' and '291,802'. Above the table there is a " "'Detect' button and a counter reading '0/2'. To the right the large black " "layer-preview canvas still shows the white UVtools logo slice, and the " "bottom status bar keeps showing 'Layers: 10 @ 0.1mm ... Machine: UVtools " "Prusa SL1S SPEED'.", RESULTS_DIR)
# ---------------------------------------------------------------------------# 11-12. interaction -> text change# ---------------------------------------------------------------------------
class TestTextAfterInteraction:
@pytest.mark.rb(depth=0, jump_kind="transition", expect="thumbnail next: '1/2' -> '2/2' and '{Width: 400, Height: 400}' " "-> '{Width: 800, Height: 480}'") def test_thumbnail_next_changes_text(self, ax): # Fresh app per test => state is already reset (thumbnail 1 of 2 selected). assert _wait_main_window(ax) is not None, "no main window exposed over AX" buttons = uv.find_by_identifier(ax, "PART_NextButton", role="button", max_depth=26) assert buttons, "the thumbnail 'next' button (PART_NextButton) was not found"
index_before = _thumbnail_index_text(ax) resolution_before = _thumbnail_resolution_text(ax) assert kit.rb_value(index_before, "1/2"), \ f"thumbnail counter should start at '1/2', got {index_before!r}" assert kit.rb_value(resolution_before, "{Width: 400, Height: 400}"), \ f"thumbnail resolution should start at '{{Width: 400, Height: 400}}', " \ f"got {resolution_before!r}"
assert uv.press_button(ax, buttons[0]), "pressing PART_NextButton failed" time.sleep(0.9)
after_texts = _texts(ax) index_after = _thumbnail_index_text(ax, after_texts) resolution_after = _thumbnail_resolution_text(ax, after_texts)
assert kit.rb_flip(index_before, index_after), \ f"thumbnail counter did not change: {index_before!r} -> {index_after!r}" assert kit.rb_value(index_after, "2/2"), \ f"thumbnail counter should read '2/2' after 'next', got {index_after!r}"
assert kit.rb_flip(resolution_before, resolution_after), \ f"thumbnail resolution did not change: " \ f"{resolution_before!r} -> {resolution_after!r}" assert kit.rb_value(resolution_after, "{Width: 800, Height: 480}"), \ f"thumbnail resolution should read '{{Width: 800, Height: 480}}' after " \ f"'next', got {resolution_after!r}"
@pytest.mark.rb(depth=0, jump_kind="transition", expect="LB: layer tooltip '0.100mm/0/10%' -> '1.000mm/9/100%' and " "'Pixels: 486195' -> 'Pixels: 568399'") def test_layer_navigation_changes_text(self, ax): # Fresh app per test => the layer slider starts at layer 0. assert _wait_main_window(ax) is not None, "no main window exposed over AX" lb = uv.find_button_by_name(ax, "LB") assert lb is not None, "the 'LB' (largest bottom layer) button was not found"
tooltip_before = uv.layer_tooltip(ax) pixels_before = _entry_containing(_texts(ax), "Pixels:") assert _lines(tooltip_before) == ["0.100mm", "0", "10%"], \ f"layer tooltip should start at '0.100mm / 0 / 10%', got {tooltip_before!r}" assert kit.rb_value(pixels_before, "486195"), \ f"layer-0 pixel read-out should be 486195, got {pixels_before!r}"
assert uv.press_button(ax, lb), "pressing the 'LB' button failed" time.sleep(1.2)
tooltip_after = uv.layer_tooltip(ax) pixels_after = _entry_containing(_texts(ax), "Pixels:")
assert kit.rb_flip(tooltip_before, tooltip_after), \ f"layer tooltip did not change: {tooltip_before!r} -> {tooltip_after!r}" for needle in ("1.000mm", "9", "100%"): assert kit.rb_value(tooltip_after, needle), \ f"layer tooltip should contain {needle!r} after 'LB', got {tooltip_after!r}"
assert kit.rb_flip(pixels_before, pixels_after), \ f"pixel read-out did not change: {pixels_before!r} -> {pixels_after!r}" assert kit.rb_value(pixels_after, "568399"), \ f"layer-9 pixel read-out should be 568399, got {pixels_after!r}"
# ---------------------------------------------------------------------------# 13-14. dialog text (depth 1 / depth 2)# ---------------------------------------------------------------------------
class TestDialogText:
@pytest.mark.rb(depth=1, jump_kind="value", expect="'About UVtools v4.4.2' window shows 'UVtools', '4.4.2 X64', " "'Copyright 2020-2026 © PTRTECH', the AGPL licence line, " "'Terms of Use', 'Tiago Conceição' and the system " "field LABELS (Operative System:, Processor cores:, Memory RAM:, " "Runtime:, OpenCV:, AvaloniaUI:)") def test_about_dialog_text(self, ax): assert _wait_main_window(ax) is not None, "no main window exposed over AX" about = uv.open_dialog(ax, "Help", "About", "About") assert about is not None, "Help > About did not open an 'About' window"
title = str(about.name or "") assert kit.rb_value(title, "About UVtools"), \ f"the dialog title should contain 'About UVtools', got {title!r}"
texts = [str(t).strip() for t in _texts(ax, root_id=about.id, max_depth=44)] assert texts, "the About dialog exposes no text values over AX" joined = "\n".join(texts)
needles = ("UVtools", "4.4.2 X64", "Copyright 2020-2026 © PTRTECH", "GNU Affero General Public License v3.0 (AGPL)", "Terms of Use", "Tiago Conceição", # only the LABELS — every value on these rows is machine specific "Operative System:", "Processor cores:", "Memory RAM:", "Runtime:", "OpenCV:", "AvaloniaUI:") if any(n not in joined for n in needles): # second chance: pick up anything rendered in a text field / text area too extra = [str(t).strip() for t in uv.text_values(ax, root_id=about.id, max_depth=44)] joined = "\n".join(sorted(set(texts) | set(extra)))
for needle in needles: assert kit.rb_value(joined, needle), \ f"About dialog is missing {needle!r} (texts {texts[:40]})"
uv.screenshot_assert( "text_test_about_dialog", "The 'About UVtools v4.4.2' window is in front of the UVtools main window. It " "shows the UVtools logo and name, the version '4.4.2 X64', " "'Copyright 2020-2026 © PTRTECH', the licence line 'GNU Affero General " "Public License v3.0 (AGPL)' next to 'Terms of Use', the author " "'Tiago Conceição' and an 'Age:' line. A Description / OpenCV / " "Assemblies tab strip sits in the middle with Description selected, listing " "system rows labelled 'Operative System:', 'Processor:', 'Processor cores:', " "'Memory RAM:', 'Runtime:', 'OpenCV:', 'Framework:', 'AvaloniaUI:' (their " "values are machine specific). 'Copy information' and 'Close' buttons are at " "the bottom.", RESULTS_DIR)
@pytest.mark.rb(depth=2, jump_kind="transition", expect="About dialog tab strip: OpenCV becomes AXSelected=True and " "Description AXSelected=False") def test_about_dialog_opencv_tab_text(self, ax): assert _wait_main_window(ax) is not None, "no main window exposed over AX" about = uv.open_dialog(ax, "Help", "About", "About") # surface 1 assert about is not None, "Help > About did not open an 'About' window"
before = _radio_states(ax, about.id) assert "OpenCV" in before, \ f"the About dialog exposes no 'OpenCV' tab: {before}" assert before.get("OpenCV") is False, \ f"'OpenCV' should not be the tab selected on open: {before}"
assert uv.select_tab(ax, "OpenCV", root_id=about.id), \ "could not select the 'OpenCV' tab inside the About dialog" # surface 2 after = _radio_states(ax, about.id)
assert kit.rb_flip(before, after), \ f"the About dialog tab selection did not change: {before} -> {after}" assert after.get("OpenCV") is True, \ f"'OpenCV' should be selected after the switch: {after}" assert after.get("Description") is False, \ f"'Description' should be deselected after the switch: {after}"
@pytest.mark.rb(depth=2, jump_kind="transition", expect="About > Assemblies tab: Assemblies becomes AXSelected=True, Description " "AXSelected=False, and the pane's text swaps away from the Description page " "(the 'Operative System:'/'Processor cores:' field labels are gone)") def test_about_dialog_assemblies_tab_text(self, ax): assert _wait_main_window(ax) is not None, "no main window exposed over AX" about = uv.open_dialog(ax, "Help", "About", "About") # surface 1 assert about is not None, "Help > About did not open an 'About' window"
before = _radio_states(ax, about.id) assert "Assemblies" in before, \ f"the About dialog exposes no 'Assemblies' tab: {before}" assert before.get("Description") is True, \ f"'Description' should be the tab selected on open: {before}" # NB: the system fields (Operative System: ...) live in the dialog's LEFT column, # outside the tab pane, so they stay visible on every tab. What swaps is the pane # itself: the Description blurb vs the loaded-assembly list. before_pane = frozenset( str(t).strip() for t in uv.text_values(ax, root_id=about.id, max_results=200)) assert any("Available File Formats:" in t for t in before_pane), \ f"the Description pane content was not readable: {sorted(before_pane)[:8]}"
assert uv.select_tab(ax, "Assemblies", root_id=about.id), \ "could not select the 'Assemblies' tab inside the About dialog" # surface 2 after = _radio_states(ax, about.id)
assert kit.rb_flip(before, after), \ f"the About dialog tab selection did not change: {before} -> {after}" assert after.get("Assemblies") is True, \ f"'Assemblies' should be selected after the switch: {after}" assert after.get("Description") is False, \ f"'Description' should be deselected after the switch: {after}"
after_pane = frozenset( str(t).strip() for t in uv.text_values(ax, root_id=about.id, max_results=200)) assert kit.rb_flip(before_pane, after_pane), \ "the About dialog pane text did not change when the tab was switched" assert not any("Available File Formats:" in t for t in after_pane), \ "the Description pane is still showing after switching to Assemblies" assert any("UVtools.Core, Version=" in t for t in after_pane), \ f"the Assemblies pane should list the loaded assemblies (UVtools.Core ...): " \ f"{sorted(after_pane)[:8]}"12345678910111213141516171819202122232425262728293031323334353637{ "ax_total": 82, "vlm_total": 14, "ax_by_lane": { "test_ax_buttons.py": 13, "test_ax_computation.py": 11, "test_ax_menus.py": 16, "test_ax_states.py": 14, "test_ax_structure.py": 13, "test_ax_text.py": 15 }, "vlm_by_dir": { "buttons": 2, "computation": 2, "menus": 3, "states": 2, "structure": 3, "text": 2 }, "vlm_names": [ "button_test_lb_button_selects_layer_nine.png", "button_test_thumbnail_next_selects_second_thumbnail.png", "computation_test_calculator_mm_to_pixels.png", "computation_test_calculator_optimal_tilt.png", "menu_test_about_dialog.png", "menu_test_convert_to_submenu.png", "menu_test_file_menu.png", "state_test_pixel_editor_enabled.png", "state_test_settings_general_page.png", "structure_test_file_menu_open.png", "structure_test_main_window.png", "structure_test_settings_dialog.png", "text_test_about_dialog.png", "text_test_issues_tab_table.png" ], "frozen_at": "stage2_finalize"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615"""UVtools AX test helpers — shared by the generated test_ax_*.py modules.
Portable by construction: every function takes the `ax` AXHelper handed over by thepytest `ax` fixture (the harness launches the app), never a path or a pid, so the SAMEtest drives the reference app AND a recreation.
Locator philosophy (UVtools is Avalonia — its AX tree has quirks): * push buttons expose AXPress but their AXTitle is junk ("Avalonia.Controls.PathIcon"), so buttons are located by the *label text rendered inside them* -> find_button_by_label(). * the app's menu bar is drawn INSIDE the window as AXMenuItem nodes (File/Tools/ Calibration/Help); those menu items expose NO AX actions, so they must be opened with a real click -> rb_enter_menu(). The macOS-level Apple/app menu also contributes AXMenuItem nodes with a 0-height frame; visible_menu_items() filters those out. * data grids expose their cells as AXStaticText; grid_rows() pairs them by row y."""from __future__ import annotations
import jsonimport osimport reimport subprocessimport time
import Quartzfrom ApplicationServices import AXUIElementCopyAttributeValue
KC_ESCAPE = 53KC_RETURN = 36KC_TAB = 48
# ---------------------------------------------------------------------------# low level# ---------------------------------------------------------------------------
def _attr(ax, element_id, name): ref = ax._get_ref(element_id) if ref is None: return None try: err, val = AXUIElementCopyAttributeValue(ref, name, None) return val if err == 0 else None except Exception: return None
def identifier(ax, element_id): """AXIdentifier (Avalonia exports x:Name here). '' when absent.""" return str(_attr(ax, element_id, "AXIdentifier") or "")
def is_selected(ax, element_id): return bool(_attr(ax, element_id, "AXSelected"))
def frame(ax, element_id): """(x, y, w, h) in screen points, or None.""" got = ax.get(element_id, ["AXPosition", "AXSize"])
def nums(v): found = re.findall(r"[-\d.]+", str(v)) return [float(x) for x in found[-2:]] if len(found) >= 2 else None
pos, size = nums(got.get("AXPosition")), nums(got.get("AXSize")) if not pos or not size: return None return (pos[0], pos[1], size[0], size[1])
def send_key(keycode, modifiers=None): """Synthesize a key press for the frontmost app (the harness activates it).""" src = Quartz.CGEventSourceCreate(Quartz.kCGEventSourceStateHIDSystemState) down = Quartz.CGEventCreateKeyboardEvent(src, keycode, True) up = Quartz.CGEventCreateKeyboardEvent(src, keycode, False) if modifiers: flag_map = { "cmd": Quartz.kCGEventFlagMaskCommand, "shift": Quartz.kCGEventFlagMaskShift, "alt": Quartz.kCGEventFlagMaskAlternate, "ctrl": Quartz.kCGEventFlagMaskControl, } flags = 0 for mod in modifiers: flags |= flag_map.get(mod, 0) Quartz.CGEventSetFlags(down, flags) Quartz.CGEventSetFlags(up, flags) Quartz.CGEventPost(Quartz.kCGHIDEventTap, down) Quartz.CGEventPost(Quartz.kCGHIDEventTap, up) time.sleep(0.3)
def press_escape(times=2): for _ in range(times): send_key(KC_ESCAPE) time.sleep(0.2)
def press_button(ax, element): """AXPress the element, falling back to a real click. Returns True on either.""" if element is None: return False eid = getattr(element, "id", element) if ax.action(eid, "AXPress"): return True return ax.click_element_cg(eid)
# ---------------------------------------------------------------------------# discovery# ---------------------------------------------------------------------------
def main_window(ax): """The biggest top-level window — UVtools' main window (title carries the file).""" best, best_area = None, -1.0 for win in ax.find(role="window", max_results=12, max_depth=2): box = frame(ax, win.id) area = (box[2] * box[3]) if box else 0.0 if area > best_area: best, best_area = win, area return best
def window_titles(ax): return [w.name or "" for w in ax.find(role="window", max_results=16, max_depth=2)]
def find_window(ax, title_contains): needle = title_contains.lower() for win in ax.find(role="window", max_results=16, max_depth=2): if needle in (win.name or "").lower(): return win return None
def elements(ax, role=None, root_id=None, max_depth=40, max_results=400): return ax.find(role=role, root_id=root_id, max_depth=max_depth, max_results=max_results)
def label_values(ax, root_id=None, max_depth=40, max_results=400): """Every non-empty AXStaticText value under root (default: whole app).""" out = [] for el in ax.find(role="label", root_id=root_id, max_depth=max_depth, max_results=max_results): if el.value not in (None, ""): out.append(str(el.value)) return out
def text_values(ax, root_id=None, max_depth=40, max_results=400): """label + text_field + text_area values (read-only display fields included).""" out = [] for role in ("label", "text_field", "text_area"): for el in ax.find(role=role, root_id=root_id, max_depth=max_depth, max_results=max_results): if el.value not in (None, ""): out.append(str(el.value)) return out
def find_text(ax, needle, root_id=None, max_depth=40): """First text value containing `needle` (case-insensitive), else None.""" low = needle.lower() for val in text_values(ax, root_id=root_id, max_depth=max_depth): if low in val.lower(): return val return None
def status_bar_texts(ax): """Labels on the bottom status bar of the main window.""" win = main_window(ax) if win is None: return [] box = frame(ax, win.id) if not box: return [] bottom = box[1] + box[3] out = [] for el in ax.find(role="label", max_depth=22, max_results=400): if el.value in (None, ""): continue pos = frame(ax, el.id) if pos and pos[1] >= bottom - 45: out.append(str(el.value)) return out
def find_button_by_label(ax, text, root_id=None, max_depth=26, exact=True): """Avalonia button whose rendered label text matches `text` (e.g. 'Rotate', 'Close').
Returns the innermost enclosing AXButton, or None. """ want = text.strip().lower() hits = []
def walk(ref, depth, button): if depth > max_depth or hits: return el = ax._ref_to_element(ref) cur = el if el.role == "button" else button if el.role in ("label", "text_field") and cur is not None: val = str(el.value or "").strip().lower() if (val == want) if exact else (want in val): hits.append(cur) return err, children = AXUIElementCopyAttributeValue(ref, "AXChildren", None) if err == 0 and children: for child in children: walk(child, depth + 1, cur) if hits: return
root = ax._get_ref(root_id) if root_id else ax._app_ref walk(root, 0, None) return hits[0] if hits else None
def find_button_by_name(ax, name, root_id=None, max_depth=26): """Button whose AXTitle equals `name` (UVtools uses this for 'SB'/'LB'/'SN'/'LN', 'Start', and data-grid column headers).""" for el in ax.find(role="button", name=name, root_id=root_id, max_depth=max_depth, max_results=4): return el return None
def find_by_identifier(ax, ident, role=None, root_id=None, max_depth=26, max_results=6): """Elements whose AXIdentifier == ident (Avalonia x:Name).""" out = []
def walk(ref, depth): if depth > max_depth or len(out) >= max_results: return el = ax._ref_to_element(ref) if (role is None or el.role == role) and identifier(ax, el.id) == ident: out.append(el) err, children = AXUIElementCopyAttributeValue(ref, "AXChildren", None) if err == 0 and children: for child in children: walk(child, depth + 1)
walk(ax._get_ref(root_id) if root_id else ax._app_ref, 0) return out
def visible_menu_items(ax, root_id=None, max_depth=26, max_results=240): """Menu items that are really on screen.
The macOS-level Apple/app menu also lives in this app's AX tree with 0-height frames; those are filtered out so a count/name assertion only sees the app's own (in-window) menus and whatever popup is currently open. """ out = [] for el in ax.find(role="menu_item", root_id=root_id, max_depth=max_depth, max_results=max_results): box = frame(ax, el.id) if box and box[3] > 0: out.append(el) return out
def menu_item_names(ax, root_id=None): return [el.name or "" for el in visible_menu_items(ax, root_id=root_id)]
def top_menu(ax, name): """The app's own top-level menu ('File'/'Tools'/'Calibration'/'Help').""" for el in visible_menu_items(ax, max_depth=18): if (el.name or "") == name: return el return None
def top_menu_names(ax): """Names of the top-level menu bar items (y near the top of the window).""" win = main_window(ax) top_y = (frame(ax, win.id) or (0, 0, 0, 0))[1] if win else 0 names = [] for el in visible_menu_items(ax, max_depth=18): box = frame(ax, el.id) if box and box[1] <= top_y + 80: names.append(el.name or "") return names
def checkbox_map(ax, root_id=None, max_depth=40, max_results=80): """{checkbox name: bool} — UVtools exposes IsChecked as AXValue.""" out = {} for el in ax.find(role="checkbox", root_id=root_id, max_depth=max_depth, max_results=max_results): name = (el.name or "").strip() if not name: continue val = el.value if isinstance(val, str): val = val.strip().lower() == "true" out[name] = bool(val) return out
def grid_row_list(ax, grid_identifier, max_depth=30): """Read an Avalonia DataGrid as a list of rows, each a list of cell strings.
Cells are AXStaticText; rows are recovered by grouping on the cell's y position and ordering the columns by x. The column-header row is dropped. """ grids = find_by_identifier(ax, grid_identifier, max_depth=max_depth) if not grids: return [] by_y = {} for el in ax.find(role="label", root_id=grids[0].id, max_depth=30, max_results=240): if el.value in (None, ""): continue box = frame(ax, el.id) if not box: continue by_y.setdefault(round(box[1]), []).append((box[0], str(el.value))) rows = [] header = None for y in sorted(by_y): cols = [v for _, v in sorted(by_y[y])] if header is None: header = cols # first (top-most) line is the column header continue if cols == header: continue rows.append(cols) return rows
def grid_rows(ax, grid_identifier, max_depth=30): """Read a two-column Avalonia DataGrid as {first cell: second cell}.""" out = {} for cols in grid_row_list(ax, grid_identifier, max_depth=max_depth): if len(cols) >= 2: out.setdefault(cols[0], cols[1]) return out
def field_for_label(ax, label_text, root_id=None, max_depth=44, tol=14): """The input/output field on the same row as `label_text` (to its right).
UVtools' tool dialogs are label + NumericUpDown grids; the field carries no accessible name, so it is matched geometrically against its row label. """ want = label_text.strip().lower() anchor = None for el in ax.find(role="label", root_id=root_id, max_depth=max_depth, max_results=300): if str(el.value or "").strip().lower() == want: anchor = frame(ax, el.id) if anchor: break if anchor is None: return None a_mid = anchor[1] + anchor[3] / 2.0 best, best_dx = None, 1e9 for el in ax.find(role="text_field", root_id=root_id, max_depth=max_depth, max_results=200): box = frame(ax, el.id) if not box: continue mid = box[1] + box[3] / 2.0 if abs(mid - a_mid) > tol: continue dx = box[0] - anchor[0] if dx > -2 and dx < best_dx: best, best_dx = el, dx return best
def numeric(value): """First number inside a display string ('40.0' -> 40.0, 'Zoom: [ 0.55x ]' -> 0.55).""" if value is None: return None found = re.findall(r"-?\d+(?:\.\d+)?", str(value).replace(",", "")) return float(found[0]) if found else None
def layer_slider(ax): """The vertical layer-navigation slider (AXValue = current layer index).""" got = find_by_identifier(ax, "LayerSlider", role="slider", max_depth=26) return got[0] if got else None
def layer_index(ax): """Current layer index as an int, read from the layer index spin box.""" got = find_by_identifier(ax, "PART_TextBox", role="text_field", max_depth=26) for el in got: box = frame(ax, el.id) if box and box[0] > 1500: # the box under the layer slider val = numeric(el.value) return None if val is None else int(val) return None
def layer_tooltip(ax): """The layer navigation read-out, e.g. '0.100mm\\n0\\n10%'.""" for val in label_values(ax, max_depth=22): if "%" in val and "mm" in val: return val return None
def spinner_buttons(ax, label_text, root_id=None, max_depth=44, tol=16): """(increase, decrease) buttons of the NumericUpDown on `label_text`'s row.""" field = field_for_label(ax, label_text, root_id=root_id, max_depth=max_depth) if field is None: return (None, None) box = frame(ax, field.id) if not box: return (None, None) mid = box[1] + box[3] / 2.0 inc = dec = None for el in ax.find(role="button", root_id=root_id, max_depth=max_depth, max_results=200): ident = identifier(ax, el.id) if ident not in ("PART_IncreaseButton", "PART_DecreaseButton"): continue pos = frame(ax, el.id) if not pos or abs(pos[1] + pos[3] / 2.0 - mid) > tol: continue if ident == "PART_IncreaseButton" and inc is None: inc = el elif ident == "PART_DecreaseButton" and dec is None: dec = el return (inc, dec)
# ---------------------------------------------------------------------------# navigation — rb_enter_* / rb_reach_* names are what the depth audit looks for# ---------------------------------------------------------------------------
def click_menu(ax, element, settle=1.2): """Activate a menu node with a real click.
NB: Avalonia's menu items advertise NO AX actions yet AXUIElementPerformAction still reports success on them, so an AXPress-first strategy silently does nothing. Menus must therefore always be driven by a synthesized click. """ if element is None: return False ok = ax.click_element_cg(getattr(element, "id", element)) time.sleep(settle) return ok
def rb_enter_menu(ax, menu_name, settle=1.2, attempts=3): """Open one of the app's top-level menus. Returns True when its popup is up.""" before = set(menu_item_names(ax)) for _ in range(attempts): menu = top_menu(ax, menu_name) if menu is None: return False click_menu(ax, menu, settle) if len(set(menu_item_names(ax)) - before) > 0: return True return False
# whitelisted alias so either spelling backs the declared depthdef open_menu(ax, menu_name, settle=1.2): return rb_enter_menu(ax, menu_name, settle=settle)
def menu_item(ax, name, exact=True): """A currently visible menu item by name.""" low = name.strip().lower() for el in visible_menu_items(ax): got = (el.name or "").strip().lower() if got == low or (not exact and low in got): return el return None
def rb_enter_menu_item(ax, menu_name, item_name, settle=2.4): """Open `menu_name` then activate `item_name`.""" if not rb_enter_menu(ax, menu_name): return False target = menu_item(ax, item_name) if target is None: press_escape() return False click_menu(ax, target, settle) return True
def rb_enter_submenu(ax, menu_name, submenu_name, settle=1.8): """Open `menu_name` > `submenu_name` and leave the submenu expanded.""" if not rb_enter_menu(ax, menu_name): return False target = menu_item(ax, submenu_name) if target is None: press_escape() return False before = set(menu_item_names(ax)) for _ in range(2): click_menu(ax, target, settle) if len(set(menu_item_names(ax)) - before) > 0: return True target = menu_item(ax, submenu_name) if target is None: return False return False
def rb_enter_dropdown(ax, identifier_name, settle=1.6): """Open one of the layer-preview drop-down buttons ('Actions', 'Outline').""" btns = find_by_identifier(ax, identifier_name, role="button", max_depth=26) if not btns: return False before = set(menu_item_names(ax)) if not ax.action(btns[0].id, "AXPress"): ax.click_element_cg(btns[0].id) time.sleep(settle) return len(set(menu_item_names(ax)) - before) > 0
def open_dialog(ax, menu_name, item_name, title_contains, settle=2.6, timeout=9.0): """menu > item, then wait for the dialog window. Returns the window element/None.""" if not rb_enter_menu_item(ax, menu_name, item_name, settle=settle): return None return rb_enter_window(ax, title_contains, timeout=timeout)
def rb_enter_window(ax, title_contains, timeout=9.0): """Wait for a window whose title contains `title_contains`.""" deadline = time.time() + timeout while time.time() < deadline: win = find_window(ax, title_contains) if win is not None: return win time.sleep(0.4) return None
def rb_enter_tab(ax, tab_identifier, settle=1.4): """Select one of the main window's left-panel tabs by AXIdentifier ('TabInformation'/'TabIssues'/'TabSuggestions'/'TabClipboard').""" tabs = find_by_identifier(ax, tab_identifier, role="radio", max_depth=26) if not tabs: return False ax.click_element_cg(tabs[0].id) time.sleep(settle) got = find_by_identifier(ax, tab_identifier, role="radio", max_depth=26) return bool(got) and is_selected(ax, got[0].id)
def switch_tab(ax, tab_identifier, settle=1.4): return rb_enter_tab(ax, tab_identifier, settle=settle)
def select_tab(ax, tab_name, root_id=None, settle=1.6): """Select a tab by its accessible NAME inside a dialog (Settings/Calculator/About).""" for el in ax.find(role="radio", root_id=root_id, max_depth=34, max_results=40): if (el.name or "").strip().lower() == tab_name.strip().lower(): ax.click_element_cg(el.id) time.sleep(settle) for again in ax.find(role="radio", root_id=root_id, max_depth=34, max_results=40): if (again.name or "").strip().lower() == tab_name.strip().lower(): return is_selected(ax, again.id) return True return False
def close_dialogs(ax, tries=2): """Best effort: press a Cancel/Close button in any secondary window, then Escape.""" for _ in range(tries): secondary = [w for w in ax.find(role="window", max_results=16, max_depth=2) if w.name and not (w.name or "").startswith("UVtools 4")] if not secondary: break for win in secondary: btn = (find_button_by_label(ax, "Cancel", root_id=win.id) or find_button_by_label(ax, "Close", root_id=win.id)) if btn is not None: press_button(ax, btn) time.sleep(0.8) press_escape(1) press_escape(1)
# ---------------------------------------------------------------------------# VLM screenshot assertions# ---------------------------------------------------------------------------
def screenshot_assert(test_name, description, results_dir=None): """Capture the screen and record what a VLM judge should see.""" base = results_dir or os.environ.get("RESULTS_DIR") or "/tmp" ss_dir = os.path.join(base, "screenshots") try: os.makedirs(ss_dir, exist_ok=True) except Exception: return ss_path = os.path.join(ss_dir, f"{test_name}.png") try: subprocess.run(["screencapture", "-x", ss_path], timeout=8) except Exception: pass assertions_file = os.path.join(ss_dir, "assertions.json") data = {} if os.path.exists(assertions_file): try: with open(assertions_file) as fh: data = json.load(fh) except Exception: data = {} data[f"{test_name}.png"] = description try: with open(assertions_file, "w") as fh: json.dump(data, fh, indent=2) except Exception: pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753"""verifier_helpers.py — High-level AX testing patterns for macOS app verification.
v6 core library. Encodes all robust testing patterns as reusable functionsso verifier agents call high-level APIs instead of building from scratch.
Depends on: ax_helpers.py (AXHelper class)"""
import datetimeimport osimport reimport signalimport subprocessimport timefrom collections import Counter
# ---------------------------------------------------------------------------# Key codes (macOS virtual key codes)# ---------------------------------------------------------------------------KC_LEFT_ARROW = 123KC_RIGHT_ARROW = 124KC_UP_ARROW = 126KC_DOWN_ARROW = 125KC_SPACE = 49KC_RETURN = 36KC_TAB = 48KC_ESCAPE = 53KC_Q = 12KC_W = 13
# ---------------------------------------------------------------------------# Bilingual keyword constants# ---------------------------------------------------------------------------
QUIT_KEYWORDS = [ "quit", "exit", "close app", "terminate", "退出", "关闭", "结束",]UPDATE_KEYWORDS = [ "update", "updates", "check for update", "check for updates", "check update", "software update", "更新", "检查更新", "软件更新",]CALENDAR_KEYWORDS = [ "calendar", "calendars", "event", "events", "show calendar", "hide calendar", "toggle calendar", "日历", "事件", "日程",]HOLIDAY_KEYWORDS = [ "holiday", "holidays", "public holiday", "festival", "假日", "节假日", "节日", "假期", "公共假日",]APPEARANCE_KEYWORDS = [ "appearance", "theme", "dark", "light", "system", "dark mode", "light mode", "外观", "主题", "深色", "浅色", "暗色", "亮色",]LOGIN_KEYWORDS = [ "login", "launch at login", "start at login", "open at login", "launch at startup", "start at startup", "auto start", "autostart", "登录时启动", "开机启动", "自动启动", "启动时打开",]ABOUT_KEYWORDS = [ "about", "info", "information", "version", "关于", "版本", "信息",]TODAY_KEYWORDS = [ "today", "go to today", "return to today", "current", "now", "今天", "今日", "当前",]
NAV_PREV_KEYWORDS = [ "prev", "previous", "back", "left", "earlier", "上一", "前一", "上个", "前", "◀", "←", "❮", "◁", "⬅",]NAV_NEXT_KEYWORDS = [ "next", "forward", "right", "later", "下一", "后一", "下个", "后", "▶", "→", "❯", "▷", "➡",]
WEEKDAY_SYMBOLS = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "SU", "MO", "TU", "WE", "TH", "FR", "SA", "Su", "Mo", "Tu", "We", "Th", "Fr", "S", "M", "T", "W", "F", "日", "一", "二", "三", "四", "五", "六",}
MONTH_YEAR_PATTERN = re.compile( r"(" r"[A-Z][a-z]{2,8}\s+\d{4}" r"|\d{4}\s*[年/\-\.]\s*\d{1,2}\s*[月]?" r"|\d{1,2}\s*[月]\s*\d{4}" r"|\d{4}\s*[年]" r"|[A-Z][a-z]{2,8}\s*\d{4}" r")", re.UNICODE,)
LUNAR_KEYWORDS = [ "初", "十", "廿", "卅", "正月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "冬月", "腊月",]
SOLAR_TERM_KEYWORDS = [ "立春", "雨水", "惊蛰", "春分", "清明", "谷雨", "立夏", "小满", "芒种", "夏至", "小暑", "大暑", "立秋", "处暑", "白露", "秋分", "寒露", "霜降", "立冬", "小雪", "大雪", "冬至", "小寒", "大寒",]
# ---------------------------------------------------------------------------# Low-level: Key sending via CGEvent# ---------------------------------------------------------------------------
def send_key(keycode, modifiers=None): """Send a keyboard event via CGEvent API. modifiers: list of "cmd", "shift", "alt", "ctrl".""" import Quartz src = Quartz.CGEventSourceCreate(Quartz.kCGEventSourceStateHIDSystemState) down = Quartz.CGEventCreateKeyboardEvent(src, keycode, True) up = Quartz.CGEventCreateKeyboardEvent(src, keycode, False) flags = 0 if modifiers: flag_map = { "cmd": Quartz.kCGEventFlagMaskCommand, "shift": Quartz.kCGEventFlagMaskShift, "alt": Quartz.kCGEventFlagMaskAlternate, "ctrl": Quartz.kCGEventFlagMaskControl, } for mod in modifiers: flags |= flag_map.get(mod, 0) Quartz.CGEventSetFlags(down, flags) Quartz.CGEventSetFlags(up, flags) Quartz.CGEventPost(Quartz.kCGHIDEventTap, down) Quartz.CGEventPost(Quartz.kCGHIDEventTap, up) time.sleep(0.3)
def click_at(x, y): """Click at absolute screen coordinates via CGEvent.""" import Quartz point = Quartz.CGPointMake(x, y) down = Quartz.CGEventCreateMouseEvent( None, Quartz.kCGEventLeftMouseDown, point, Quartz.kCGMouseButtonLeft) up = Quartz.CGEventCreateMouseEvent( None, Quartz.kCGEventLeftMouseUp, point, Quartz.kCGMouseButtonLeft) Quartz.CGEventPost(Quartz.kCGHIDEventTap, down) time.sleep(0.05) Quartz.CGEventPost(Quartz.kCGHIDEventTap, up) time.sleep(0.3)
# ---------------------------------------------------------------------------# Panel detection: find and manage UI panels/windows# ---------------------------------------------------------------------------
def find_panel_container(ax, min_texts=3, max_depth=12): """Find the app's main panel container.
A popover/sheet is accepted by ROLE alone: a menu-bar / status-item app's freshly-opened popover is often sparse (an empty clipboard list, an empty note, a search field) so requiring >= min_texts wrongly REJECTS it. The generic container roles (window/group/web_area/scroll_area) still require >= min_texts text children to avoid matching window chrome.
Searches to max_depth=12 (was 3). Status-item popovers sit ~7-8 levels deep in the AX tree, so the old depth-3 search SILENTLY MISSED them -> ensure_panel_open()/ensure_ui_visible() returned None -> every reveal- dependent test hit `None.id` -> 0% baseline -> the whole menu-bar app was pruned to 0 and the job failed. (Verified on a live VM: depth-3 missed the popover 3/3 fresh launches; depth-12 + role-accept found it 3/3.) Returns the AXElement or None.""" for role in ("popover", "sheet"): containers = ax.find(role=role, max_results=10, max_depth=max_depth) if containers: return containers[0] for role in ("window", "group", "web_area", "scroll_area"): containers = ax.find(role=role, max_results=10, max_depth=max_depth) for c in containers: texts = ax.find_text_elements(root_id=c.id, max_results=min_texts + 1) if len(texts) >= min_texts: return c return None
def is_panel_visible(ax, min_texts=2): """Check if any panel-like container with content is visible.""" return find_panel_container(ax, min_texts=min_texts) is not None
def ensure_panel_open(ax): """Ensure the app's panel is open. Tries clicking each menu_bar_item. Returns the panel container element, or None if all attempts fail.""" panel = find_panel_container(ax) if panel: return panel
# max_depth=6 (was 3): the status-item / menu-bar-extra item that actually # reveals a status app's popover sits ~depth 4 — DEEPER than the app's own # menu-bar items (Apple/File/Edit at depth 2-3). A depth-3 search returned # only the app menus (whose AXPress opens dropdowns, NOT the popover), so the # status item was never pressed and the popover never opened -> None -> # 0% baseline for every menu-bar app. Widen the net so the status item is # found and pressed. (Verified on a live VM: depth-3 never opened the popover; # depth>=4 did.) mbis = ax.find(role="menu_bar_item", max_results=12, max_depth=6) # Two passes. The old code interleaved a CG click per item: AXPress, and if # that didn't reveal, click_element_cg the SAME item immediately. But a CG # click on an app menu (Apple/File/Edit) opens a blocking dropdown that # POISONS the next press, so the status popover a later AXPress would have # opened was never seen -> None -> 0% baseline for menu-bar apps. # Pass 1: AXPress every item, dismissing any dropdown a miss leaves open. # (Verified on a live VM: AXPress-only opened + detected the popover 3/3; # the interleaved CG click made it fail 3/3.) for mbi in mbis: ax.action(mbi.id, "AXPress") time.sleep(1.0) panel = find_panel_container(ax) if panel: return panel dismiss_menus(ax) # Pass 2: CG-click fallback only if AXPress revealed nothing anywhere. for mbi in mbis: ax.click_element_cg(mbi.id) time.sleep(1.0) panel = find_panel_container(ax) if panel: return panel dismiss_menus(ax)
return None
def dismiss_panel(ax): """Dismiss the panel. Multi-strategy: Escape -> click outside. Returns True if panel was dismissed (or was already closed).""" if not is_panel_visible(ax): return True
send_key(KC_ESCAPE) time.sleep(0.8) if not is_panel_visible(ax): return True
click_at(10, 10) time.sleep(0.8) return not is_panel_visible(ax)
def dismiss_menus(ax): """Dismiss any open menus by pressing Escape twice.""" send_key(KC_ESCAPE) time.sleep(0.3) send_key(KC_ESCAPE) time.sleep(0.3)
# ---------------------------------------------------------------------------# Text extraction: robust methods for getting text from panels# ---------------------------------------------------------------------------
def get_panel_texts(ax, panel=None): """Get all text strings from the panel. Scoped to the target app only. Returns list[str].""" if panel is None: panel = find_panel_container(ax) if panel is None: return [] text_els = ax.find_text_elements(root_id=panel.id, max_results=300) return [el.text for el in text_els if el.text]
def snapshot_panel_text(ax, panel=None): """Counter-based snapshot of panel text, for detecting changes.""" return Counter(get_panel_texts(ax, panel))
def extract_date_numbers(texts): """Extract day-of-month numbers (1-31) from a list of text strings. Handles standalone "7", mixed "7 廿一", "15 初一", etc.""" found = set() for t in texts: s = str(t).strip() if s.isdigit(): n = int(s) if 1 <= n <= 31: found.add(n) continue for m in re.finditer(r'\b(\d{1,2})\b', s): n = int(m.group(1)) if 1 <= n <= 31: found.add(n) m = re.match(r'^(\d{1,2})', s) if m: n = int(m.group(1)) if 1 <= n <= 31: found.add(n) return found
def count_weekday_symbols(texts): """Count how many texts match known weekday symbols.""" return sum(1 for t in texts if str(t).strip() in WEEKDAY_SYMBOLS)
def has_month_year(texts): """Check if any text contains a month/year pattern.""" all_text = " ".join(str(t) for t in texts) return MONTH_YEAR_PATTERN.search(all_text) is not None
# ---------------------------------------------------------------------------# Menu item search: keyword-based with fallback# ---------------------------------------------------------------------------
def find_by_keywords(items, keywords): """Find first item matching any keyword (case-insensitive, partial match).""" for item in items: name_lower = (item.name or "").lower() for kw in keywords: if kw.lower() in name_lower: return item return None
def find_menu_item(ax, keywords): """Search for a menu item by keyword list. First searches role=menu_item, then falls back to all clickable elements.""" items = ax.find(role="menu_item", max_results=100) result = find_by_keywords(items, keywords) if result: return result
clickable = ax.find_clickable(max_results=200) return find_by_keywords(clickable, keywords)
def open_actions_menu(ax): """Open the actions/settings menu and return its menu items. Tries buttons, pop-up buttons, menu buttons, then all clickable elements.""" panel = ensure_panel_open(ax) if panel is None: return []
existing = ax.find(role="menu_item", max_results=5) if len(existing) >= 3: return existing
skip_keywords = ["quit", "close", "exit", "delete", "remove"]
def _try_press(el): ax.action(el.id, "AXPress") time.sleep(0.6) menu_items = ax.find(role="menu_item", max_results=50) if len(menu_items) >= 3: return menu_items ax.click_element_cg(el.id) time.sleep(0.6) menu_items = ax.find(role="menu_item", max_results=50) if len(menu_items) >= 3: return menu_items send_key(KC_ESCAPE) time.sleep(0.3) return None
for role in ("button", "pop_up_button", "menu_button"): elements = ax.find(role=role, root_id=panel.id, max_results=20) for el in elements: name = (el.name or "").lower() if any(kw in name for kw in skip_keywords): continue result = _try_press(el) if result: return result
clickable = ax.find_clickable(root_id=panel.id, max_results=50) for el in clickable: name = (el.name or "").lower() if any(kw in name for kw in skip_keywords): continue if el.role in ("button", "pop_up_button", "menu_button"): continue result = _try_press(el) if result: return result
return ax.find(role="menu_item", max_results=50)
# ---------------------------------------------------------------------------# Month navigation: multi-strategy with fallback# ---------------------------------------------------------------------------
def navigate_month(ax, direction="forward"): """Navigate to the next/previous month. Multi-strategy fallback: 1. Named button (prev/next/arrow keywords) 2. Keyboard arrow key 3. Brute force — try all clickable elements Returns True if panel text changed.""" panel = ensure_panel_open(ax) if panel is None: return False text_before = snapshot_panel_text(ax, panel)
# Strategy 1: named button keywords = NAV_NEXT_KEYWORDS if direction == "forward" else NAV_PREV_KEYWORDS clickable = ax.find_clickable(root_id=panel.id, max_results=50) for el in clickable: name_lower = (el.name or "").lower() if any(kw.lower() in name_lower for kw in keywords): ax.action(el.id, "AXPress") time.sleep(0.6) panel2 = find_panel_container(ax) if panel2: text_after = snapshot_panel_text(ax, panel2) if text_after != text_before: return True ax.click_element_cg(el.id) time.sleep(0.6) panel2 = find_panel_container(ax) if panel2: text_after = snapshot_panel_text(ax, panel2) if text_after != text_before: return True
# Strategy 2: keyboard key_code = KC_RIGHT_ARROW if direction == "forward" else KC_LEFT_ARROW send_key(key_code) time.sleep(0.5) panel2 = find_panel_container(ax) if panel2: text_after = snapshot_panel_text(ax, panel2) if text_after != text_before: return True
# Strategy 3: brute force — try all clickable in panel panel = ensure_panel_open(ax) if panel is None: return False text_before = snapshot_panel_text(ax, panel) buttons = ax.find(role="button", root_id=panel.id, max_results=20) for btn in buttons: name = (btn.name or "").lower() if any(kw in name for kw in ["quit", "close", "exit", "setting", "about"]): continue ax.action(btn.id, "AXPress") time.sleep(0.6) panel2 = find_panel_container(ax) if panel2: text_after = snapshot_panel_text(ax, panel2) if text_after != text_before: return True ax.click_element_cg(btn.id) time.sleep(0.6) panel2 = find_panel_container(ax) if panel2: text_after = snapshot_panel_text(ax, panel2) if text_after != text_before: return True
return False
# ---------------------------------------------------------------------------# Today detection: multi-strategy# ---------------------------------------------------------------------------
def check_today_in_panel(ax, panel=None): """Check if today's date is present in the panel. Multi-strategy: 1. Extract date numbers and check for today 2. Search for "today" keywords in text 3. Check AXSelected/AXDescription attributes""" today = datetime.date.today().day
if panel is None: panel = ensure_panel_open(ax) texts = get_panel_texts(ax, panel)
# Strategy 1: date number extraction numbers = extract_date_numbers(texts) if today in numbers: return True
# Strategy 2: "today" keyword search for t in texts: for kw in TODAY_KEYWORDS: if kw.lower() in str(t).lower(): return True
# Strategy 3: AX attributes if panel: elements = ax.find(root_id=panel.id, max_results=200) for el in elements: attrs = ax.get(el.id, ["AXSelected", "AXDescription"]) if attrs.get("AXSelected"): return True desc = str(attrs.get("AXDescription", "")) if re.search(r"\btoday\b|今天|今日", desc, re.IGNORECASE): return True if str(today) in desc: return True
return False
# ---------------------------------------------------------------------------# Application lifecycle# ---------------------------------------------------------------------------
def quit_app_via_menu(ax): """Try to quit the app via menu item. Returns True if quit item found and clicked.""" items = open_actions_menu(ax) quit_item = find_by_keywords(items, QUIT_KEYWORDS) if quit_item: ax.action(quit_item.id, "AXPress") time.sleep(1.0) return True return False
def quit_app_via_shortcut(pid): """Quit app via Cmd+Q. Returns True if process terminated.""" send_key(KC_Q, modifiers=["cmd"]) time.sleep(1.5) try: os.kill(pid, 0) return False except ProcessLookupError: return True
def is_process_running(pid): """Check if a process is still running.""" try: os.kill(pid, 0) return True except ProcessLookupError: return False
# ---------------------------------------------------------------------------# Screenshot capture# ---------------------------------------------------------------------------
def take_screenshot(save_path, region=None): """Take a screenshot and save to save_path. region: optional (x, y, w, h) tuple for partial capture. Returns the save_path on success, None on failure.""" os.makedirs(os.path.dirname(os.path.abspath(save_path)), exist_ok=True) cmd = ["screencapture", "-x"] if region: x, y, w, h = region cmd.extend(["-R", f"{x},{y},{w},{h}"]) cmd.append(save_path) try: subprocess.run(cmd, timeout=10, check=True, capture_output=True, text=True) if os.path.exists(save_path) and os.path.getsize(save_path) > 0: return save_path except (subprocess.SubprocessError, OSError): pass return None
def take_screenshot_of_panel(ax, save_path): """Take a fullscreen screenshot. Uses fullscreen to stay consistent with official screenshots captured by the App Explorer (CU-based).""" return take_screenshot(save_path)
# ---------------------------------------------------------------------------# VLM screenshot comparison (Claude Vision API)# ---------------------------------------------------------------------------
def _load_image_base64(path): """Load image file as base64 string.""" import base64 with open(path, "rb") as f: return base64.b64encode(f.read()).decode("utf-8")
def _get_media_type(path): """Infer media type from file extension.""" ext = os.path.splitext(path)[1].lower() return {"png": "image/png", "jpg": "image/jpeg", "jpeg": "image/jpeg", "gif": "image/gif", "webp": "image/webp"}.get(ext.lstrip("."), "image/png")
def compare_screenshots_vlm(official_path, recreated_path, aspect, model=None, api_key=None, base_url=None): """Compare two screenshots using VLM via OpenAI-compatible API.
Args: official_path: path to the official app screenshot (ground truth) recreated_path: path to the recreated app screenshot aspect: what visual aspect to compare model: VLM model name (default: env VLM_MODEL) api_key: API key (default: env VLM_API_KEY) base_url: API base URL (default: env VLM_BASE_URL)
Returns: dict with keys: score (int 1-10), reason (str) """ import json try: import urllib.request import urllib.error except ImportError: return {"score": 1, "reason": "urllib not available"}
if not os.path.exists(official_path): return {"score": 1, "reason": f"Official screenshot not found: {official_path}"} if not os.path.exists(recreated_path): return {"score": 1, "reason": f"Recreated screenshot not found: {recreated_path}"}
model = model or os.environ.get("VLM_MODEL", "qwen-vl-max") api_key = api_key or os.environ.get("VLM_API_KEY") \ or os.environ.get("OPENAI_API_KEY") \ or os.environ.get("ANTHROPIC_API_KEY") base_url = base_url or os.environ.get("VLM_BASE_URL") \ or os.environ.get("OPENAI_BASE_URL") \ or "https://dashscope.aliyuncs.com/compatible-mode/v1"
if not api_key: return {"score": 1, "reason": "No API key found (set VLM_API_KEY)"}
base_url = base_url.rstrip("/")
official_b64 = _load_image_base64(official_path) recreated_b64 = _load_image_base64(recreated_path) official_mime = _get_media_type(official_path) recreated_mime = _get_media_type(recreated_path)
prompt = f"""You are a visual QA judge comparing two macOS app screenshots.
Image 1 (OFFICIAL): The reference/ground-truth screenshot of the original app.Image 2 (RECREATED): A screenshot of a recreated version of the same app.
Visual aspect to evaluate: {aspect}
Compare the two screenshots and rate how faithfully the recreated app reproduces the visual aspect described above.
Focus on:- Layout and positioning of UI elements- Text content and formatting- Colors, icons, and visual styling- Overall visual similarity for the specified aspect
Rate on a scale of 1-10: 1-2: Completely different, no resemblance 3-4: Major differences, some elements recognizable 5-6: Moderate similarity, layout roughly correct but notable differences 7-8: Good reproduction, minor visual differences 9-10: Near-perfect match, only trivial differences (antialiasing, font rendering)
Be lenient on minor pixel differences, font rendering, and antialiasing — focus on functional visual equivalence.
Respond in EXACTLY this JSON format (no other text):{{"score": <integer 1-10>, "reason": "one sentence explanation"}}"""
payload = { "model": model, "messages": [{ "role": "user", "content": [ {"type": "image_url", "image_url": { "url": f"data:{official_mime};base64,{official_b64}"}}, {"type": "image_url", "image_url": { "url": f"data:{recreated_mime};base64,{recreated_b64}"}}, {"type": "text", "text": prompt} ] }], "temperature": 0, "max_tokens": 256, }
headers = { "Content-Type": "application/json", "Authorization": f"Bearer {api_key}", }
import time as _time max_retries = 12 last_err = None
for attempt in range(max_retries): try: req = urllib.request.Request( f"{base_url}/chat/completions", data=json.dumps(payload).encode("utf-8"), headers=headers, method="POST") with urllib.request.urlopen(req, timeout=120) as resp: body = json.loads(resp.read().decode("utf-8"))
text = body["choices"][0]["message"]["content"].strip()
json_match = re.search(r'\{[^{}]*"score"[^{}]*\}', text) if json_match: result = json.loads(json_match.group()) score = int(result.get("score", 1)) score = max(1, min(10, score)) result["score"] = score result.setdefault("reason", "") return result
return {"score": 1, "reason": f"Could not parse VLM response: {text[:200]}"}
except urllib.error.HTTPError as e: last_err = f"HTTP {e.code}: {e.read().decode('utf-8', errors='replace')[:200]}" if e.code == 429: delay = 3 else: delay = 10 if attempt < max_retries - 1: _time.sleep(delay) continue except (urllib.error.URLError, json.JSONDecodeError, OSError) as e: last_err = str(e) if attempt < max_retries - 1: _time.sleep(10) continue
return {"score": 1, "reason": f"VLM API error after {max_retries} attempts: {last_err}"}
def assert_screenshot_match(ax, official_screenshot_path, aspect, save_dir="/tmp/verifier_screenshots"): """High-level helper: take screenshot of current app panel, compare with official. Raises AssertionError if VLM judges the screenshots don't match.""" import time as _time _time.sleep(1.0) os.makedirs(save_dir, exist_ok=True) basename = os.path.basename(official_screenshot_path) recreated_path = os.path.join(save_dir, f"recreated_{basename}")
result = take_screenshot_of_panel(ax, recreated_path) assert result is not None, "Failed to take screenshot of recreated app"
comparison = compare_screenshots_vlm(official_screenshot_path, recreated_path, aspect) score = comparison.get("score", 1) assert score >= 7, ( f"Screenshot mismatch for '{aspect}': {comparison.get('reason', '')} " f"(score={score}/10)" )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205{ "schema_version": 2, "instance_id": "macos/sn4k3-uvtools", "grading": { "mode": "deferred", "model": null, "scored_separately": true }, "totals": { "assertions": 14, "with_verdict": 0, "calibrated": 0, "usable": null, "scored_records": 0, "unbacked_records": 0 }, "assertions": [ { "id": "button_test_thumbnail_next_selects_second_thumbnail.png", "screenshot": "button_test_thumbnail_next_selects_second_thumbnail.png", "assertion": "UVtools main window, Information tab: the thumbnail selector at the top of the narrow left panel now reads '2/2' with the left (previous) arrow enabled and the right (next) arrow greyed out; the label beside it reads '{Width: 800, Height: 480}' and the image below it is the WIDER second thumbnail (800x480 landscape preview of the sliced model) instead of the square 400x400 one. Below it the 'Properties: 154 | Groups: 4' line and the Properties/Layer-data tables are unchanged, and the big black layer preview on the right still shows the white UVtools logo slice.", "form": "statement", "expected": true, "aspect": null, "modality": null, "links_to": "button_test_thumbnail_next_selects_second_thumbnail.png", "rigor": null, "verdict": null, "calibration": null }, { "id": "button_test_lb_button_selects_layer_nine.png", "screenshot": "button_test_lb_button_selects_layer_nine.png", "assertion": "UVtools main window after pressing the 'LB' button at the bottom of the right-hand layer column: layer 9 (the last/top layer) is selected — the vertical layer slider handle on the right edge sits at the TOP of its track, the read-out beside the handle shows '1.000mm', '9' and '100%', the small index box under the slider reads 9, and the black preview canvas shows the topmost slice of the model. The bottom-left read-out under the canvas reads 'Pixels: 568399 (13.71%)' / 'Volume: 142.10mm3'.", "form": "statement", "expected": true, "aspect": null, "modality": null, "links_to": "button_test_lb_button_selects_layer_nine.png", "rigor": null, "verdict": null, "calibration": null }, { "id": "computation_test_calculator_mm_to_pixels.png", "screenshot": "computation_test_calculator_mm_to_pixels.png", "assertion": "The UVtools 'Calculator' dialog is open in front of the main window on its 'Millimeters to pixels' tab, which shows 'Converts from Millimeters to Pixels' and 'Formula: Pixels = Resolution / Display * Millimeters'. The numeric rows read Resolution X: 1620, Resolution Y: 2560, Display width: 81.00, Display height: 128.00 and Input millimeters: 2.00 (after two 0.5 mm spinner increments from 1.00). The derived rows read X pixels per millimeter: 20 and Y pixels per millimeter: 20, and the computed outputs read X Pixels: 40.0 and Y Pixels: 40.0. A Cancel button sits at the bottom of the dialog.", "form": "statement", "expected": true, "aspect": null, "modality": null, "links_to": "computation_test_calculator_mm_to_pixels.png", "rigor": null, "verdict": null, "calibration": null }, { "id": "computation_test_calculator_optimal_tilt.png", "screenshot": "computation_test_calculator_optimal_tilt.png", "assertion": "The UVtools 'Calculator' dialog is open with its SECOND tab, 'Optimal model tilt', now selected (the 'Millimeters to pixels' tab is no longer the selected one). The panel shows the description 'Calculates the optimal model tilt angle for printing and to minimize the visual layer effect.' followed by the line 'Formula: Angle = arctan(Layer height / XYResolution) * (180 / PI)'. Rows labelled 'Layer height:' (showing 0.100), 'XY resolution:' and 'Optimal tilt angle:' are visible; on this build the two computed output rows display a System.InvalidCastException message instead of a number. A Cancel button sits at the bottom of the dialog.", "form": "statement", "expected": true, "aspect": null, "modality": null, "links_to": "computation_test_calculator_optimal_tilt.png", "rigor": null, "verdict": null, "calibration": null }, { "id": "menu_test_file_menu.png", "screenshot": "menu_test_file_menu.png", "assertion": "UVtools main window with the File drop-down open under the 'File' title of the in-window menu bar (File Tools Calibration Help, top-left). The menu lists, with icons: Open, Open in new window, Open recent, Open in partial mode, Reload, Save (greyed out/disabled), Save as, Rename, Convert to (with a submenu arrow), Close, Reset layers properties (greyed out), I printed this file, Open containing folder, Extract file contents, Copy parameters to files, Terminal, Fullscreen, Settings, Exit. Behind it: the black layer-preview canvas with the white UVtools logo slice.", "form": "statement", "expected": true, "aspect": null, "modality": null, "links_to": "menu_test_file_menu.png", "rigor": null, "verdict": null, "calibration": null }, { "id": "menu_test_convert_to_submenu.png", "screenshot": "menu_test_convert_to_submenu.png", "assertion": "UVtools with the File menu open AND its 'Convert to' entry expanded into a second-level submenu displayed beside the File drop-down. The submenu lists printer / file-format targets: Prusa, Chitubox, Anycubic Photon Workshop, CWS, Anet, Longer3D, Voxeldance, CXDLP, NanoDLP, Klipper, Elegoo GOO, Phrozen Sonic Mini 8K S (PRZ), UnizMaker IBEE (ZCode), Z-Suite ZCodex, GR1 Workshop, Flashforge SVGX, Vendor-neutral format (UVJ), Generic Zip / Phrozen Zip and more.", "form": "statement", "expected": true, "aspect": null, "modality": null, "links_to": "menu_test_convert_to_submenu.png", "rigor": null, "verdict": null, "calibration": null }, { "id": "menu_test_about_dialog.png", "screenshot": "menu_test_about_dialog.png", "assertion": "The 'About UVtools v4.4.2' window is open in front of the main window: it shows the UVtools logo, the app name and version '4.4.2 X64', the AGPL licence line and 'Copyright 2020-2026 PTRTECH' / author 'Tiago Conceicao', a Terms of Use link, a Description / OpenCV / Assemblies tab strip, a table of system fields (Operative System, Processor, Processor cores, Memory RAM, Runtime, OpenCV, Framework, AvaloniaUI) and 'Copy information' + 'Close' buttons at the bottom.", "form": "statement", "expected": true, "aspect": null, "modality": null, "links_to": "menu_test_about_dialog.png", "rigor": null, "verdict": null, "calibration": null }, { "id": "state_test_pixel_editor_enabled.png", "screenshot": "state_test_pixel_editor_enabled.png", "assertion": "Pixel editor mode is ON: the 'Pixel editor' button in the toolbar above the black layer-preview canvas is pressed/highlighted (toggled on), and a 5th icon tab has appeared in the narrow left-hand tab strip and is selected, showing the pixel editor panel with its row of drawing sub-tabs instead of the thumbnail/property tables.", "form": "statement", "expected": true, "aspect": null, "modality": null, "links_to": "state_test_pixel_editor_enabled.png", "rigor": null, "verdict": null, "calibration": null }, { "id": "state_test_settings_general_page.png", "screenshot": "state_test_settings_general_page.png", "assertion": "The 'UVtools - Settings' window is open on top of the main window, showing the General category page: the left column lists the categories General (selected/highlighted), Layer preview, Issues, Pixel editor, Layer repair, Tools, Automations, Network. The General page shows a 'Startup' section whose check boxes 'Start maximized', 'Check for updates on startup' and 'Loads a demo file on startup if no file was specified' are TICKED, while 'Restore window last position', 'Restore window last size' and 'Loads the last recent file on startup if no file was specified' are UNTICKED.", "form": "statement", "expected": true, "aspect": null, "modality": null, "links_to": "state_test_settings_general_page.png", "rigor": null, "verdict": null, "calibration": null }, { "id": "structure_test_main_window.png", "screenshot": "structure_test_main_window.png", "assertion": "The UVtools main window, maximized. Top-left: a menu bar with exactly four menus - File, Tools, Calibration, Help. Left: a narrow panel with 4 small icon tabs, a square thumbnail image of the sliced model, a '1/2' thumbnail index with prev/next arrows, and two property tables with Name/Value/Group columns under a 'Layer data' heading. Centre: a large black layer-preview canvas showing the white 'UVtools' logo slice, with a row of buttons above it. Right edge: a vertical layer slider with a numeric layer box and SB/LB/SN/LN buttons beneath. Bottom: a one-line status bar reading 'Layers: 10 @ 0.1mm', 'Bottom layers: 10/1mm', 'Exposure: 20/3s', 'Print time: 09m', 'Used material', 'Material cost', 'Material: ERYONE Water Washable Grey @0.10' and 'Machine: UVtools Prusa SL1S SPEED'. The title bar reads 'UVtools 4.4.2 X64 File: UVtools_demo_file.sl1s (493.06 KB) ...'.", "form": "statement", "expected": true, "aspect": null, "modality": null, "links_to": "structure_test_main_window.png", "rigor": null, "verdict": null, "calibration": null }, { "id": "structure_test_file_menu_open.png", "screenshot": "structure_test_file_menu_open.png", "assertion": "The File drop-down menu is open directly under the 'File' entry at the top left of the UVtools window. It lists, with small icons: Open, Open in new window, Open recent, Open in partial mode, Reload, Save (greyed out), Save as, Rename, Convert to, Close, Reset layers properties (greyed out), I printed this file, Open containing folder, Extract file contents, Copy parameters to files, Terminal, Fullscreen, Settings, Exit. The main window with its black layer preview, right-hand layer slider and bottom status bar is still visible behind the open menu.", "form": "statement", "expected": true, "aspect": null, "modality": null, "links_to": "structure_test_file_menu_open.png", "rigor": null, "verdict": null, "calibration": null }, { "id": "structure_test_settings_dialog.png", "screenshot": "structure_test_settings_dialog.png", "assertion": "A separate window titled 'UVtools - Settings' is in front of the main UVtools window. It shows a strip/list of 8 category tabs - General, Layer preview, Issues, Pixel editor, Layer repair, Tools, Automations, Network - with General selected, and a scrollable General page of grouped check boxes under headings such as Startup, Tasks and Windows / dialogs ('Start maximized' ticked, 'Check for updates on startup' ticked, 'Loads a demo file on startup if no file was specified' ticked). Parts of the main window - the black layer preview and the bottom status bar - remain visible behind the dialog.", "form": "statement", "expected": true, "aspect": null, "modality": null, "links_to": "structure_test_settings_dialog.png", "rigor": null, "verdict": null, "calibration": null }, { "id": "text_test_issues_tab_table.png", "screenshot": "text_test_issues_tab_table.png", "assertion": "UVtools main window with the Issues tab selected in the narrow left panel. The panel shows an issues table with the column headers Type / Layer(s) / Area and exactly two rows, both of type 'SuctionCup', both spanning layers '0-9 (10)', with areas '291,816' and '291,802'. Above the table there is a 'Detect' button and a counter reading '0/2'. To the right the large black layer-preview canvas still shows the white UVtools logo slice, and the bottom status bar keeps showing 'Layers: 10 @ 0.1mm ... Machine: UVtools Prusa SL1S SPEED'.", "form": "statement", "expected": true, "aspect": null, "modality": null, "links_to": "text_test_issues_tab_table.png", "rigor": null, "verdict": null, "calibration": null }, { "id": "text_test_about_dialog.png", "screenshot": "text_test_about_dialog.png", "assertion": "The 'About UVtools v4.4.2' window is in front of the UVtools main window. It shows the UVtools logo and name, the version '4.4.2 X64', 'Copyright 2020-2026 © PTRTECH', the licence line 'GNU Affero General Public License v3.0 (AGPL)' next to 'Terms of Use', the author 'Tiago Conceição' and an 'Age:' line. A Description / OpenCV / Assemblies tab strip sits in the middle with Description selected, listing system rows labelled 'Operative System:', 'Processor:', 'Processor cores:', 'Memory RAM:', 'Runtime:', 'OpenCV:', 'Framework:', 'AvaloniaUI:' (their values are machine specific). 'Copy information' and 'Close' buttons are at the bottom.", "form": "statement", "expected": true, "aspect": null, "modality": null, "links_to": "text_test_about_dialog.png", "rigor": null, "verdict": null, "calibration": null } ], "merged_from_files": 6, "source_shapes": { "dict_str": 14 }}123456789101112131415161718192021MIT License
Copyright (c) 2020 Alexander Sokolov
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.12345678910{ "schema_version": 1, "instance_id": "macos/sokoloffa-radiola", "platform": "macos", "repo": "https://github.com/SokoloffA/radiola", "commit": "3321ca281afc222544b7e67e64f64f7f13051925", "patches": [], "package": null, "license": null}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102#!/usr/bin/env bash## build.sh — reproducible build for Radiola (macOS menu-bar Internet radio player)## Self-contained: on a fresh `git clone` into which only build.sh and launch.sh# are copied, `bash build.sh` produces Radiola.app.## Build system : Xcode project (Radiola.xcodeproj, scheme "Radiola")# Dependencies : Xcode toolchain (pre-installed) + Sparkle Swift package# (declared in the .xcodeproj, fetched automatically by xcodebuild).# No Homebrew / CocoaPods / npm / pip packages are required.#set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"cd "$SCRIPT_DIR"
PROJECT="Radiola.xcodeproj"SCHEME="Radiola"CONFIGURATION="Release"DERIVED_DATA="$SCRIPT_DIR/DerivedData"APP_NAME="Radiola.app"OUT_DIR="${APP_OUTPUT_DIR:-$SCRIPT_DIR}"
echo "==> Radiola build"echo " SCRIPT_DIR = $SCRIPT_DIR"echo " OUT_DIR = $OUT_DIR"
# ---------------------------------------------------------------------------# 1. Dependencies# ---------------------------------------------------------------------------# The only build dependency is the Xcode command-line toolchain, which ships# with macOS/Xcode. The Sparkle framework is a Swift Package dependency wired# into the .xcodeproj and is resolved/downloaded automatically by xcodebuild.# There are no brew/pod/npm/pip packages to install for this project.## Verify the toolchain is present (idempotent, no-op if already available).if ! xcodebuild -version >/dev/null 2>&1; then echo "ERROR: xcodebuild not found. Install Xcode and run:" >&2 echo " sudo xcode-select -s /Applications/Xcode.app/Contents/Developer" >&2 exit 1fixcodebuild -version
# Resolve the Sparkle Swift package explicitly (idempotent — cached in# DerivedData on subsequent runs). Requires network access on the first run.echo "==> Resolving Swift package dependencies (Sparkle)"xcodebuild \ -project "$PROJECT" \ -scheme "$SCHEME" \ -derivedDataPath "$DERIVED_DATA" \ -resolvePackageDependencies
# ---------------------------------------------------------------------------# 2. Source patches# ---------------------------------------------------------------------------# None required — the project compiles as-is with the Swift 5.10 toolchain# (project targets SWIFT_VERSION = 5.0, MACOSX_DEPLOYMENT_TARGET = 11.0).# If a patch were needed it would be applied here as an inline `git apply`.
# ---------------------------------------------------------------------------# 3. Build (code signing disabled, as required for CI/reproducible builds)# ---------------------------------------------------------------------------echo "==> Building $SCHEME ($CONFIGURATION)"xcodebuild \ -project "$PROJECT" \ -scheme "$SCHEME" \ -configuration "$CONFIGURATION" \ -derivedDataPath "$DERIVED_DATA" \ CODE_SIGN_IDENTITY="" \ CODE_SIGNING_ALLOWED=NO \ CODE_SIGNING_REQUIRED=NO \ build
BUILT_APP="$DERIVED_DATA/Build/Products/$CONFIGURATION/$APP_NAME"if [[ ! -d "$BUILT_APP" ]]; then echo "ERROR: expected app not found at $BUILT_APP" >&2 exit 1fi
# ---------------------------------------------------------------------------# 4. Ad-hoc code signature# ---------------------------------------------------------------------------# The build above is unsigned. An ad-hoc signature (identity "-") lets the# bundle launch on both Intel and Apple Silicon without a developer identity.echo "==> Ad-hoc signing $APP_NAME"codesign --force --deep --sign - "$BUILT_APP"
# ---------------------------------------------------------------------------# 5. Copy final .app to the output directory# ---------------------------------------------------------------------------mkdir -p "$OUT_DIR"if [[ "$(cd "$OUT_DIR" && pwd)" != "$DERIVED_DATA/Build/Products/$CONFIGURATION" ]]; then rm -rf "$OUT_DIR/$APP_NAME" cp -R "$BUILT_APP" "$OUT_DIR/"fi
FINAL_APP="$OUT_DIR/$APP_NAME"echo ""echo "==> BUILD SUCCEEDED"echo " App: $FINAL_APP"file "$FINAL_APP/Contents/MacOS/Radiola" | sed 's/^/ /'123456789101112131415161718192021222324252627282930313233343536373839404142434445464748#!/usr/bin/env bash## launch.sh — start Radiola (a macOS status-bar / menu-bar app).## Radiola has LSBackgroundOnly=true: it shows an icon in the system status bar# (top-right menu bar) rather than a dock icon or a main window.## The .app bundle is self-contained — Sparkle.framework and the Swift runtime# libraries are embedded under Contents/Frameworks with an @executable_path# rpath, so no DYLD_* / framework-path environment variables are required.#set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"APP_NAME="Radiola.app"
# Resolve the app bundle, checking the likely locations in order.CANDIDATES=( "${APP_OUTPUT_DIR:-}/$APP_NAME" "$SCRIPT_DIR/$APP_NAME" "$SCRIPT_DIR/DerivedData/Build/Products/Release/$APP_NAME")
APP_PATH=""for c in "${CANDIDATES[@]}"; do [[ -n "$c" && -d "$c" ]] || continue APP_PATH="$(cd "$c" && pwd)" breakdone
if [[ -z "$APP_PATH" ]]; then echo "ERROR: could not find $APP_NAME. Run build.sh first." >&2 echo "Looked in:" >&2 printf ' %s\n' "${CANDIDATES[@]}" >&2 exit 1fi
echo "Launching $APP_PATH"
# Launch the GUI app. `open` returns as soon as the app is started; the app# then keeps running in the status bar. Any extra arguments are passed through.if [[ "$#" -gt 0 ]]; then open "$APP_PATH" --args "$@"else open "$APP_PATH"fi
echo "Radiola started — look for its icon in the macOS status bar (menu bar)."123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849import osimport reimport timeimport warningsimport subprocessfrom dataclasses import dataclass, fieldfrom typing import Optionalfrom collections import Counter, deque
from ApplicationServices import ( AXUIElementCreateApplication, AXUIElementCreateSystemWide, AXUIElementCopyAttributeNames, AXUIElementCopyAttributeValue, AXUIElementGetAttributeValueCount, AXUIElementCopyAttributeValues, AXUIElementIsAttributeSettable, AXUIElementSetAttributeValue, AXUIElementCopyMultipleAttributeValues, AXUIElementCopyParameterizedAttributeNames, AXUIElementCopyParameterizedAttributeValue, AXUIElementCopyActionNames, AXUIElementCopyActionDescription, AXUIElementPerformAction, AXUIElementCopyElementAtPosition, AXUIElementGetPid, AXUIElementSetMessagingTimeout, kAXValueCGPointType, kAXValueCGSizeType, AXValueGetValue,)import Quartz
ROLE_MAP = { "AXButton": "button", "AXStaticText": "label", "AXTextField": "text_field", "AXTextArea": "text_area", "AXCheckBox": "checkbox", "AXRadioButton": "radio", "AXPopUpButton": "popup", "AXComboBox": "combobox", "AXSlider": "slider", "AXImage": "image", "AXGroup": "group", "AXList": "list", "AXTable": "table", "AXGrid": "grid", "AXCell": "cell", "AXRow": "row", "AXColumn": "column", "AXOutline": "outline", "AXToolbar": "toolbar", "AXTabGroup": "tab_group", "AXTab": "tab", "AXScrollArea": "scroll_area", "AXScrollBar": "scroll_bar", "AXWindow": "window", "AXSheet": "sheet", "AXDialog": "dialog", "AXPopover": "popover", "AXMenu": "menu", "AXMenuBar": "menu_bar", "AXMenuBarItem": "menu_bar_item", "AXMenuItem": "menu_item", "AXSplitGroup": "split_group", "AXSplitter": "splitter", "AXProgressIndicator": "progress", "AXBusyIndicator": "busy", "AXValueIndicator": "value_indicator", "AXLink": "link", "AXDisclosureTriangle": "disclosure",}
@dataclassclass AXElement: id: str role: str name: Optional[str] = None value: Optional[str] = None text: Optional[str] = None enabled: bool = True actions: list = field(default_factory=list) ref: object = field(default=None, repr=False)
_DYNAMIC_TEXT_PATTERNS = [ re.compile(r"^\d{1,2}:\d{2}(:\d{2})?(\s*[AP]M)?$"), re.compile(r"^\d{4}-\d{2}-\d{2}"), re.compile(r"^\d{1,2}/\d{1,2}/\d{2,4}$"),]
def _bundle_for_pid(pid): """Best-effort .app bundle path for a running pid (via its executable path).""" try: out = subprocess.run( ["ps", "-o", "comm=", "-p", str(int(pid))], capture_output=True, text=True, ).stdout.strip() except Exception: return "" marker = "/Contents/MacOS/" return out.split(marker)[0] if marker in out else ""
def is_electron_app(pid): """True if the app for `pid` is a Chromium-based app (Electron or CEF) whose web content AX tree stays empty unless launched with --force-renderer-accessibility. Detected by the presence of the Electron/CEF framework — precise, and does NOT false-positive on a native app that merely bundles a "* Helper.app" (XPC helper).""" bundle = _bundle_for_pid(pid) if not bundle: return False fw = bundle + "/Contents/Frameworks" return (os.path.isdir(fw + "/Electron Framework.framework") or os.path.isdir(fw + "/Chromium Embedded Framework.framework"))
def wait_for_web_ax(pid, timeout=8.0): """For Electron apps launched with --force-renderer-accessibility, the Chromium AXWebArea appears a few seconds after launch (async). Poll until it shows up so a read right after launch doesn't capture an empty window. Fast no-op for non-Electron apps (native/Gecko already expose AX). Best-effort; returns True when settled or when the app isn't Electron.""" try: if not is_electron_app(pid): return True app = AXUIElementCreateApplication(int(pid)) except Exception: return True try: AXUIElementSetMessagingTimeout(app, 5.0) except Exception: pass deadline = time.time() + timeout while time.time() < deadline: dq = deque([app]) seen = 0 while dq and seen < 8000: el = dq.popleft() seen += 1 err, role = AXUIElementCopyAttributeValue(el, "AXRole", None) if err == 0 and str(role) == "AXWebArea": return True # Chromium web content is built err, kids = AXUIElementCopyAttributeValue(el, "AXChildren", None) if err == 0 and kids: for k in kids: dq.append(k) time.sleep(0.5) return True
class AXHelper: def __init__(self, app_name_or_pid, wait_for_ready=True, ready_timeout=10, prime=True): if isinstance(app_name_or_pid, int): self._pid = app_name_or_pid else: self._pid = self._find_pid_by_name(app_name_or_pid) self._app_ref = AXUIElementCreateApplication(self._pid) self._element_cache = {}
# Electron apps launched with --force-renderer-accessibility build their # Chromium AXWebArea a few seconds after launch (async). Wait for it here so # the first real read sees full web content, not an empty window. Runs even # when wait_for_ready=False (e.g. the pytest `ax` fixture). Fast no-op for # non-Electron apps (native/Gecko already expose AX). if prime: wait_for_web_ax(self._pid)
if wait_for_ready: self._wait_until_ready(ready_timeout)
def _wait_until_ready(self, timeout): deadline = time.time() + timeout while time.time() < deadline: try: err, role = AXUIElementCopyAttributeValue(self._app_ref, "AXRole", None) if err == 0 and role: err, children = AXUIElementCopyAttributeValue( self._app_ref, "AXChildren", None ) if err == 0 and children and len(children) > 0: return except Exception: pass time.sleep(0.3) warnings.warn(f"AX tree for PID {self._pid} not ready after {timeout}s")
def _find_pid_by_name(self, name): search_name = name[:15] result = subprocess.run( ["pgrep", "-x", search_name], capture_output=True, text=True ) if result.returncode != 0: result = subprocess.run( ["pgrep", "-f", search_name], capture_output=True, text=True ) if result.returncode != 0: raise RuntimeError(f"Process '{name}' not found") return int(result.stdout.strip().split("\n")[0])
# ── Core API ──
def find( self, role=None, name=None, name_contains=None, value=None, enabled=None, max_results=50, root_id=None, max_depth=None, ): root_ref = self._get_ref(root_id) if root_id else self._app_ref results = []
def _recurse(ref, depth): if max_depth is not None and depth > max_depth: return if len(results) >= max_results: return el = self._ref_to_element(ref) if self._matches(el, role, name, name_contains, value, enabled): results.append(el) err, children = AXUIElementCopyAttributeValue(ref, "AXChildren", None) if err == 0 and children: for child in children: _recurse(child, depth + 1) if len(results) >= max_results: return
_recurse(root_ref, 0) return results
def action(self, element_id, action_name): ref = self._get_ref(element_id) if ref is None: return False try: err = AXUIElementPerformAction(ref, action_name) return err == 0 except Exception: return False
def action_checked(self, element_id, action_name): success = self.action(element_id, action_name) if not success: warnings.warn(f"Action '{action_name}' failed on {element_id}") return success
def click_element_cg(self, element_id): """Simulate a real mouse click at the element's screen position using CGEvent.
Use this when AXPress doesn't work — e.g. menu bar apps that use NSEvent.addLocalMonitorForEvents instead of button target-action. """ ref = self._get_ref(element_id) if ref is None: return False center = self._get_element_center(ref) if center is None: return False point = Quartz.CGPointMake(center[0], center[1]) event_down = Quartz.CGEventCreateMouseEvent( None, Quartz.kCGEventLeftMouseDown, point, Quartz.kCGMouseButtonLeft ) Quartz.CGEventPost(Quartz.kCGHIDEventTap, event_down) time.sleep(0.05) event_up = Quartz.CGEventCreateMouseEvent( None, Quartz.kCGEventLeftMouseUp, point, Quartz.kCGMouseButtonLeft ) Quartz.CGEventPost(Quartz.kCGHIDEventTap, event_up) return True
def get(self, element_id, attributes): # element_id=None 表示 APPLICATION 元素,与 find(root_id=None)/attribute_names(None) 一致。 # 否则 ax.get(None, ["AXTitle"]) 走不进元素缓存、返回 {},读 app 自身标题的 test 拿到 None。 ref = self._get_ref(element_id) if element_id else self._app_ref if ref is None: return {} result = {} for attr in attributes: try: err, val = AXUIElementCopyAttributeValue(ref, attr, None) if err == 0: result[attr] = self._serialize_value(val) else: result[attr] = None except Exception: result[attr] = None return result
def activate(self): """把本 helper 绑定的 app 提到前台,返回是否成功。
有些 toolkit 只在进程被 ACTIVATED 时才装原生菜单栏:olive(Qt)启动后 90s 仍只有 ['Apple','Olive'];zotero(Gecko/XUL)一直只有 ['Apple','Zotero','File','Window'], 且搜索框会吞掉合成键。一次激活即补齐。用 AX API 设 AXFrontmost 会返回成功但无效, 所以走 NSRunningApplication。 """ try: from AppKit import NSRunningApplication except Exception: return False try: app = NSRunningApplication.runningApplicationWithProcessIdentifier_(int(self._pid)) if app is None: return False return bool(app.activateWithOptions_(1 << 1)) # IgnoringOtherApps except Exception: return False
def set_value(self, element_id, value): ref = self._get_ref(element_id) if ref is None: return False try: err = AXUIElementSetAttributeValue(ref, "AXValue", value) return err == 0 except Exception: return False
# ── Attribute Introspection ──
def attribute_names(self, element_id=None): ref = self._get_ref(element_id) if element_id else self._app_ref if ref is None: return [] try: err, names = AXUIElementCopyAttributeNames(ref, None) if err == 0 and names: return list(names) except Exception: pass return []
def is_attribute_settable(self, element_id, attribute): ref = self._get_ref(element_id) if ref is None: return False try: err, settable = AXUIElementIsAttributeSettable(ref, attribute, None) return err == 0 and bool(settable) except Exception: return False
def attribute_value_count(self, element_id, attribute): ref = self._get_ref(element_id) if ref is None: return 0 try: err, count = AXUIElementGetAttributeValueCount(ref, attribute, None) return count if err == 0 else 0 except Exception: return 0
def attribute_values_range(self, element_id, attribute, index, count): ref = self._get_ref(element_id) if ref is None: return [] try: err, values = AXUIElementCopyAttributeValues(ref, attribute, index, count, None) if err == 0 and values: return [self._serialize_value(v) for v in values] except Exception: pass return []
def get_multiple(self, element_id, attributes): ref = self._get_ref(element_id) if ref is None: return {} try: err, values, errors = AXUIElementCopyMultipleAttributeValues( ref, attributes, 0, None, None ) if err == 0 and values: result = {} for i, attr in enumerate(attributes): if i < len(values): result[attr] = self._serialize_value(values[i]) else: result[attr] = None return result except Exception: pass return self.get(element_id, attributes)
# ── Parameterized Attributes ──
def parameterized_attribute_names(self, element_id=None): ref = self._get_ref(element_id) if element_id else self._app_ref if ref is None: return [] try: err, names = AXUIElementCopyParameterizedAttributeNames(ref, None) if err == 0 and names: return list(names) except Exception: pass return []
def parameterized_attribute_value(self, element_id, attribute, parameter): ref = self._get_ref(element_id) if ref is None: return None try: err, value = AXUIElementCopyParameterizedAttributeValue( ref, attribute, parameter, None ) if err == 0: return self._serialize_value(value) except Exception: pass return None
# ── Action Introspection ──
def action_description(self, element_id, action_name): ref = self._get_ref(element_id) if ref is None: return "" try: err, desc = AXUIElementCopyActionDescription(ref, action_name, None) if err == 0 and desc: return str(desc) except Exception: pass return ""
# ─��� Position / PID / Timeout ──
def element_at_position(self, x, y): try: sys_ref = AXUIElementCreateSystemWide() err, el_ref = AXUIElementCopyElementAtPosition(sys_ref, float(x), float(y), None) if err == 0 and el_ref: element = self._ref_to_element(el_ref) return element except Exception: pass return None
def get_pid(self, element_id=None): ref = self._get_ref(element_id) if element_id else self._app_ref if ref is None: return -1 try: err, pid = AXUIElementGetPid(ref, None) return pid if err == 0 else -1 except Exception: return -1
def set_messaging_timeout(self, element_id, timeout_seconds): ref = self._get_ref(element_id) if element_id else self._app_ref if ref is None: return False try: err = AXUIElementSetMessagingTimeout(ref, float(timeout_seconds)) return err == 0 except Exception: return False
@staticmethod def create_system_wide(): return AXUIElementCreateSystemWide()
def tree(self, max_depth=5, root_id=None): root_ref = self._get_ref(root_id) if root_id else self._app_ref
def _build(ref, depth): el = self._ref_to_element(ref) node = { "role": el.role, "name": el.name, "id": el.id, "actions": el.actions, } if el.value: node["value"] = str(el.value)[:100] if depth < max_depth: err, children = AXUIElementCopyAttributeValue(ref, "AXChildren", None) if err == 0 and children: node["children"] = [_build(c, depth + 1) for c in children] return node
return _build(root_ref, 0)
def list_apps(self): from AppKit import NSWorkspace
apps = NSWorkspace.sharedWorkspace().runningApplications() return [ { "name": app.localizedName(), "pid": app.processIdentifier(), "bundle_id": app.bundleIdentifier() or "", "type": "regular" if app.activationPolicy() == 0 else "accessory", } for app in apps if app.activationPolicy() in (0, 1) ]
# ── Capability-based Search ──
def find_clickable(self, root_id=None, max_results=50): all_elements = self._walk_tree(root_id, max_results * 3) clickable = [] for el in all_elements: if "AXPress" in el.actions or "AXConfirm" in el.actions: subrole = self._get_attr(el.ref, "AXSubrole", "") if subrole in ( "AXCloseButton", "AXMinimizeButton", "AXZoomButton", "AXFullScreenButton", ): continue clickable.append(el) if len(clickable) >= max_results: break return clickable
def find_text_elements(self, root_id=None, max_results=100): all_elements = self._walk_tree(root_id, max_results * 3) text_elements = [] for el in all_elements: text = ( self._get_attr(el.ref, "AXValue", "") or self._get_attr(el.ref, "AXTitle", "") or self._get_attr(el.ref, "AXDescription", "") or el.name or "" ) if isinstance(text, str) and text.strip(): el.text = text.strip() text_elements.append(el) if len(text_elements) >= max_results: break return text_elements
def find_value_settable(self, root_id=None, max_results=20): all_elements = self._walk_tree(root_id, max_results * 3) settable = [] for el in all_elements: try: err, is_settable = AXUIElementIsAttributeSettable( el.ref, "AXValue", None ) if err == 0 and is_settable: settable.append(el) if len(settable) >= max_results: break except Exception: continue return settable
def find_togglable(self, root_id=None, max_results=20): all_elements = self._walk_tree(root_id, max_results * 3) togglable = [] for el in all_elements: if "AXPress" in el.actions: value = self._get_attr(el.ref, "AXValue", None) if value in (0, 1, True, False, "0", "1"): togglable.append(el) if len(togglable) >= max_results: break return togglable
# ── Text Snapshot ──
def snapshot_all_text(self, exclude_dynamic=True): text_elements = self.find_text_elements(max_results=200) texts = [] for el in text_elements: text = el.text if exclude_dynamic and any( p.match(text) for p in _DYNAMIC_TEXT_PATTERNS ): continue texts.append(text) return Counter(texts)
def wait_for_text_change(self, original_text, timeout=3.0): deadline = time.time() + timeout while time.time() < deadline: current = self.snapshot_all_text() if current != original_text: return current time.sleep(0.2) return self.snapshot_all_text()
def wait_for(self, role=None, name=None, timeout=5.0, max_results=1): deadline = time.time() + timeout while time.time() < deadline: results = self.find(role=role, name=name, max_results=max_results) if results: return results time.sleep(0.3) return []
# ── Verifier Helpers ──
def find_safe_buttons(self, max_results=20): clickable = self.find_clickable(max_results=max_results * 2) safe = [] for el in clickable: name_lower = (el.name or "").lower() if any( kw in name_lower for kw in [ "quit", "delete", "remove", "erase", "reset", "clear all", "uninstall", ] ): continue safe.append(el) if len(safe) >= max_results: break return safe
def ensure_ui_visible(self): _CONTAINER_ROLES = ["window", "popover", "group", "sheet"] # Menu-item labels that reveal the main UI via a Settings/Preferences # window (EN + ZH). Kept deliberately narrow and high-signal: broader # verbs like "open"/"show" risk pressing File-menu items such as # "Open…" that pop a file dialog instead of revealing the main UI. _REVEAL_KW = ("preference", "settings", "偏好", "设置")
def _visible(): # max_depth=12 (was 3): status-item / menu-bar popovers sit ~7-8 levels # deep in the AX tree, so a depth-3 check reported "not visible" even # after the popover opened -> reveal loops gave up / tests saw no UI. for role in _CONTAINER_ROLES: if self.find(role=role, max_results=1, max_depth=12): return True return False
if _visible(): return True menu_items = self.find(role="menu_bar_item", max_results=8, max_depth=3) for item in menu_items: self.action(item.id, "AXPress") time.sleep(0.5) if _visible(): return True # Two-level reveal: pressing the status/menu-bar item may open a MENU # (not the window). A valid recreation can wire it as # icon -> menu -> "Preferences…" -> window. Click a reveal item. for mi in self.find(role="menu_item", max_results=40, max_depth=6): name = (mi.name or "").lower() if name and any(k in name for k in _REVEAL_KW): self.action(mi.id, "AXPress") time.sleep(0.5) if _visible(): return True # AXPress may not work for apps using NSEvent mouse monitoring; # fall back to a real CGEvent click at the element's position. self.click_element_cg(item.id) time.sleep(1.0) if _visible(): return True # Preferences hotkey (⌘,) — standard macOS "show settings" trigger. # Guarded so this method preserves its contract of never raising # (osascript can hit the subprocess timeout). try: subprocess.run( [ "osascript", "-e", 'tell application "System Events" to ' 'keystroke "," using command down', ], capture_output=True, timeout=3, ) time.sleep(0.5) except Exception: pass return _visible()
def dismiss_any_dialog(self): for role in ["sheet", "dialog"]: dialogs = self.find(role=role, max_results=3, max_depth=3) for dlg in dialogs: buttons = self.find(role="button", root_id=dlg.id, max_results=10) for btn in buttons: name_lower = (btn.name or "").lower() if name_lower in ( "cancel", "ok", "close", "dismiss", "don't save", ): self.action(btn.id, "AXPress") time.sleep(0.3) return True subprocess.run( [ "osascript", "-e", 'tell application "System Events" to key code 53', ], capture_output=True, timeout=2, ) time.sleep(0.3) return True return False
def get_main_window(self): windows = self.find(role="window", max_results=10, max_depth=1) if not windows: return None if len(windows) == 1: return windows[0].id for w in windows: attrs = self.get(w.id, ["AXMain"]) if attrs.get("AXMain"): return w.id best, best_area = None, 0 for w in windows: attrs = self.get(w.id, ["AXSize"]) size = attrs.get("AXSize") if size is not None: area = getattr(size, "width", 0) * getattr(size, "height", 0) else: area = 0 if area > best_area: best_area = area best = w.id return best
# ── Internal ──
def _walk_tree(self, root_id, max_count): root_ref = self._get_ref(root_id) if root_id else self._app_ref results = []
def _recurse(ref): if len(results) >= max_count: return el = self._ref_to_element(ref) results.append(el) err, children = AXUIElementCopyAttributeValue(ref, "AXChildren", None) if err == 0 and children: for child in children: _recurse(child) if len(results) >= max_count: return
_recurse(root_ref) return results
def _ref_to_element(self, ref): el_id = str(hash(ref)) self._element_cache[el_id] = ref
role_raw = self._get_attr(ref, "AXRole", "") role = ROLE_MAP.get( role_raw, role_raw.replace("AX", "").lower() if role_raw else "unknown", ) name = self._get_attr(ref, "AXTitle", "") or self._get_attr( ref, "AXDescription", "" ) value = self._get_attr(ref, "AXValue", "") enabled = self._get_attr(ref, "AXEnabled", True)
actions = [] try: err, action_names = AXUIElementCopyActionNames(ref, None) if err == 0 and action_names: actions = list(action_names) except Exception: pass
return AXElement( id=el_id, role=role, name=name, value=value, enabled=enabled, actions=actions, ref=ref, )
def _get_ref(self, element_id): return self._element_cache.get(element_id)
def _get_element_center(self, ref): """Return (x, y) screen coordinates of the element's center, or None.""" pos_val = self._get_attr(ref, "AXPosition", None) size_val = self._get_attr(ref, "AXSize", None) if pos_val is None or size_val is None: return None pos_str = str(pos_val) size_str = str(size_val) pos_nums = re.findall(r"[-\d.]+", pos_str) size_nums = re.findall(r"[-\d.]+", size_str) if len(pos_nums) < 2 or len(size_nums) < 2: return None px, py = float(pos_nums[-2]), float(pos_nums[-1]) sw, sh = float(size_nums[-2]), float(size_nums[-1]) return (px + sw / 2, py + sh / 2)
def _get_attr(self, ref, attr_name, default=None): try: err, val = AXUIElementCopyAttributeValue(ref, attr_name, None) return val if err == 0 else default except Exception: return default
def _matches(self, el, role, name, name_contains, value, enabled): if role and el.role != role: return False if name and el.name != name: return False if name_contains and (not el.name or name_contains not in el.name): return False if value is not None and el.value != value: return False if enabled is not None and el.enabled != enabled: return False return True
def _serialize_value(self, val): if val is None: return None if isinstance(val, (str, int, float, bool)): return val if hasattr(val, "width") and hasattr(val, "height"): return {"width": val.width, "height": val.height} if hasattr(val, "x") and hasattr(val, "y"): return {"x": val.x, "y": val.y} return str(val)
def _pid_by_name(name): """Resolve a pid from a process name using the same MAXCOMLEN(15)/pgrep logic the stage shells use.""" s = name[:15] r = subprocess.run(["pgrep", "-x", s], capture_output=True, text=True) if r.returncode != 0: r = subprocess.run(["pgrep", "-f", s], capture_output=True, text=True) if r.returncode != 0: return None out = r.stdout.strip() return int(out.split("\n")[0]) if out else None123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584"""conftest.py template for verifiers.
Provides fixtures: app_path, app_process, ax, ax_with_reset, open_panel.Each test gets a fresh app instance — app is launched before and killed after every test."""
import jsonimport osimport signalimport subprocessimport tempfileimport time
import pytest
# ── RB TestGen kit: depth/jump declaration capture ──────────────────────────# Tests declare navigation depth + jump rigor via @pytest.mark.rb(depth=, jump_kind=,# expect=). This hook records the declaration + outcome so the runner can fold# depth/jump/tier/expect into <module>_results.json (rb_audit/rb_lint read them).# The record's `passed` is informational — the runner keeps pytest's exit code as the# authoritative pass/fail, so a teardown-phase failure (e.g. app crash check) is never# masked by a call-phase pass here._RB_TIER = {"none": 0, "liveness": 1, "reach": 2, "transition": 2, "value": 3}
def pytest_configure(config): config.addinivalue_line( "markers", "rb(depth, jump_kind, expect): declare navigation depth + jump rigor (RB TestGen kit)", )
@pytest.hookimpl(hookwrapper=True)def pytest_runtest_makereport(item, call): outcome = yield rep = outcome.get_result() if rep.when != "call": return rec_path = os.environ.get("RB_RECORD_FILE", "") if not rec_path: return m = item.get_closest_marker("rb") depth, jump_kind, expect = 0, "none", "" if m is not None: if m.args: try: depth = int(m.args[0]) except Exception: depth = 0 try: depth = int(m.kwargs.get("depth", depth) or 0) except Exception: depth = 0 jump_kind = m.kwargs.get("jump_kind", "none") or "none" expect = m.kwargs.get("expect", "") or "" if jump_kind not in _RB_TIER: jump_kind = "none" rec = { "name": item.nodeid, "passed": bool(rep.passed), "depth": max(0, int(depth)), "jump_kind": jump_kind, "tier": _RB_TIER[jump_kind], "expect": str(expect), } try: d = os.path.dirname(rec_path) if d: os.makedirs(d, exist_ok=True) with open(rec_path, "w") as f: json.dump(rec, f) except Exception: pass
def _find_pid_by_name(name): # macOS kernel truncates process names to 16 chars (MAXCOMLEN). # Drop -x (exact match) and use substring match so name[:15] still # matches the 16-char truncated kernel name. search = name[:15] result = subprocess.run( ["pgrep", search], capture_output=True, text=True, timeout=5) if result.returncode != 0: return None pids = result.stdout.strip().split("\n") return int(pids[0]) if pids and pids[0] else None
def _kill_pid(pid): try: os.kill(pid, signal.SIGTERM) time.sleep(1) os.kill(pid, 0) os.kill(pid, signal.SIGKILL) except ProcessLookupError: pass
def _find_all_pids_by_name(name): search = name[:15] result = subprocess.run( ["pgrep", search], capture_output=True, text=True, timeout=5) if result.returncode != 0: return [] return [int(p) for p in result.stdout.strip().split("\n") if p.strip()]
def _kill_existing_app(binary_name): # Kill ALL instances matching the name (not just the first). Otherwise a # still-running reference app (same binary name, launched in stage3/4) lingers # into the test run and can be scored in place of the recreation. Target # disambiguation for the process we actually test is done by executable PATH # in _resolve_target_pid below. if not binary_name: return for pid in _find_all_pids_by_name(binary_name): _kill_pid(pid) time.sleep(0.5)
def _get_all_pids(): result = subprocess.run(["ps", "-axo", "pid="], capture_output=True, text=True) return [int(p.strip()) for p in result.stdout.splitlines() if p.strip().isdigit()]
def _get_process_name(pid): # Use args= (full command line) instead of comm= which is truncated to # 16 chars (MAXCOMLEN) by the macOS kernel — breaks detection for long # binary names like "MacOSReachabilityTestARC" (24 chars). result = subprocess.run( ["ps", "-p", str(pid), "-o", "args="], capture_output=True, text=True) if result.returncode == 0 and result.stdout.strip(): exe = result.stdout.strip().split()[0] name = os.path.basename(exe) if name: return name result = subprocess.run( ["ps", "-p", str(pid), "-o", "comm="], capture_output=True, text=True) return os.path.basename(result.stdout.strip()) if result.returncode == 0 else None
def _get_process_args(pid): """Full command line (executable path + args) for a pid, kept WHOLE (not split). Substring tests on this are space-safe — Electron helpers like 'Foo Helper (GPU)' and bundle paths with spaces are matched correctly, unlike args.split()[0] which breaks at the first space.""" try: r = subprocess.run(["ps", "-p", str(pid), "-o", "args="], capture_output=True, text=True, timeout=5) if r.returncode == 0 and r.stdout.strip(): return r.stdout.strip() except Exception: pass return ""
# Command-line markers identifying the REFERENCE app (the ground-truth app kept# running from stage3/4). It always runs from a pipeline-internal path; the# recreation never does. A process whose command line contains one of these must# never be scored — this is what stops a crashed/absent recreation from being# silently scored as the still-running reference._REFERENCE_PATH_MARKERS = (".pipeline_refapp", "/pipeline_work/")
def _is_reference_proc(pid): a = _get_process_args(pid) return any(m in a for m in _REFERENCE_PATH_MARKERS)
def _args_under_app(pid, app_path): """True iff the pid's EXECUTABLE runs from inside app_path (it IS the app) — NOT a launcher like `open -W <bundle>` whose ARGUMENT merely contains the bundle path.
A running .app's argv0 is <bundle>/Contents/MacOS/<binary>, so we require that inner executable path. The old bare-substring test (`app_path in args`) also matched the lingering `open -W <bundle>` process launch.sh leaves behind (`exec open -W …`); that launcher has NO AX tree, so the fixture bound to it → every element lookup returned nothing → reference-app baseline ~0% → the whole suite was pruned to 0.""" if not app_path: return False args = _get_process_args(pid) ap = app_path.rstrip("/") if ap.endswith(".app"): # The real GUI process: argv0 == <bundle>/Contents/MacOS/<binary>. return (ap + "/Contents/MacOS/") in args # Non-bundle executable: require it as argv0 (command starts with it), not merely # mentioned as a later argument (which is how `open <path>` would match). return args == ap or args.startswith(ap + " ")
# Electron/CEF helper subprocesses live inside the app bundle too but are NOT the# app. Identified by a --type= switch (renderer/gpu-process/utility) or a# "Helper (...)" executable — matched on the full command line (space-safe)._HELPER_MARKERS = ("--type=", " Helper", "(GPU)", "(Renderer)", "(Plugin)", "(CEF")
def _is_helper_proc(pid): a = _get_process_args(pid) return any(m in a for m in _HELPER_MARKERS)
def _name_matches(pid, names): pname = _get_process_name(pid) if not pname: return False for cand in names: if cand and (pname == cand or cand.lower() in pname.lower() or pname.lower() in cand.lower()): return True return False
def _resolve_target_pid(candidate_pids, app_path, binary_name, app_dir_name, app_name_env): """Pick the process of the APP UNDER TEST — never a sibling reference, never a helper.
app_path is the app we were told to test: the OFFICIAL app at stage2 baseline (built under ~/pipeline_work/<app>/source/App.app) and the RECREATION at stage5 eval. In both cases a process running from INSIDE app_path IS the target and must be selected — even though that path lives under /pipeline_work/.
Selection order: 1. the non-helper process running from INSIDE app_path (exact path match), checked BEFORE any reference-marker filtering — a process that literally runs from app_path can never be the "other" app, so it is always eligible. 2. name match, for launch.sh setups that run the app from a build/DerivedData path DIFFERENT from app_path (very common: OFFICIAL_APP points at source/build/.../Release/App.app while launch.sh starts source/App.app). The reference (.pipeline_refapp) and helpers are excluded here.
BUGFIX (baseline 0% root cause): the reference markers used to be a flat (".pipeline_refapp", "/pipeline_work/") pre-filter applied to ALL candidates. But the OFFICIAL app under test at stage2 baseline is itself built under ~/pipeline_work/<app>/... — so the "/pipeline_work/" marker excluded the only running instance, _resolve_target_pid returned None -> conftest raised `Could not find process` -> every baseline test errored -> the suite was pruned to 0 -> the app went unscored. And the exact-path match in step 1 does NOT save it, because launch.sh frequently starts the app from a /pipeline_work/ sub-path that differs from OFFICIAL_APP (source/App.app vs source/build/.../App.app). Fix: suppress the broad "/pipeline_work/" marker when the app under test is ITSELF under /pipeline_work/ (i.e. baseline). ".pipeline_refapp" is always excluded. At stage5 eval the recreation lives under ~/Recreation (NOT /pipeline_work/), so app_in_pw is False there and the "/pipeline_work/" marker still fires to keep the official reference from ever being scored — preserving commit 99d3cef's intent. """ if app_path: for p in candidate_pids: if _args_under_app(p, app_path) and not _is_helper_proc(p): return p app_in_pw = bool(app_path) and "/pipeline_work/" in app_path
def _is_ref_here(pid): a = _get_process_args(pid) if ".pipeline_refapp" in a: return True if not app_in_pw and "/pipeline_work/" in a: return True return False
names = (binary_name, app_dir_name, app_name_env) for p in candidate_pids: if (not _is_helper_proc(p) and not _is_ref_here(p) and _name_matches(p, names)): return p return None
def _get_binary_name(app_path): if app_path: info_plist = os.path.join(app_path, "Contents", "Info.plist") if os.path.exists(info_plist): result = subprocess.run( ["defaults", "read", info_plist, "CFBundleExecutable"], capture_output=True, text=True, timeout=5) if result.returncode == 0: return result.stdout.strip() return os.environ.get("APP_BINARY") or os.environ.get("APP_NAME") or None
def _get_bundle_id(app_path): info_plist = os.path.join(app_path, "Contents", "Info.plist") if os.path.exists(info_plist): result = subprocess.run( ["defaults", "read", info_plist, "CFBundleIdentifier"], capture_output=True, text=True, timeout=5) if result.returncode == 0: return result.stdout.strip() return None
def _grant_tcc_permissions(bundle_id): """Grant all common TCC permissions to the app so system dialogs don't block tests.""" if not bundle_id: return tcc_db = os.path.expanduser( "~/Library/Application Support/com.apple.TCC/TCC.db") if not os.path.exists(tcc_db): return services = [ "kTCCServiceAccessibility", "kTCCServiceScreenCapture", "kTCCServiceAppleEvents", "kTCCServicePostEvent", "kTCCServiceListenEvent", "kTCCServiceSystemPolicyAllFiles", "kTCCServiceDeveloperTool", "kTCCServiceCalendar", "kTCCServiceAddressBook", "kTCCServiceContactsFull", "kTCCServiceContactsLimited", "kTCCServiceReminders", "kTCCServicePhotos", "kTCCServicePhotosAdd", "kTCCServiceCamera", "kTCCServiceMicrophone", "kTCCServiceBluetoothAlways", "kTCCServiceMediaLibrary", "kTCCServiceSpeechRecognition", "kTCCServiceMotion", "kTCCServiceLocation", "kTCCServiceFocusStatus", "kTCCServiceSystemPolicyDesktopFolder", "kTCCServiceSystemPolicyDocumentsFolder", "kTCCServiceSystemPolicyDownloadsFolder", "kTCCServiceSystemPolicyNetworkVolumes", "kTCCServiceSystemPolicyRemovableVolumes", "kTCCServiceFileProviderDomain", "kTCCServiceFileProviderPresence", ] now = str(int(time.time())) for svc in services: subprocess.run( ["sqlite3", tcc_db, f"INSERT OR REPLACE INTO access" f" (service, client, client_type, auth_value, auth_reason, auth_version," f" csreq, policy_id, indirect_object_identifier_type," f" indirect_object_identifier, indirect_object_code_identity," f" flags, last_modified, pid, pid_version, boot_uuid, last_reminded)" f" VALUES ('{svc}', '{bundle_id}', 0, 2, 0, 1," f" NULL, NULL, NULL, 'UNUSED', NULL, NULL, {now}, NULL, NULL, 'UNUSED', {now});"], capture_output=True, timeout=5)
def _clear_autosaved_documents(app_path, bundle_id=""): """Drop the app's UNSAVED documents from ~/Library/Autosave Information/.
macOS restores an unsaved document of a document-based app on the NEXT launch, and neither `defaults delete` nor removing the .savedState touches that directory. A test that types into the editor therefore leaks its content into the FOLLOWING test's launch state. Measured on MaciASL: after one test set the editor text, every later test came up with an 'Untitled' window still holding that text (OEM ID "RBTEST") instead of the app opening the machine's System DSDT, which failed 4 of its own baseline tests. Clearing this directory restored window 'System DSDT', a 92 KB editor and OEM ID "BOCHS ".
Scoped to entries naming the app under test (bundle name / bundle id), so an unrelated app's autosave is never touched. """ base = os.path.expanduser("~/Library/Autosave Information") if not os.path.isdir(base): return names = set() stem = os.path.basename(app_path or "").replace(".app", "").strip() if stem: names.add(stem.lower()) if bundle_id: names.add(bundle_id.lower()) names.add(bundle_id.rsplit(".", 1)[-1].lower()) if not names: return try: entries = os.listdir(base) except OSError: return for entry in entries: low = entry.lower() if any(n in low for n in names): subprocess.run(["rm", "-rf", os.path.join(base, entry)], capture_output=True, timeout=5)
def _reset_app_state(app_path): bundle_id = _get_bundle_id(app_path) # Autosaved documents survive an app with no readable bundle id too, so clear first. _clear_autosaved_documents(app_path, bundle_id or "") if not bundle_id: return subprocess.run(["defaults", "delete", bundle_id], capture_output=True, timeout=5) saved_state = os.path.expanduser( f"~/Library/Saved Application State/{bundle_id}.savedState") if os.path.isdir(saved_state): subprocess.run(["rm", "-rf", saved_state], capture_output=True, timeout=5)
def _activate_app(pid): """Bring the launched app frontmost (by pid) so interaction/menu tests hit the RIGHT app. Tests that open menus, send System Events keystrokes, or drive the frontmost app fail spuriously when it is merely launched-but-background (the case under automated per-test relaunch — nothing foregrounds it).
Uses NSRunningApplication.activateWithOptions_ (robust, by pid) — verified on a sandbox VM to return True and set frontmost. NOT osascript: the System Events 'process whose unix id is N' selector is unreliable (errors -1719 on Electron helper pids etc.). AX reads via the app_ref work regardless, so best-effort.""" try: from AppKit import NSRunningApplication app = NSRunningApplication.runningApplicationWithProcessIdentifier_(int(pid)) if app is not None: app.activateWithOptions_(1 << 1) # NSApplicationActivateIgnoringOtherApps except Exception: pass
def _launch_app(app_path): binary_name = _get_binary_name(app_path) _kill_existing_app(binary_name) if app_path: _reset_app_state(app_path)
before_pids = set(_get_all_pids())
launch_sh = os.environ.get("LAUNCH_SH", "") launch_proc = None launch_err_path = None if launch_sh and os.path.isfile(launch_sh): launch_err_fd, launch_err_path = tempfile.mkstemp(suffix="_launch.log") launch_err_file = os.fdopen(launch_err_fd, "w") launch_proc = subprocess.Popen( ["bash", launch_sh], stdout=subprocess.DEVNULL, stderr=launch_err_file) launch_err_file.close() elif app_path: subprocess.run(["open", app_path], check=True) else: pytest.fail("No APP_PATH and no LAUNCH_SH — cannot launch app")
pid = None app_dir_name = os.path.basename(app_path).replace(".app", "") if app_path else "" app_name_env = os.environ.get("APP_NAME", "") # Bind to the RECREATION only. When app_path is known we require a process # running from inside that bundle (path match) — immune to the reference app # sharing the same binary name. Reference processes are always excluded, so a # crashed / never-launched recreation resolves to None → the test fails (score # 0) instead of silently scoring the still-running reference. for _ in range(30): new_pids = set(_get_all_pids()) - before_pids pid = _resolve_target_pid(new_pids, app_path, binary_name, app_dir_name, app_name_env) if pid: break time.sleep(0.5)
# Fallback: launch.sh may have activated a pre-launched instance (no new pid, # e.g. `open` without -n). Search ALL pids — still restricted to the recreation # bundle (path match) / reference-excluded. if pid is None: pid = _resolve_target_pid(_get_all_pids(), app_path, binary_name, app_dir_name, app_name_env)
if pid is None: launch_stderr = "" if launch_err_path: try: if launch_proc: launch_proc.wait(timeout=2) with open(launch_err_path) as f: launch_stderr = f.read()[:500] except Exception: pass _dbg = subprocess.run( ["ps", "-axo", "pid,comm,args"], capture_output=True, text=True ).stdout[:3000] assert False, ( f"Could not find process for {app_path or launch_sh} within 15s.\n" f"binary_name={binary_name}, app_dir_name={app_dir_name}, " f"app_name_env={app_name_env}\n" f"launch stderr: {launch_stderr or '(empty)'}\n" f"Active processes (pid,comm,args):\n{_dbg}" )
if launch_err_path: try: os.unlink(launch_err_path) except OSError: pass # Bring the app frontmost BEFORE settling/AX-ready: menu-bar reads, opened menus, # and System Events keystrokes all target the frontmost app; a launched-but- # background app makes those tests fail spuriously (root cause of the mass 0% # baselines). Best-effort — AX reads via app_ref are unaffected. _activate_app(pid) # Electron apps are launched (via launch.sh, which build/recreation inject with # --force-renderer-accessibility) so their Chromium AXWebArea builds a few seconds # after launch; the AXHelper `ax` fixture then waits for it. Give the process a # moment to come up first. time.sleep(2) return pid
@pytest.fixture(scope="session")def app_path(): path = os.environ.get("APP_PATH", "") launch_sh = os.environ.get("LAUNCH_SH", "") if not path or not os.path.isdir(path): if launch_sh and os.path.isfile(launch_sh): return "" assert False, ( f"APP_PATH not set or invalid: '{path}', and no LAUNCH_SH found. " "Set via: export APP_PATH=/path/to/App.app or export LAUNCH_SH=/path/to/launch.sh" ) bundle_id = _get_bundle_id(path) if bundle_id: _grant_tcc_permissions(bundle_id) return path
@pytest.fixturedef app_process(app_path): pid = _launch_app(app_path) yield pid _kill_pid(pid)
@pytest.fixturedef ax(app_process): from ax_helpers import AXHelper # wait_for_ready=True: AXHelper._wait_until_ready() polls the app's AX tree until # it reports AXChildren>0 before the first query (default True, 10s). This was # explicitly set to False, so every test queried an app that may not be AX-ready # yet — under per-test relaunch + VM load the tree is still empty → element lookups # return nothing → `assert False` → the test fails on the REFERENCE app → 0% # baseline → the whole suite gets pruned to 0. Same fixture is used by stage2 # baseline (over-prune) AND stage5 eval (recreated app scored spuriously low), so # this one flag corrupted both. Restore the wait (the _launch_app comment already # states the fixture "waits for it"). # ready_timeout=45 (was default 10): heavy apps (Qt video editors like olive, # large Electron) need >10s for AXChildren>0 after a per-test relaunch under VM # load. At 10s the wait warned-and-proceeded on a still-empty tree → element # lookups returned nothing → assert False → ALL tests fail baseline on the # OFFICIAL app → the whole suite is pruned to empty (observed: olive 53 real # tests all pruned). A working app reaches AXChildren>0 in <10s so this only # costs time on genuinely-slow apps; it never false-fails a working one. return AXHelper(app_process, wait_for_ready=True, ready_timeout=45)
@pytest.fixturedef ax_with_reset(ax): import verifier_helpers as helpers helpers.ensure_panel_open(ax) yield ax helpers.dismiss_menus(ax)
@pytest.fixture(autouse=True)def check_app_alive(app_process): yield try: os.kill(app_process, 0) except ProcessLookupError: pytest.fail(f"App process {app_process} crashed during test")
@pytest.fixture(scope="session", autouse=True)def check_ax_permission(): try: import ApplicationServices trusted = ApplicationServices.AXIsProcessTrusted() if not trusted: pytest.exit("Process does not have Accessibility permission") except ImportError: pass
@pytest.fixture(scope="session")def official_screenshots_dir(): """Path to the directory containing official app screenshots (ground truth). Set via OFFICIAL_SCREENSHOTS_DIR env var; defaults to ./official_screenshots/""" d = os.environ.get("OFFICIAL_SCREENSHOTS_DIR", os.path.join(os.path.dirname(__file__), "official_screenshots")) if not os.path.isdir(d): # A-ii: FAIL, don't skip. A missing official-screenshot baseline means this # visual test has no ground truth → it must be pruned (counted as failed), never # silently skipped. The runner treats skip as fail anyway; failing here is explicit # and keeps the "no skip — unimplemented/missing == fail" invariant. pytest.fail(f"Official screenshots dir not found: {d}") return d
@pytest.fixture(scope="session")def recreated_screenshots_dir(tmp_path_factory): """Temporary directory for recreated app screenshots during test run.""" return str(tmp_path_factory.mktemp("recreated_screenshots"))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789"""rb_radiola.py — shared, PORTABLE navigation/observation helpers for the RadiolaAX test suite.
Radiola is a macOS *status-bar* (accessory / LSBackgroundOnly) app: it has NO window atlaunch. Every surface has to be revealed through the status-bar item or through the app'sown menu bar. The helpers below encapsulate the reveal steps that were verified againstthe running reference app, and are written so a faithful recreation is driven by exactlythe same calls (tolerant locators, several fallbacks, no hardcoded install path, no`defaults write`, no direct AX handle creation — the `ax` fixture owns the connection).
Naming convention matters: the forward-navigation helpers are named `rb_enter_*` /`rb_reach_*` so `rb_testgen_kit.rb_audit_depth` can MEASURE the declared navigation depthfrom the test source.
IMPORTANT for test authors--------------------------* Use the plain `ax` fixture, NOT `ax_with_reset` — `verifier_helpers.ensure_panel_open()` blind-presses every menu-bar item (including Apple/File/Edit) and cannot recognise Radiola's status menu, so it leaves stray system menus open.* NEVER press the Settings "Audio" tab: `AudioSytstem.devices()` traps (index out of range) on a machine with no audio devices and the app dies -> conftest's `check_app_alive` fails the test. `SETTINGS_TABS_SAFE` excludes it.* NEVER press "Remove station", "Add station"/"Add group" *OK*, or Quit: the station list is persisted to ~/Library/Application Support/…/bookmarks.opml and would leak into every later test. Opening those sheets and pressing Cancel is safe (and is what the tests do)."""
from __future__ import annotations
import jsonimport osimport subprocessimport time
import verifier_helpers as helpers
# ── Reference-observed constants (all OBSERVED on the running app, not read from source) ──
APP_MENU_NAMES = ("Apple", "Radiola", "File", "Edit", "Control", "Window", "Help", "View", "Format")
# The three default favourite stations, exactly as the status menu / stations list show them.STATION_1 = "Radio Caroline"STATION_2 = "Radio Caroline 319 Gold [ Hits from '60-'70 ]"STATION_3 = "Radio Caroline 259 Gold [ Happy Rock & Album Station ]"DEFAULT_STATIONS = (STATION_1, STATION_2, STATION_3)STATION_1_URL = "http://sc3.radiocaroline.net:8030"STATION_2_URL = "http://www.rcgoldserver.eu:8192"STATION_3_URL = "http://www.rcgoldserver.eu:8253"
# Status-menu commands present with the default settings.STATUS_MENU_COMMANDS = ("Open Radiola", "History...", "Settings...", "Quit")
SETTINGS_TABS_SAFE = ("Controls", "Appearance", "Startup", "Updates")SETTINGS_TAB_UNSAFE = "Audio" # crashes the reference app in this environment
CONNECTING_TEXT = "Connecting..."
# Keyboard codes for the few characters the tests type (CGEvent virtual key codes).# Shifted characters carry their modifier, so ':' really produces ':' and not ';'._KEYCODES = { "a": 0, "b": 11, "c": 8, "d": 2, "e": 14, "f": 3, "g": 5, "h": 4, "i": 34, "j": 38, "k": 40, "l": 37, "m": 46, "n": 45, "o": 31, "p": 35, "q": 12, "r": 15, "s": 1, "t": 17, "u": 32, "v": 9, "w": 13, "x": 7, "y": 16, "z": 6, "0": 29, "1": 18, "2": 19, "3": 20, "4": 21, "5": 23, "6": 22, "7": 26, "8": 28, "9": 25, ".": 47, "/": 44, ";": 41, "-": 27, " ": 49,}
# ── low level ────────────────────────────────────────────────────────────────────────
def _val(ax, el_id, attr="AXValue"): return ax.get(el_id, [attr]).get(attr)
def label_values(ax, root_id=None, max_results=80): """AXValue of every static text under `root_id` (the whole app when None).""" out = [] for l in ax.find(role="label", root_id=root_id, max_results=max_results): v = _val(ax, l.id) if v: out.append(str(v)) return out
def text_field_values(ax, root_id=None, max_results=60): out = [] for t in ax.find(role="text_field", root_id=root_id, max_results=max_results): v = _val(ax, t.id) if v: out.append(str(v)) return out
def buttons(ax, root_id=None, max_results=60): """{AXTitle/description -> element} for every button under root_id.""" res = {} for b in ax.find(role="button", root_id=root_id, max_results=max_results): if b.name: res.setdefault(b.name, b) return res
def checkboxes(ax, root_id=None, max_results=40): res = {} for c in ax.find(role="checkbox", root_id=root_id, max_results=max_results): if c.name: res.setdefault(c.name, c) return res
def find_by_keywords(elements, keywords): """First element whose name contains any keyword (case-insensitive).""" for el in elements or []: n = (getattr(el, "name", "") or "").lower() if n and any(k.lower() in n for k in keywords): return el return None
def press(ax, el): """AXPress with an AXPick fallback (menu items accept either).""" if el is None: return False if ax.action(el.id, "AXPress"): return True return ax.action(el.id, "AXPick")
def close_all_menus(ax): """Escape twice — closes an open status menu / context menu / popup menu.""" helpers.send_key(helpers.KC_ESCAPE) time.sleep(0.25) helpers.send_key(helpers.KC_ESCAPE) time.sleep(0.25)
def type_chars(ax, el, text): """Focus `el` and type `text` with REAL key events.
An AXValue write does not run NSTextField's controlTextDidChange:, so a dialog that enables its OK button from live editing never updates. Real key events do.
Only UNSHIFTED characters are typed (a-z 0-9 . / ; - space); anything else is skipped, because holding shift through a CGEvent burst leaks the modifier into the next keys. """ import ApplicationServices as AS ref = ax._get_ref(el.id) if ref is None: return False AS.AXUIElementSetAttributeValue(ref, "AXFocused", True) time.sleep(0.35) for ch in text.lower(): kc = _KEYCODES.get(ch) if kc is None: # only unshifted keys — see docstring continue helpers.send_key(kc) time.sleep(0.35) return True
def clipboard(): try: return subprocess.run(["pbpaste"], capture_output=True, text=True, timeout=5).stdout except Exception: return ""
def set_clipboard(text): try: p = subprocess.Popen(["pbcopy"], stdin=subprocess.PIPE) p.communicate(text.encode()) except Exception: pass
# ── windows ──────────────────────────────────────────────────────────────────────────
def windows(ax): return ax.find(role="window", max_results=10, max_depth=1)
def window_titles(ax): return [str(ax.get(w.id, ["AXTitle"]).get("AXTitle") or "") for w in windows(ax)]
def find_window(ax, title, timeout=0.0): """Window whose AXTitle equals/contains `title` (case-insensitive).""" t0 = time.time() while True: for w in windows(ax): wt = str(ax.get(w.id, ["AXTitle"]).get("AXTitle") or "") if wt and title.lower() in wt.lower(): return w if time.time() - t0 >= timeout: return None time.sleep(0.25)
def wait_for_window(ax, title, timeout=6.0): return find_window(ax, title, timeout=timeout)
# ── the status-bar item: Radiola's ONLY entry point ──────────────────────────────────
def status_item(ax): """The app's status-bar (menu-bar-extra) item.
Reference: an AXMenuBarItem with AXRoleDescription 'status menu', empty AXTitle and a real 32x22 frame, living in a second AXMenuBar. Fallbacks keep this working for a recreation that reports a different role description. """ items = ax.find(role="menu_bar_item", max_results=24, max_depth=6) for m in items: if (ax.get(m.id, ["AXRoleDescription"]).get("AXRoleDescription") or "") == "status menu": return m for m in items: title = ax.get(m.id, ["AXTitle"]).get("AXTitle") if title in (None, ""): size = str(ax.get(m.id, ["AXSize"]).get("AXSize") or "") if "w:0.000000" not in size: return m for m in items: if (m.name or "") not in APP_MENU_NAMES: return m return None
def status_item_tooltip(ax): """AXHelp of the status item — the reference puts the station name (and, while playing/connecting, the song line) there.""" si = status_item(ax) return "" if si is None else str(ax.get(si.id, ["AXHelp"]).get("AXHelp") or "")
def rb_reach_status_menu(ax, timeout=5.0): """Open the status-bar menu and return its AXMenu element (None on failure).
A REAL CGEvent click is used, never AXPress: the reference REBUILDS the menu inside an NSEvent mouse-down monitor, so the menu contents follow the current settings only on a real click. (AXPress replays the previously attached NSMenu, i.e. a stale snapshot — that silently broke settings->menu tests.) AXPress is only a last-ditch fallback for a recreation that wires the status item's action directly and never gets a menu otherwise. """ si = status_item(ax) if si is None: return None for attempt in range(3): if attempt < 2: ax.click_element_cg(si.id) else: ax.action(si.id, "AXPress") # Settle before the first probe: for ~1s after the click the PREVIOUS NSMenu is # still the status item's AX child, so probing immediately returns a STALE menu # (its items reflect the settings/favourites of the previous open). time.sleep(1.0) t0 = time.time() while time.time() - t0 < timeout: menus = ax.find(role="menu", root_id=si.id, max_results=4, max_depth=2) if menus: return menus[-1] pops = ax.find(role="popover", max_results=2, max_depth=8) if pops: return pops[-1] time.sleep(0.2) close_all_menus(ax) return None
def status_menu_items(ax, menu): """[(name, enabled, cmd_char)] for the top level of an open status menu.""" if menu is None: return [] out = [] for i in ax.find(role="menu_item", root_id=menu.id, max_results=60, max_depth=1): d = ax.get(i.id, ["AXEnabled", "AXMenuItemCmdChar"]) out.append((i.name or "", d.get("AXEnabled"), d.get("AXMenuItemCmdChar"))) return out
def status_menu_item(ax, menu, name): """Menu item of an open status menu, matched exactly then by substring.""" if menu is None: return None items = ax.find(role="menu_item", root_id=menu.id, max_results=60, max_depth=1) for i in items: if (i.name or "").strip() == name: return i low = name.lower().rstrip(".") for i in items: n = (i.name or "").strip().lower() if n and (low in n or n.rstrip(".") == low): return i return None
def status_menu_favorite_names(ax, menu): """Station entries of an open status menu: every enabled item between the disabled 'Favorite stations' header and the 'Open Radiola' command.""" names = [] started = False for (n, enabled, _c) in status_menu_items(ax, menu): if not started: if "favorite" in n.lower(): started = True continue if n in STATUS_MENU_COMMANDS or n.startswith("Open ") or n == "Mute" or n == "Unmute": break if n and enabled: names.append(n.strip()) return names
def status_menu_play_item(ax, menu): """The custom 'now playing' first item: {icon, song, station, favorite}.
icon AXImage whose name is 'Play' when paused and 'Pause' while connecting/playing song AXStaticText: '' when paused, 'Connecting...' while connecting station AXStaticText holding the current station name favorite AXCheckBox 'Mark current song as favorite' (disabled unless playing) """ res = {"icon": None, "song": None, "station": None, "favorite": None, "labels": []} if menu is None: return res kids = ax.find(root_id=menu.id, max_results=40, max_depth=2) for c in kids: if c.role == "image" and res["icon"] is None: res["icon"] = c elif c.role == "checkbox" and res["favorite"] is None: res["favorite"] = c elif c.role == "label": res["labels"].append(c) if res["labels"]: res["song"] = res["labels"][0] if len(res["labels"]) > 1: res["station"] = res["labels"][1] return res
# ── the app's own menu bar ───────────────────────────────────────────────────────────
def app_menu(ax, name): """The AXMenuBarItem of the app's own menu bar with this title.""" for m in ax.find(role="menu_bar_item", max_results=24, max_depth=6): if (m.name or "") == name: return m return None
def rb_enter_app_menu(ax, name): """The AXMenu hanging off the named app menu-bar item (present in the AX tree without activating the app, which is what makes these tests work for a background app).""" mbi = app_menu(ax, name) if mbi is None: return None menus = ax.find(role="menu", root_id=mbi.id, max_results=2, max_depth=1) return menus[0] if menus else None
def app_menu_items(ax, name): """[(item name, enabled)] for the named app menu.""" menu = rb_enter_app_menu(ax, name) if menu is None: return [] return [(i.name or "", ax.get(i.id, ["AXEnabled"]).get("AXEnabled")) for i in ax.find(role="menu_item", root_id=menu.id, max_results=60, max_depth=1)]
def app_menu_item(ax, menu_name, item_name): menu = rb_enter_app_menu(ax, menu_name) if menu is None: return None items = ax.find(role="menu_item", root_id=menu.id, max_results=60, max_depth=1) for i in items: if (i.name or "").strip() == item_name: return i low = item_name.lower().rstrip("…. ") for i in items: n = (i.name or "").strip().lower() if n and low and (low in n): return i return None
def control_menu_item_names(ax): """Titles in the 'Control' menu — 'Play' while paused, 'Pause' while playing (the reference hides the other one).""" return [n for (n, _en) in app_menu_items(ax, "Control") if n]
# ── the three windows ─��──────────────────────────────────────────────────────────────
def _reach_window_via_status_menu(ax, item_name, window_title, timeout=8.0): menu = rb_reach_status_menu(ax) item = status_menu_item(ax, menu, item_name) if item is not None: press(ax, item) w = wait_for_window(ax, window_title, timeout=timeout) if w is not None: return w close_all_menus(ax) return None
def rb_enter_stations_window(ax, timeout=8.0): """Reveal the main 'Stations' window (status menu -> 'Open Radiola').""" w = find_window(ax, "Stations") if w is not None: return w w = _reach_window_via_status_menu(ax, "Open Radiola", "Stations", timeout) if w is not None: return w # fallback: the global ⌘R the reference also binds helpers.send_key(_KEYCODES["r"], ["cmd"]) return wait_for_window(ax, "Stations", timeout=4.0)
def rb_enter_history_window(ax, timeout=8.0): """Reveal the 'History' window (status menu -> 'History...').""" w = find_window(ax, "History") if w is not None: return w w = _reach_window_via_status_menu(ax, "History...", "History", timeout) if w is not None: return w helpers.send_key(_KEYCODES["y"], ["cmd"]) return wait_for_window(ax, "History", timeout=4.0)
def settings_window(ax): """The preferences window — its AXTitle is the SELECTED TAB name, so match any of them.""" for w in windows(ax): t = str(ax.get(w.id, ["AXTitle"]).get("AXTitle") or "") if t in SETTINGS_TABS_SAFE or t == SETTINGS_TAB_UNSAFE: return w return None
def rb_enter_settings_window(ax, timeout=8.0): """Reveal the preferences window (status menu -> 'Settings...'); opens on 'Controls'.""" w = settings_window(ax) if w is not None: return w menu = rb_reach_status_menu(ax) item = status_menu_item(ax, menu, "Settings...") if item is not None: press(ax, item) t0 = time.time() while time.time() - t0 < timeout: w = settings_window(ax) if w is not None: return w time.sleep(0.25) close_all_menus(ax) # fallback: the app menu's Settings…/Preferences… item item = app_menu_item(ax, "Radiola", "Settings") if item is None: item = app_menu_item(ax, "Radiola", "Preferences") if item is not None: press(ax, item) t0 = time.time() while time.time() - t0 < timeout: w = settings_window(ax) if w is not None: return w time.sleep(0.25) return None
def settings_tab_buttons(ax, win=None): """{tab name -> toolbar button} of the preferences window.""" win = win or settings_window(ax) if win is None: return {} return buttons(ax, root_id=win.id, max_results=40)
def rb_enter_settings_tab(ax, tab_name, timeout=6.0): """Select a preferences tab and return the window (whose title becomes the tab name).
Refuses the 'Audio' tab, which traps in the reference app on a device-less machine. """ if tab_name == SETTINGS_TAB_UNSAFE: raise AssertionError("the Audio settings tab crashes the reference app here") win = rb_enter_settings_window(ax) if win is None: return None btn = settings_tab_buttons(ax, win).get(tab_name) if btn is None: return None press(ax, btn) t0 = time.time() while time.time() - t0 < timeout: w = find_window(ax, tab_name) if w is not None: return w time.sleep(0.25) return settings_window(ax)
def settings_tab_title(ax): win = settings_window(ax) return "" if win is None else str(ax.get(win.id, ["AXTitle"]).get("AXTitle") or "")
# ── inside the Stations window ───────────────────────────────────────────────────────
def stations_play_button(ax, win=None): """The big play/pause button: AXTitle 'play' + AXHelp 'Play' while paused, 'pause'/'Pause' while playing.""" win = win or find_window(ax, "Stations") if win is None: return None for b in ax.find(role="button", root_id=win.id, max_results=40): if (b.name or "").lower() in ("play", "pause"): return b return None
def stations_volume_slider(ax, win=None): win = win or find_window(ax, "Stations") if win is None: return None sl = ax.find(role="slider", root_id=win.id, max_results=3) return sl[0] if sl else None
def stations_volume_button(ax, win=None, direction="up"): """The +/- volume buttons ('volume up' / 'audio output volume off').""" win = win or find_window(ax, "Stations") if win is None: return None want_up = direction == "up" for b in ax.find(role="button", root_id=win.id, max_results=40): n = (b.name or "").lower() h = str(ax.get(b.id, ["AXHelp"]).get("AXHelp") or "").lower() if want_up and ("up" in n or "increase" in h): return b if not want_up and ("off" in n or "down" in n or "decrease" in h): return b return None
def stations_mute_checkbox(ax, win=None): win = win or find_window(ax, "Stations") if win is None: return None for c in ax.find(role="checkbox", root_id=win.id, max_results=20): n = (c.name or "").lower() h = str(ax.get(c.id, ["AXHelp"]).get("AXHelp") or "").lower() if "mute" in n or "mute" in h: return c return None
def stations_station_labels(ax, win=None): """The station-name / current-song labels shown in the Stations window toolbar.""" win = win or find_window(ax, "Stations") if win is None: return [] out = [] for l in ax.find(role="label", root_id=win.id, max_results=60): d = ax.get(l.id, ["AXValue", "AXHelp"]) if d.get("AXHelp") is not None: # only the two toolbar labels carry AXHelp out.append((l, str(d.get("AXValue") or ""))) return out
def stations_song_label_value(ax, win=None): labs = stations_station_labels(ax, win) return labs[0][1] if labs else ""
def stations_station_label_value(ax, win=None): labs = stations_station_labels(ax, win) return labs[1][1] if len(labs) > 1 else ""
def sidebar_labels(ax, win=None): """Sidebar entries: 'My lists', 'My stations', 'Radio browser', 'By tag', 'By name', 'By country'.""" win = win or find_window(ax, "Stations") if win is None: return [] wanted = ("My lists", "My stations", "Radio browser", "By tag", "By name", "By country") out = [] for l in ax.find(role="label", root_id=win.id, max_results=80): v = str(_val(ax, l.id) or "") if v in wanted: out.append((l, v)) return out
def sidebar_label(ax, text, win=None): for el, v in sidebar_labels(ax, win): if v == text: return el return None
def rb_enter_sidebar_list(ax, text, win=None, settle=1.6): """Click a sidebar entry (a real click — the outline's action only fires on click).""" el = sidebar_label(ax, text, win) if el is None: return False ax.click_element_cg(el.id) time.sleep(settle) return True
def station_rows(ax, win=None): """[(title, url)] of the local station rows (each row = 2 text fields).""" win = win or find_window(ax, "Stations") if win is None: return [] out = [] for r in ax.find(role="row", root_id=win.id, max_results=40): tfs = [str(_val(ax, t.id) or "") for t in ax.find(role="text_field", root_id=r.id, max_results=4)] if len(tfs) >= 2: out.append((tfs[0], tfs[1])) return out
def station_favorite_checkboxes(ax, win=None): win = win or find_window(ax, "Stations") if win is None: return [] return [c for c in ax.find(role="checkbox", root_id=win.id, max_results=20) if (c.name or "").lower() == "favorite"]
def station_favorite_state(ax, checkbox): """Whether a station row is CURRENTLY a favourite, read from AXHelp.
The row's star is an NSButton of type .toggle whose `state` (== AXValue) is flipped by AppKit on every click and is NEVER synced back from the model, so AXValue is a meaningless click counter. The app DOES rewrite the tooltip from the model on every change: 'Unmark the station as a favorite' while it is a favourite, 'Mark the station as a favorite' while it is not. That tooltip is the observable truth. """ h = str(ax.get(checkbox.id, ["AXHelp"]).get("AXHelp") or "").lower() if "unmark" in h: return True if "mark" in h: return False return None
def station_context_buttons(ax, win=None): win = win or find_window(ax, "Stations") if win is None: return [] return [b for b in ax.find(role="button", root_id=win.id, max_results=40) if "context" in (b.name or "").lower()]
def rb_reach_row_context_menu(ax, index=0, win=None, timeout=4.0): """Open a station row's '...' context menu; returns the AXMenu.""" btns = station_context_buttons(ax, win) if len(btns) <= index: return None btn = btns[index] ax.action(btn.id, "AXShowMenu") t0 = time.time() while time.time() - t0 < timeout: menus = ax.find(role="menu", root_id=btn.id, max_results=3, max_depth=2) if menus: return menus[0] time.sleep(0.2) return None
def menu_item_names(ax, menu, max_depth=1): if menu is None: return [] return [i.name or "" for i in ax.find(role="menu_item", root_id=menu.id, max_results=40, max_depth=max_depth)]
def menu_item_by_name(ax, menu, name): if menu is None: return None items = ax.find(role="menu_item", root_id=menu.id, max_results=40, max_depth=1) for i in items: if (i.name or "").strip() == name: return i low = name.lower() for i in items: if low in (i.name or "").strip().lower(): return i return None
def rb_reach_add_station_sheet(ax, win=None, timeout=5.0): """'Add station' -> the modal sheet with Title/Url fields (Cancel it afterwards).""" return _reach_sheet(ax, ("add station",), win, timeout)
def rb_reach_add_group_sheet(ax, win=None, timeout=5.0): """'Add group' -> the modal sheet with a Title field (Cancel it afterwards).""" return _reach_sheet(ax, ("add group",), win, timeout)
def _reach_sheet(ax, keywords, win, timeout): win = win or find_window(ax, "Stations") if win is None: return None btn = None for b in ax.find(role="button", root_id=win.id, max_results=40): n = (b.name or "").lower() if any(k in n for k in keywords): btn = b break if btn is None: return None press(ax, btn) t0 = time.time() while time.time() - t0 < timeout: sheets = ax.find(role="sheet", max_results=3, max_depth=3) if sheets: return sheets[0] time.sleep(0.2) return None
def sheet_cancel(ax, sheet=None): """Press the sheet's Cancel button (falls back to Escape).""" sheets = [sheet] if sheet is not None else ax.find(role="sheet", max_results=3, max_depth=3) for sh in sheets: if sh is None: continue btn = find_by_keywords(ax.find(role="button", root_id=sh.id, max_results=10), ["cancel", "close"]) if btn is not None and press(ax, btn): time.sleep(0.6) return True helpers.send_key(helpers.KC_ESCAPE) time.sleep(0.6) return not ax.find(role="sheet", max_results=1, max_depth=3)
def sheet_present(ax): return bool(ax.find(role="sheet", max_results=1, max_depth=3))
# ── inside the History window ────────────────────────────────────────────────────────
def history_favorites_checkbox(ax, win=None): win = win or find_window(ax, "History") if win is None: return None for c in ax.find(role="checkbox", root_id=win.id, max_results=10): n = (c.name or "").lower() if "favorite" in n: return c return None
# ── screenshots for the VLM judge ────────────────────────────────────────────────────
def screenshot_assert(test_name, description, results_dir=None): """Capture the screen and record what a VLM should see in it.""" results_dir = results_dir or os.environ.get("RESULTS_DIR") or os.getcwd() ss_dir = os.path.join(results_dir, "screenshots") try: os.makedirs(ss_dir, exist_ok=True) except Exception: return ss_path = os.path.join(ss_dir, f"{test_name}.png") try: subprocess.run(["screencapture", "-x", ss_path], timeout=8) except Exception: pass assertions_file = os.path.join(ss_dir, "assertions.json") assertions = {} if os.path.exists(assertions_file): try: with open(assertions_file) as f: assertions = json.load(f) except Exception: assertions = {} assertions[f"{test_name}.png"] = description try: with open(assertions_file, "w") as f: json.dump(assertions, f, indent=2) except Exception: pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575#!/usr/bin/env python3"""RB TestGen Kit (macOS/AX port of the Linux v7.5 kit) — a test's NAVIGATIONDEPTH and JUMP RIGOR are DECLARED (not inferred), uniformly recorded, andself-auditable.
DIFFERENCE FROM LINUX: macOS tests are **pytest** (methods on Test* classes takingthe `ax` fixture, plain asserts) — NOT standalone scripts calling R.record(). So theDECLARATION 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 andwrites {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 isdepth 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 astimport globimport jsonimport osimport 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]}")123pytestpytest-checkpyobjc123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621"""AX BUTTON tests for Radiola (macOS status-bar radio player).
Every test drives a button that recon `## BUTTONS` (B1-B13) recorded a MEASUREDconsequence for, and asserts that consequence — never "the button exists" and never"the app did not crash".
Radiola has NO window at launch, so every button lives behind a navigation step: * Stations-window buttons -> rbr.rb_enter_stations_window(ax) (depth 1) * sheet / row-context -> + rbr.rb_reach_add_*_sheet / row menu (depth 2) * preferences buttons -> rbr.rb_enter_settings_window/tab(ax) (depth 1)
HARD PROHIBITIONS honoured here (recon `## APP` / `## BUTTONS`): * the preferences `Audio` tab is only ever ENUMERATED, never pressed (it traps in AudioSytstem.devices() and kills the app), * `Remove station`, a sheet's `Add station`/`Add group` OK button, `Check for Updates now`, `Quit`, `Quit Radiola`, `Radiola Help` and Export/Import are never pressed, * every sheet that is opened is closed again with Cancel and the station list is re-counted so nothing leaks into ~/…/bookmarks.opml.
Uses the plain `ax` fixture (NEVER `ax_with_reset`: verifier_helpers.ensure_panel_open()blind-presses every menu-bar item and leaves stray system menus open — see recon `## APP`)."""
import time
import pytest
import rb_radiola as rbrimport rb_testgen_kit as kit
# ── reference-observed expectations (recon ## TEXT / ## AX_TREE) ──────────────────────
SIDEBAR_LABELS = ["My lists", "My stations", "Radio browser", "By tag", "By name", "By country"]
ADD_STATION_PROMPT = "To add a station, fill out the following information:"ADD_GROUP_PROMPT = "To add a group, fill out the following information:"
APPEARANCE_CHECKBOXES = { "Show the volume control in the menu", "Show the mute item in the menu", 'Show the "Copy song title and artist" item in the menu', "Show a tooltip with the radiostation and song",}
CONTROLS_LABELS = ("Left mouse button:", "Middle mouse button:", "Right mouse button:", "Mouse wheel:", "Media key handling:")
# the six Controls popups, sorted: "shows the popup menu" x3, "does nothing" x2, "always"CONTROLS_POPUP_VALUES = sorted(["shows the popup menu"] * 3 + ["does nothing"] * 2 + ["always"])
CONTEXT_MENU_ITEMS = ["Copy station title", "Copy station URL"]
ALL_SETTINGS_TABS = sorted(list(rbr.SETTINGS_TABS_SAFE) + [rbr.SETTINGS_TAB_UNSAFE])
SEPARATOR_CHAR = "⎯" # ⎯ HORIZONTAL LINE EXTENSION — the tooltip separator run
# ── tiny local utilities (no navigation inside — depth stays honest) ──────────────────
def _wait_until(read, ok, timeout=5.0, interval=0.25): """Poll `read()` until `ok(value)` or timeout; always returns the last value read.""" val = read() t0 = time.time() while not ok(val) and (time.time() - t0) < timeout: time.sleep(interval) val = read() return val
def _play_state(ax, win): """(button name, AXHelp) of the Stations play/pause button — 'play'/'Play' when paused, 'pause'/'Pause' once it is connecting (recon B1).""" btn = rbr.stations_play_button(ax, win) if btn is None: return ("", "") return ((btn.name or "").lower(), str(ax.get(btn.id, ["AXHelp"]).get("AXHelp") or ""))
def _enabled(ax, el): return bool(ax.get(el.id, ["AXEnabled"]).get("AXEnabled"))
def _volume(ax, win): """Current volume-slider AXValue, re-resolving the slider each read so a rebuilt toolbar cannot leave us reading a stale element.""" slider = rbr.stations_volume_slider(ax, win) if slider is None: return None try: return float(rbr._val(ax, slider.id)) except (TypeError, ValueError): return None
def _sidebar_texts(ax, win): return [text for _el, text in rbr.sidebar_labels(ax, win)]
def _sheet_button(ax, sheet, keywords): return rbr.find_by_keywords( ax.find(role="button", root_id=sheet.id, max_results=12), keywords)
# ══════════════════════════════════════════════════════════════════════════════════════# B1 — the Stations window play button# ══════════════════════════════════════════════════════════════════════════════════════
class TestPlayButton:
@pytest.mark.rb(depth=1, jump_kind="transition", expect="Stations play button flips from name 'play'/AXHelp 'Play' " "to name 'pause'/AXHelp 'Pause'") def test_play_button_flips_identity_to_pause(self, ax): win = rbr.rb_enter_stations_window(ax) assert win is not None, "the Stations window never appeared"
before = _play_state(ax, win) assert before[0] == "play", f"expected a paused 'play' button, got {before}"
btn = rbr.stations_play_button(ax, win) assert rbr.press(ax, btn), "AXPress on the play button failed"
after = _wait_until(lambda: _play_state(ax, win), lambda s: s[0] == "pause", timeout=6.0) assert kit.rb_flip(before, after), \ f"play button did not change state: {before} -> {after}" assert after == ("pause", "Pause"), f"unexpected playing state {after}"
@pytest.mark.rb(depth=1, jump_kind="value", expect="Stations song label goes '' -> 'Connecting...'") def test_play_button_sets_song_label_to_connecting(self, ax): win = rbr.rb_enter_stations_window(ax) assert win is not None, "the Stations window never appeared"
song_before = rbr.stations_song_label_value(ax, win) assert song_before == "", f"song label should start empty, got {song_before!r}"
assert rbr.press(ax, rbr.stations_play_button(ax, win)), "play AXPress failed"
song_after = _wait_until(lambda: rbr.stations_song_label_value(ax, win), lambda v: v == rbr.CONNECTING_TEXT, timeout=6.0) assert kit.rb_value(song_after, rbr.CONNECTING_TEXT), \ f"song label is {song_after!r}, expected {rbr.CONNECTING_TEXT!r}" # the station label must NOT change — only the song line does assert rbr.stations_station_label_value(ax, win) == rbr.STATION_1
rbr.screenshot_assert( "buttons_stations_play_connecting", "Radiola's Stations window is open and playback has been started from its " "play button: the left sidebar lists 'My lists > My stations' and " "'Radio browser > By tag / By name / By country', the toolbar's play " "triangle has become a pause control, 'Connecting...' is shown above the " "station name 'Radio Caroline', a volume slider with -/mute/+ controls sits " "beside it, and the list below shows 3 Radio Caroline stations (each with a " "yellow favourite star and a '…' context button) above the Add station / " "Add group / Remove station buttons.")
@pytest.mark.rb(depth=1, jump_kind="value", expect="status-item tooltip becomes " "'Radio Caroline\\n<⎯ separator>\\nConnecting...'") def test_play_button_extends_status_item_tooltip(self, ax): win = rbr.rb_enter_stations_window(ax) assert win is not None, "the Stations window never appeared"
tip_before = rbr.status_item_tooltip(ax) assert tip_before == rbr.STATION_1, \ f"paused tooltip should be {rbr.STATION_1!r}, got {tip_before!r}"
assert rbr.press(ax, rbr.stations_play_button(ax, win)), "play AXPress failed"
tip_after = _wait_until(lambda: rbr.status_item_tooltip(ax), lambda v: rbr.CONNECTING_TEXT in v, timeout=6.0) assert kit.rb_value(tip_after, rbr.CONNECTING_TEXT), \ f"tooltip {tip_after!r} never gained the connecting line"
lines = tip_after.split("\n") assert len(lines) == 3, f"expected 3 tooltip lines, got {lines!r}" assert lines[0] == rbr.STATION_1 assert set(lines[1]) == {SEPARATOR_CHAR} and len(lines[1]) >= 20, \ f"middle tooltip line should be a long run of '{SEPARATOR_CHAR}', " \ f"got {lines[1]!r}" assert lines[2] == rbr.CONNECTING_TEXT
# ══════════════════════════════════════════════════════════════════════════════════════# B2 / B3 — the volume +/- buttons# ══════════════════════════════════════════════════════════════════════════════════════
class TestVolumeButtons:
@pytest.mark.rb(depth=1, jump_kind="value", expect="volume slider 0.5 -> 0.55 after one 'volume up' press") def test_volume_up_button_raises_slider_by_005(self, ax): win = rbr.rb_enter_stations_window(ax) assert win is not None, "the Stations window never appeared"
assert rbr.stations_volume_slider(ax, win) is not None, \ "no volume slider in the Stations window" start = _volume(ax, win) assert start is not None and abs(start - 0.5) < 1e-3, \ f"fresh-launch volume should be 0.5, got {start}"
up = rbr.stations_volume_button(ax, win, "up") assert up is not None, "no 'volume up' (Increase volume) button" assert rbr.press(ax, up), "AXPress on 'volume up' failed"
raised = _wait_until(lambda: _volume(ax, win), lambda v: v is not None and abs(v - 0.55) < 1e-3, timeout=3.0) assert raised is not None, "the volume slider disappeared" assert kit.rb_value(round(raised, 3), 0.55), \ f"volume up produced {raised}, expected 0.55" assert abs(raised - 0.55) < 1e-3
@pytest.mark.rb(depth=1, jump_kind="value", expect="volume slider 0.55 -> 0.5 after one 'Decrease volume' press") def test_volume_down_button_lowers_slider_by_005(self, ax): win = rbr.rb_enter_stations_window(ax) assert win is not None, "the Stations window never appeared"
assert rbr.stations_volume_slider(ax, win) is not None, \ "no volume slider in the Stations window"
up = rbr.stations_volume_button(ax, win, "up") assert up is not None, "no 'volume up' button" rbr.press(ax, up) raised = _wait_until(lambda: _volume(ax, win), lambda v: v is not None and abs(v - 0.55) < 1e-3, timeout=3.0) assert raised is not None and abs(raised - 0.55) < 1e-3, \ f"could not reach 0.55 first, slider is {raised}"
down = rbr.stations_volume_button(ax, win, "down") assert down is not None, "no 'audio output volume off' (Decrease volume) button" assert rbr.press(ax, down), "AXPress on the decrease-volume button failed"
lowered = _wait_until(lambda: _volume(ax, win), lambda v: v is not None and abs(v - 0.5) < 1e-3, timeout=3.0) assert lowered is not None, "the volume slider disappeared" assert kit.rb_value(round(lowered, 3), 0.5), \ f"volume down produced {lowered}, expected 0.5" assert abs(lowered - 0.5) < 1e-3
# ══════════════════════════════════════════════════════════════════════════════════════# B4 — the Stations toolbar "Toggle sidebar" button# ══════════════════════════════════════════════════════════════════════════════════════
class TestSidebarToggleButton:
@staticmethod def _toggle_button(ax, win): return rbr.find_by_keywords( ax.find(role="button", root_id=win.id, max_results=40), ["toggle sidebar", "sidebar"])
@pytest.mark.rb(depth=1, jump_kind="transition", expect="Stations sidebar collapses: 6 sidebar labels -> 0") def test_toggle_sidebar_button_collapses_sidebar(self, ax): win = rbr.rb_enter_stations_window(ax) assert win is not None, "the Stations window never appeared"
before = _sidebar_texts(ax, win) assert len(before) == 6, f"expected 6 sidebar labels, got {before!r}"
btn = self._toggle_button(ax, win) assert btn is not None, "no 'Toggle sidebar' toolbar button" assert rbr.press(ax, btn), "AXPress on 'Toggle sidebar' failed"
after = _wait_until(lambda: _sidebar_texts(ax, win), lambda v: len(v) == 0, timeout=4.0) assert kit.rb_flip(len(before), len(after)), \ f"sidebar did not collapse: {before!r} -> {after!r}" assert after == [], f"sidebar labels still visible: {after!r}"
@pytest.mark.rb(depth=1, jump_kind="value", expect="a second 'Toggle sidebar' press restores exactly " "['My lists','My stations','Radio browser','By tag'," "'By name','By country']") def test_toggle_sidebar_button_restores_all_six_labels(self, ax): win = rbr.rb_enter_stations_window(ax) assert win is not None, "the Stations window never appeared"
btn = self._toggle_button(ax, win) assert btn is not None, "no 'Toggle sidebar' toolbar button"
assert rbr.press(ax, btn), "first AXPress on 'Toggle sidebar' failed" collapsed = _wait_until(lambda: _sidebar_texts(ax, win), lambda v: len(v) == 0, timeout=4.0) assert collapsed == [], f"sidebar did not collapse first: {collapsed!r}"
assert rbr.press(ax, btn), "second AXPress on 'Toggle sidebar' failed" restored = _wait_until(lambda: _sidebar_texts(ax, win), lambda v: len(v) == 6, timeout=4.0) assert kit.rb_value(restored, SIDEBAR_LABELS), \ f"sidebar restored as {restored!r}, expected {SIDEBAR_LABELS!r}"
# ═════════════════════════════════════���════════════════════════════════════════════════# B5 / B6 / B7 / B8 — the Add station / Add group sheets (OK button is NEVER pressed)# ══════════════════════════════════════════════════════════════════════════════════════
class TestStationSheetButtons:
@pytest.mark.rb(depth=2, jump_kind="reach", expect="a modal 'To add a station, fill out the following " "information:' sheet with Title:/Url: fields and a DISABLED " "'Add station' button") def test_add_station_button_opens_sheet(self, ax): win = rbr.rb_enter_stations_window(ax) assert win is not None, "the Stations window never appeared"
before = kit.rb_showing(ax) sheet = rbr.rb_reach_add_station_sheet(ax, win) assert sheet is not None, "'Add station' did not open a sheet" after = kit.rb_showing(ax) try: assert kit.rb_reach(before, after, target=ADD_STATION_PROMPT), \ "the Add-station sheet's prompt never appeared in the AX tree"
labels = rbr.label_values(ax, sheet.id) assert ADD_STATION_PROMPT in labels, f"sheet labels are {labels!r}" assert "Title:" in labels and "Url:" in labels, f"sheet labels are {labels!r}" assert len(ax.find(role="text_field", root_id=sheet.id, max_results=6)) >= 2
ok_btn = _sheet_button(ax, sheet, ["add station", "add"]) assert ok_btn is not None, "the sheet has no 'Add station' button" assert not _enabled(ax, ok_btn), \ "'Add station' must start DISABLED while both fields are empty" assert _sheet_button(ax, sheet, ["cancel"]) is not None, "no Cancel button"
rbr.screenshot_assert( "buttons_add_station_sheet", "A modal sheet is layered over Radiola's Stations window reading " "'To add a station, fill out the following information:' with empty " "'Title:' and 'Url:' text fields, a greyed-out (disabled) 'Add station' " "button and an enabled 'Cancel' button; the 3 Radio Caroline station " "rows and the sidebar are dimmed behind the sheet.") finally: rbr.sheet_cancel(ax, sheet)
assert not rbr.sheet_present(ax), "the sheet stayed open after Cancel" rows = rbr.station_rows(ax, win) assert len(rows) == 3, f"the station list must be untouched, got {rows!r}"
@pytest.mark.rb(depth=2, jump_kind="reach", expect="a modal 'To add a group, fill out the following " "information:' sheet with one Title: field and a DISABLED " "'Add group' button") def test_add_group_button_opens_sheet(self, ax): win = rbr.rb_enter_stations_window(ax) assert win is not None, "the Stations window never appeared"
before = kit.rb_showing(ax) sheet = rbr.rb_reach_add_group_sheet(ax, win) assert sheet is not None, "'Add group' did not open a sheet" after = kit.rb_showing(ax) try: assert kit.rb_reach(before, after, target=ADD_GROUP_PROMPT), \ "the Add-group sheet's prompt never appeared in the AX tree"
labels = rbr.label_values(ax, sheet.id) assert ADD_GROUP_PROMPT in labels, f"sheet labels are {labels!r}" assert "Title:" in labels, f"sheet labels are {labels!r}" assert "Url:" not in labels, "the group sheet must not offer a Url field" assert len(ax.find(role="text_field", root_id=sheet.id, max_results=6)) == 1
ok = _sheet_button(ax, sheet, ["add group", "add"]) assert ok is not None, "the sheet has no 'Add group' button" assert not _enabled(ax, ok), \ "'Add group' must start DISABLED while the title is empty" assert _sheet_button(ax, sheet, ["cancel"]) is not None, "no Cancel button" finally: rbr.sheet_cancel(ax, sheet)
assert not rbr.sheet_present(ax), "the sheet stayed open after Cancel" rows = rbr.station_rows(ax, win) assert len(rows) == 3, f"the station list must be untouched, got {rows!r}"
@pytest.mark.rb(depth=2, jump_kind="transition", expect="the sheet's 'Add station' button goes AXEnabled False -> True " "once both Title and Url are typed") def test_add_station_ok_button_enables_when_both_fields_filled(self, ax): win = rbr.rb_enter_stations_window(ax) assert win is not None, "the Stations window never appeared"
sheet = rbr.rb_reach_add_station_sheet(ax, win) assert sheet is not None, "'Add station' did not open a sheet" try: fields = ax.find(role="text_field", root_id=sheet.id, max_results=6) assert len(fields) >= 2, f"expected Title+Url fields, found {len(fields)}"
ok = _sheet_button(ax, sheet, ["add station", "add", "ok"]) assert ok is not None, "the sheet has no 'Add station' button"
before = _enabled(ax, ok) assert before is False, "'Add station' should be disabled with empty fields"
# real keystrokes: an AXValue write never runs controlTextDidChange: assert rbr.type_chars(ax, fields[0], "zz"), "could not type into a sheet field" after_one = _enabled(ax, ok) assert after_one is False, \ "'Add station' must stay disabled while the other field is empty"
assert rbr.type_chars(ax, fields[1], "z.z"), "could not type into a sheet field" after = _wait_until(lambda: _enabled(ax, ok), lambda v: v is True, timeout=3.0)
assert kit.rb_flip(before, after), \ f"'Add station' enablement never flipped: {before} -> {after}" assert after is True # the OK button is deliberately NEVER pressed — it would persist a station. finally: rbr.sheet_cancel(ax, sheet)
assert not rbr.sheet_present(ax), "the sheet stayed open after Cancel" rows = rbr.station_rows(ax, win) assert len(rows) == 3, f"nothing must have been added, got {rows!r}"
@pytest.mark.rb(depth=2, jump_kind="transition", expect="the sheet's Cancel button dismisses the sheet (present " "True -> False) leaving the 3 default stations") def test_sheet_cancel_button_dismisses_sheet(self, ax): win = rbr.rb_enter_stations_window(ax) assert win is not None, "the Stations window never appeared"
sheet = rbr.rb_reach_add_station_sheet(ax, win) assert sheet is not None, "'Add station' did not open a sheet"
before = rbr.sheet_present(ax) assert before is True, "no sheet was reported after 'Add station'"
cancel = _sheet_button(ax, sheet, ["cancel"]) assert cancel is not None, "the sheet has no Cancel button" assert rbr.press(ax, cancel), "AXPress on Cancel failed" time.sleep(0.6)
after = _wait_until(lambda: rbr.sheet_present(ax), lambda v: v is False, timeout=3.0) assert kit.rb_flip(before, after), f"the sheet survived Cancel: {after}" assert after is False
rows = rbr.station_rows(ax, win) assert len(rows) == 3, f"nothing must have been added, got {rows!r}" assert [t for t, _u in rows] == list(rbr.DEFAULT_STATIONS), \ f"the station list changed: {rows!r}"
# ══════════════════════════════════════════════════════════════════════════════════════# B9 — a station row's "Context menu" (…) button# ══════════════════════════════════════════════════════════════════════════════════════
class TestRowContextMenuButton:
@pytest.mark.rb(depth=2, jump_kind="reach", expect="the row's context menu with exactly 'Copy station title' " "and 'Copy station URL'") def test_context_menu_button_shows_copy_items(self, ax): win = rbr.rb_enter_stations_window(ax) assert win is not None, "the Stations window never appeared"
rows = rbr.station_rows(ax, win) assert len(rows) == 3, f"expected the 3 default station rows, got {rows!r}" ctx = rbr.station_context_buttons(ax, win) assert len(ctx) == len(rows), \ f"expected one 'Context menu' button per station row, got {len(ctx)}" assert "AXShowMenu" in (ctx[0].actions or []), \ f"the context button's actions are {ctx[0].actions!r}, expected AXShowMenu"
before = kit.rb_showing(ax) menu = rbr.rb_reach_row_context_menu(ax, 0, win) try: assert menu is not None, "AXShowMenu on the row's '…' button opened no menu" after = kit.rb_showing(ax) names = rbr.menu_item_names(ax, menu) assert kit.rb_reach(before, after, target="Copy station title"), \ "the context menu's items never appeared in the AX tree" assert [n for n in names if n] == CONTEXT_MENU_ITEMS, \ f"context menu items are {names!r}" finally: rbr.close_all_menus(ax)
# ══════════════════════════════════��═══════════════════════════════════════════════════# B10-B13 (+ B16 existence-only) — the preferences toolbar tab buttons# ══════════════════════════════════════════════════════════════════════════════════════
class TestPreferencesToolbarButtons:
@pytest.mark.rb(depth=1, jump_kind="value", expect="prefs window title becomes 'Appearance' and the page shows " "the 4 Appearance checkboxes") def test_appearance_tab_button_switches_page(self, ax): base = rbr.rb_enter_settings_window(ax) assert base is not None, "the preferences window never appeared" assert rbr.settings_tab_title(ax) == "Controls", \ "preferences should open on the 'Controls' tab" assert not (APPEARANCE_CHECKBOXES & set(rbr.checkboxes(ax, base.id))), \ "the Appearance checkboxes must not be on the Controls page"
win = rbr.rb_enter_settings_tab(ax, "Appearance") assert win is not None, "the 'Appearance' toolbar button did not switch tab"
title = _wait_until(lambda: rbr.settings_tab_title(ax), lambda t: t == "Appearance", timeout=4.0) assert kit.rb_value(title, "Appearance"), \ f"prefs window title is {title!r}, expected 'Appearance'"
names = set(rbr.checkboxes(ax, win.id).keys()) assert len(names) == 4, f"expected 4 Appearance checkboxes, got {sorted(names)!r}" assert APPEARANCE_CHECKBOXES <= names, \ f"missing Appearance checkboxes: {sorted(APPEARANCE_CHECKBOXES - names)!r}"
rbr.screenshot_assert( "buttons_prefs_appearance_tab", "Radiola's preferences window titled 'Appearance' after pressing the " "Appearance toolbar button: a 5-icon toolbar across the top " "(Controls, Appearance, Audio, Startup, Updates) with Appearance " "highlighted, a 'Show groups in favorites:' dropdown reading 'as a flat " "list', and four checkboxes — 'Show the volume control in the menu', " "'Show the mute item in the menu', 'Show the \"Copy song title and artist\" " "item in the menu' (all unchecked) and 'Show a tooltip with the " "radiostation and song' (checked).")
@pytest.mark.rb(depth=1, jump_kind="value", expect="prefs window title becomes 'Startup' and the page shows the " "'Play last station on startup' checkbox") def test_startup_tab_button_switches_page(self, ax): base = rbr.rb_enter_settings_window(ax) assert base is not None, "the preferences window never appeared" title_before = rbr.settings_tab_title(ax) assert title_before == "Controls"
win = rbr.rb_enter_settings_tab(ax, "Startup") assert win is not None, "the 'Startup' toolbar button did not switch tab"
title = _wait_until(lambda: rbr.settings_tab_title(ax), lambda t: t == "Startup", timeout=4.0) assert kit.rb_value(title, "Startup"), \ f"prefs window title is {title!r}, expected 'Startup'"
names = list(rbr.checkboxes(ax, win.id).keys()) assert names == ["Play last station on startup"], \ f"Startup page checkboxes are {names!r}"
@pytest.mark.rb(depth=1, jump_kind="value", expect="prefs window title becomes 'Updates' and the page shows the " "'Check for Updates now' button + 'Automatically check for " "updates' checkbox") def test_updates_tab_button_switches_page(self, ax): base = rbr.rb_enter_settings_window(ax) assert base is not None, "the preferences window never appeared"
win = rbr.rb_enter_settings_tab(ax, "Updates") assert win is not None, "the 'Updates' toolbar button did not switch tab"
title = _wait_until(lambda: rbr.settings_tab_title(ax), lambda t: t == "Updates", timeout=4.0) assert kit.rb_value(title, "Updates"), \ f"prefs window title is {title!r}, expected 'Updates'"
# existence only — pressing 'Check for Updates now' opens Sparkle's network panel btn_names = set(rbr.buttons(ax, win.id).keys()) assert "Check for Updates now" in btn_names, f"Updates buttons are {btn_names!r}" cb_names = list(rbr.checkboxes(ax, win.id).keys()) assert cb_names == ["Automatically check for updates"], \ f"Updates page checkboxes are {cb_names!r}"
@pytest.mark.rb(depth=1, jump_kind="value", expect="prefs window title returns to 'Controls' and the page shows " "its 6 mouse/media popups and the mouse-button labels") def test_controls_tab_button_switches_page_back(self, ax): away = rbr.rb_enter_settings_tab(ax, "Appearance") assert away is not None, "could not leave the Controls tab first" assert _wait_until(lambda: rbr.settings_tab_title(ax), lambda t: t == "Appearance", timeout=4.0) == "Appearance"
win = rbr.rb_enter_settings_tab(ax, "Controls") assert win is not None, "the 'Controls' toolbar button did not switch tab"
title = _wait_until(lambda: rbr.settings_tab_title(ax), lambda t: t == "Controls", timeout=4.0) assert kit.rb_value(title, "Controls"), \ f"prefs window title is {title!r}, expected 'Controls'"
popups = ax.find(role="popup", root_id=win.id, max_results=20) assert len(popups) == 6, f"expected 6 Controls popups, found {len(popups)}" popup_values = sorted(str(rbr._val(ax, p.id) or "") for p in popups) assert popup_values == CONTROLS_POPUP_VALUES, \ f"Controls popup values are {popup_values!r}, expected {CONTROLS_POPUP_VALUES!r}"
labels = rbr.label_values(ax, win.id) for expected in CONTROLS_LABELS: assert expected in labels, f"missing Controls label {expected!r} in {labels!r}"
@pytest.mark.rb(depth=1, jump_kind="value", expect="the prefs toolbar exposes all five tab buttons " "Appearance/Audio/Controls/Startup/Updates") def test_prefs_toolbar_exposes_five_tab_buttons_including_audio(self, ax): win = rbr.rb_enter_settings_window(ax) assert win is not None, "the preferences window never appeared"
tabs = rbr.settings_tab_buttons(ax, win) known = set(rbr.SETTINGS_TABS_SAFE) | {rbr.SETTINGS_TAB_UNSAFE} observed = sorted(n for n in tabs if n in known) assert kit.rb_value(observed, ALL_SETTINGS_TABS), \ f"prefs toolbar tabs are {observed!r}, expected {ALL_SETTINGS_TABS!r}"
# 'Audio' is asserted to EXIST only: selecting it traps in AudioSytstem.devices() # on a device-less machine and kills the app, so it is never pressed here. audio = tabs.get(rbr.SETTINGS_TAB_UNSAFE) assert audio is not None, "the 'Audio' tab button is missing from the toolbar" assert "AXPress" in (audio.actions or []), \ "the 'Audio' tab button should be a pressable toolbar button" assert rbr.settings_tab_title(ax) == "Controls", \ "enumerating the tabs must not change the selected tab"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629"""COMPUTATION lane for Radiola (macOS status-bar radio player).
Radiola is NOT a calculator: it has no arithmetic UI. Its deterministicinput -> output mappings (recorded in recon.md `## COMPUTATION`) are:
* volume arithmetic `volume up` = +0.05, `audio output volume off` = -0.05, fresh-launch default 0.5, clamped to [0, 1], stored as a float32 (so every comparison is done on round(v, 3)). * `set_value(slider,x)` the slider's AXValue is settable and reads x back. * mute predicate mute ON => slider / volume up / volume down all AXEnabled False mute OFF => all three AXEnabled True again. * clipboard mapping row i context menu -> `Copy station title` / `Copy station URL` puts exactly that row's title / url text-field value on the pasteboard. * station-switch map status-menu station item i -> play-item station label == that item's title, song label == "Connecting...", status-item tooltip == title + "\\n" + 28x U+23AF + "\\nConnecting...". * OK-enable predicate the Add-station sheet's OK button is enabled IFF BOTH the Title and the Url field are non-empty. * tab -> title map selecting preferences tab X makes the window's AXTitle == X.
Every expected value below is COMPUTED here from that recorded mapping (not re-readfrom the app) and asserted through `kit.rb_value`.
Constraints honoured (see recon `## APP`): * the plain `ax` fixture only — never `ax_with_reset` (its ensure_panel_open blind- presses every menu-bar item and leaves stray system menus open), * the preferences `Audio` tab is NEVER selected (it crashes the reference app here), * `Remove station`, a sheet's `Add station`/`Add group` OK button, `Check for Updates now`, `Quit`/`Quit Radiola`, `Radiola Help` and Export/Import are NEVER pressed; every sheet that is opened is Cancelled again."""
import time
import pytest
import rb_radiola as rbrimport rb_testgen_kit as kit
# ── the recorded arithmetic constants ────────────────────────────────────────────────VOL_DEFAULT = 0.5 # fresh launch (defaults deleted) always starts hereVOL_STEP = 0.05 # +/- per press of volume up / audio output volume offVOL_MAX = 1.0 # clamp ceilingVOL_MIN = 0.0 # clamp floorND = 3 # rounding used for the reference's float32 slider (~1e-3)
# The status-item tooltip's separator line: 28x U+23AF HORIZONTAL LINE EXTENSION.TOOLTIP_SEP = "⎯" * 28
SENTINEL = "SENTINEL" # seeded into the clipboard so a no-op copy is detectable
# ── small observation helpers (no navigation happens in here) ────────────────────────
def _num(v): try: return float(v) except (TypeError, ValueError): return None
def _v2(x): """A volume as a fixed 2-decimal string.
`kit.rb_value` falls back to a SUBSTRING match, and "0.5" IS a substring of "0.55" — so a dead volume-down button could pass a raw-float comparison vacuously. Comparing the fixed-width forms ("0.50" vs "0.55") removes that hole while keeping the float32 tolerance (the values are rounded to 1e-3 first). """ return None if x is None else f"{x:.2f}"
def _vol(ax, slider): """Rounded AXValue of the volume slider (float32 on the reference -> round to 1e-3).""" if slider is None: return None v = _num(ax.get(slider.id, ["AXValue"]).get("AXValue")) return None if v is None else round(v, ND)
def _enabled(ax, el): if el is None: return None return bool(ax.get(el.id, ["AXEnabled"]).get("AXEnabled"))
def _sval(ax, el): """AXValue of a label / text field as a string ('' when the value is empty).""" if el is None: return None v = ax.get(el.id, ["AXValue"]).get("AXValue") return "" if v is None else str(v)
def _volume_button(ax, win, direction): """The +/- volume button, located by its visible name / AXHelp.
Strict keywords first ("volume up"/"increase", "volume off"/"volume down"/"decrease") because a bare "up" substring also matches "Add gro-up-"; anything naming a station / group / add action is skipped outright. Falls back to the shared helper. """ want = ("volume up", "increase volume", "increase") if direction == "up" else \ ("volume off", "volume down", "decrease volume", "decrease") for b in ax.find(role="button", root_id=win.id, max_results=40): n = (b.name or "").lower() h = str(ax.get(b.id, ["AXHelp"]).get("AXHelp") or "").lower() blob = n + " " + h if any(bad in blob for bad in ("add", "group", "station", "remove", "sidebar")): continue if direction == "down" and "mute" in blob: continue if any(k in blob for k in want): return b return rbr.stations_volume_button(ax, win, direction)
def _volume_controls(ax, win): """(slider, volume-up button, volume-down button) of the Stations toolbar.
Located by role + visible name / AXHelp, never by index or tree path, so a recreation built on a different framework or hierarchy is driven identically. """ return (rbr.stations_volume_slider(ax, win), _volume_button(ax, win, "up"), _volume_button(ax, win, "down"))
def _volume_enablement(ax, win, prev): """((slider, up, down) AXEnabled triple, refreshed handles).
The three widgets are re-located after every toggle (a SwiftUI recreation may rebuild them), falling back to the handles we already hold when a re-find comes up empty. """ fresh = _volume_controls(ax, win) els = tuple(new or old for new, old in zip(fresh, prev)) return tuple(_enabled(ax, el) for el in els), els
def _sheet_ok_button(ax, sheet): """The sheet's OK button ('Add station') — NEVER pressed, only read.""" btns = ax.find(role="button", root_id=sheet.id, max_results=12) ok = rbr.find_by_keywords(btns, ["add station", "add", "ok", "确定"]) if ok is not None: return ok for b in btns: if "cancel" not in (b.name or "").lower(): return b return None
def _sheet_fields(ax, sheet): """(Title field, Url field) of the Add-station sheet.
Prefer a semantic hint (AXTitle / AXDescription / AXPlaceholderValue / AXHelp naming the url); the reference exposes both fields unnamed, so fall back to the sheet's documented field order (Title: then Url:). """ tfs = ax.find(role="text_field", root_id=sheet.id, max_results=6) if len(tfs) < 2: return (tfs[0] if tfs else None, None) url_idx = None for i, tf in enumerate(tfs): d = ax.get(tf.id, ["AXTitle", "AXDescription", "AXPlaceholderValue", "AXHelp"]) blob = " ".join(str(v or "") for v in d.values()).lower() if "url" in blob or "地址" in blob or "链接" in blob: url_idx = i break if url_idx is None: return (tfs[0], tfs[1]) return (tfs[1 if url_idx == 0 else 0], tfs[url_idx])
def _expected_tooltip(station_title): """The status-item AXHelp the reference builds while connecting to a station.""" return station_title + "\n" + TOOLTIP_SEP + "\n" + rbr.CONNECTING_TEXT
# ── 1. volume arithmetic (Stations window = depth 1) ─────────────────────────────────
class TestVolumeArithmetic: """The volume slider is Radiola's only arithmetic surface: +/-0.05 per press from a 0.5 fresh-launch default, clamped to [0, 1]."""
@pytest.mark.rb(depth=1, jump_kind="value", expect="volume slider reads 0.55 after ONE 'volume up' press (0.5 + 0.05)") def test_volume_up_once_is_0_55(self, ax): win = rbr.rb_enter_stations_window(ax) assert win is not None, "Stations window did not open (status menu -> 'Open Radiola')" slider, up, _down = _volume_controls(ax, win) assert slider is not None, "no volume slider in the Stations window" assert up is not None, "no 'volume up' / 'Increase volume' button in the Stations window"
start = _vol(ax, slider) assert start == VOL_DEFAULT, f"fresh launch volume should be {VOL_DEFAULT}, got {start}"
rbr.press(ax, up) time.sleep(0.35) observed = _vol(ax, slider) expected = round(VOL_DEFAULT + VOL_STEP, ND) # 0.5 + 0.05 = 0.55 assert kit.rb_value(_v2(observed), _v2(expected)), ( f"one 'volume up' press should give {expected}, slider reads {observed}")
@pytest.mark.rb(depth=1, jump_kind="value", expect="volume slider reads 0.6 after TWO 'volume up' presses (0.5 + 2*0.05)") def test_volume_up_twice_is_0_60(self, ax): win = rbr.rb_enter_stations_window(ax) assert win is not None, "Stations window did not open (status menu -> 'Open Radiola')" slider, up, _down = _volume_controls(ax, win) assert slider is not None and up is not None, "volume slider / 'volume up' button missing"
start = _vol(ax, slider) assert start == VOL_DEFAULT, f"fresh launch volume should be {VOL_DEFAULT}, got {start}"
rbr.press(ax, up) time.sleep(0.35) mid = _vol(ax, slider) rbr.press(ax, up) time.sleep(0.35) observed = _vol(ax, slider)
rbr.screenshot_assert( "computation_volume_up_twice", "Radiola's 'Stations' window is open: a left sidebar listing My lists / My " "stations / Radio browser / By tag / By name / By country, and three 'Radio " "Caroline' rows (each with a yellow star and a '...' button) with Add station / " "Add group / Remove station along the bottom. In the toolbar the volume slider's " "knob has been raised from the middle to about 60% of the track (value 0.6 after " "two 'volume up' presses), sitting between the speaker-off button on its left and " "the volume-up button on its right; the play triangle and 'Radio Caroline' are " "shown to the left of the slider.")
expected_mid = round(VOL_DEFAULT + VOL_STEP, ND) # 0.55 expected = round(VOL_DEFAULT + 2 * VOL_STEP, ND) # 0.60 assert mid == expected_mid, ( f"after the FIRST press the slider should read {expected_mid}, got {mid}") assert kit.rb_value(_v2(observed), _v2(expected)), ( f"two 'volume up' presses should give {expected}, slider reads {observed}")
@pytest.mark.rb(depth=1, jump_kind="value", expect="volume up then volume down returns the slider to 0.5") def test_volume_up_then_down_returns_to_0_50(self, ax): win = rbr.rb_enter_stations_window(ax) assert win is not None, "Stations window did not open (status menu -> 'Open Radiola')" slider, up, down = _volume_controls(ax, win) assert slider is not None and up is not None, "volume slider / 'volume up' button missing" assert down is not None, "no 'audio output volume off' / 'Decrease volume' button"
start = _vol(ax, slider) assert start == VOL_DEFAULT, f"fresh launch volume should be {VOL_DEFAULT}, got {start}"
rbr.press(ax, up) time.sleep(0.35) mid = _vol(ax, slider) expected_mid = round(VOL_DEFAULT + VOL_STEP, ND) # 0.55 assert mid == expected_mid, ( f"'volume up' should raise 0.5 to {expected_mid}, slider reads {mid} " "(a no-op button would make the round trip pass vacuously)")
rbr.press(ax, down) time.sleep(0.35) observed = _vol(ax, slider) expected = round(VOL_DEFAULT + VOL_STEP - VOL_STEP, ND) # 0.5 assert kit.rb_value(_v2(observed), _v2(expected)), ( f"up then down should return to {expected}, slider reads {observed}")
@pytest.mark.rb(depth=1, jump_kind="value", expect="setting the slider's AXValue to 0.8 reads back 0.8") def test_volume_set_value_reads_back_0_80(self, ax): win = rbr.rb_enter_stations_window(ax) assert win is not None, "Stations window did not open (status menu -> 'Open Radiola')" slider, _up, _down = _volume_controls(ax, win) assert slider is not None, "no volume slider in the Stations window"
start = _vol(ax, slider) assert start == VOL_DEFAULT, f"fresh launch volume should be {VOL_DEFAULT}, got {start}"
ax.set_value(slider.id, 0.8) time.sleep(0.4) observed = _vol(ax, slider) expected = round(0.8, ND) assert kit.rb_value(_v2(observed), _v2(expected)), ( f"AXValue 0.8 should read back as {expected}, slider reads {observed}")
@pytest.mark.rb(depth=1, jump_kind="value", expect="12 'volume up' presses clamp the slider at 1.0 and never exceed it") def test_volume_clamps_at_max_1_0(self, ax): win = rbr.rb_enter_stations_window(ax) assert win is not None, "Stations window did not open (status menu -> 'Open Radiola')" slider, up, _down = _volume_controls(ax, win) assert slider is not None and up is not None, "volume slider / 'volume up' button missing"
start = _vol(ax, slider) assert start == VOL_DEFAULT, f"fresh launch volume should be {VOL_DEFAULT}, got {start}"
seen = [] for _ in range(12): # 0.5 + 12*0.05 = 1.10 -> must clamp at 1.0 rbr.press(ax, up) time.sleep(0.3) seen.append(_vol(ax, slider)) assert all(v is not None for v in seen), f"unreadable slider values: {seen}"
observed = (round(max(seen), ND), round(seen[-1], ND)) expected = (VOL_MAX, VOL_MAX) assert kit.rb_value((_v2(observed[0]), _v2(observed[1])), (_v2(expected[0]), _v2(expected[1]))), ( f"volume should saturate at {VOL_MAX} (max seen, final) = {observed}; " f"trace={seen}")
@pytest.mark.rb(depth=1, jump_kind="value", expect="11 'audio output volume off' presses clamp the slider at 0.0") def test_volume_clamps_at_min_0_0(self, ax): win = rbr.rb_enter_stations_window(ax) assert win is not None, "Stations window did not open (status menu -> 'Open Radiola')" slider, _up, down = _volume_controls(ax, win) assert slider is not None, "no volume slider in the Stations window" assert down is not None, "no 'audio output volume off' / 'Decrease volume' button"
start = _vol(ax, slider) assert start == VOL_DEFAULT, f"fresh launch volume should be {VOL_DEFAULT}, got {start}"
seen = [] for _ in range(11): # 0.5 - 11*0.05 = -0.05 -> must clamp at 0.0 rbr.press(ax, down) time.sleep(0.3) seen.append(_vol(ax, slider)) assert all(v is not None for v in seen), f"unreadable slider values: {seen}"
observed = (round(min(seen), ND), round(seen[-1], ND)) expected = (VOL_MIN, VOL_MIN) assert kit.rb_value((_v2(observed[0]), _v2(observed[1])), (_v2(expected[0]), _v2(expected[1]))), ( f"volume should floor at {VOL_MIN} (min seen, final) = {observed}; trace={seen}")
# ── 2. mute -> enablement matrix (Stations window = depth 1) ─────────────────────────
class TestMuteEnablement: """Muting is a predicate over three widgets: it disables the slider and both volume buttons; unmuting re-enables exactly those three."""
@pytest.mark.rb(depth=1, jump_kind="value", expect="mute ON -> (slider, volume up, volume down) AXEnabled " "(False, False, False); mute OFF -> (True, True, True)") def test_mute_toggles_volume_control_enablement(self, ax): win = rbr.rb_enter_stations_window(ax) assert win is not None, "Stations window did not open (status menu -> 'Open Radiola')" mute = rbr.stations_mute_checkbox(ax, win) assert mute is not None, "no mute checkbox ('audio output mute' / AXHelp 'Mute')" els = _volume_controls(ax, win) assert all(e is not None for e in els), ( "volume slider / volume up / volume down not all present")
baseline = tuple(_enabled(ax, e) for e in els) assert baseline == (True, True, True), ( f"an unmuted fresh launch must have all volume controls enabled, got {baseline}")
rbr.press(ax, mute) # mute ON time.sleep(0.7) muted, els = _volume_enablement(ax, win, els)
rbr.screenshot_assert( "computation_mute_disables_volume", "Radiola's 'Stations' window is open and the audio is MUTED: the toolbar's mute " "control now shows a struck-through / slashed speaker icon, and the volume slider " "together with the small volume-down and volume-up buttons on either side of it " "are greyed out (dimmed, non-interactive). The rest of the window is unchanged: " "the sidebar on the left, the play triangle and 'Radio Caroline' in the toolbar, " "three 'Radio Caroline' station rows, and Add station / Add group / Remove station " "at the bottom.")
mute = rbr.stations_mute_checkbox(ax, win) or mute rbr.press(ax, mute) # mute OFF again (restore the default) time.sleep(0.7) unmuted, _els = _volume_enablement(ax, win, els)
observed = (muted, unmuted) expected = ((False, False, False), (True, True, True)) assert kit.rb_value(observed, expected), ( f"mute enablement matrix should be {expected}, observed {observed}")
# ── 3. clipboard mapping (Stations window + row context menu = depth 2) ──────────────
class TestClipboardMapping: """Each station row's '...' context menu maps `Copy station title` / `Copy station URL` onto exactly that row's title / url text-field value."""
@pytest.mark.rb(depth=2, jump_kind="value", expect="row 0 ctx -> 'Copy station title' puts 'Radio Caroline' on the clipboard") def test_copy_station_title_row0(self, ax): rbr.set_clipboard(SENTINEL) win = rbr.rb_enter_stations_window(ax) assert win is not None, "Stations window did not open (status menu -> 'Open Radiola')" rows = rbr.station_rows(ax, win) assert len(rows) >= 1, f"expected 3 station rows, got {rows}" expected = rbr.STATION_1 assert rows[0][0] == expected, f"row 0's title field should be {expected!r}, got {rows[0][0]!r}"
menu = rbr.rb_reach_row_context_menu(ax, 0, win) assert menu is not None, "row 0's 'Context menu' button did not open a menu" item = rbr.menu_item_by_name(ax, menu, "Copy station title") assert item is not None, f"context menu items are {rbr.menu_item_names(ax, menu)}" rbr.press(ax, item) time.sleep(0.8) rbr.close_all_menus(ax)
clip = rbr.clipboard().strip() assert clip != SENTINEL, "'Copy station title' left the clipboard at SENTINEL (no-op)" assert clip == expected and kit.rb_value(clip, expected), ( f"clipboard should be {expected!r}, got {clip!r}")
@pytest.mark.rb(depth=2, jump_kind="value", expect="row 0 ctx -> 'Copy station URL' puts " "'http://sc3.radiocaroline.net:8030' on the clipboard") def test_copy_station_url_row0(self, ax): rbr.set_clipboard(SENTINEL) win = rbr.rb_enter_stations_window(ax) assert win is not None, "Stations window did not open (status menu -> 'Open Radiola')" rows = rbr.station_rows(ax, win) assert len(rows) >= 1, f"expected 3 station rows, got {rows}" expected = rbr.STATION_1_URL assert rows[0][1] == expected, f"row 0's url field should be {expected!r}, got {rows[0][1]!r}"
menu = rbr.rb_reach_row_context_menu(ax, 0, win) assert menu is not None, "row 0's 'Context menu' button did not open a menu" item = rbr.menu_item_by_name(ax, menu, "Copy station URL") assert item is not None, f"context menu items are {rbr.menu_item_names(ax, menu)}" rbr.press(ax, item) time.sleep(0.8) rbr.close_all_menus(ax)
clip = rbr.clipboard().strip() assert clip != SENTINEL, "'Copy station URL' left the clipboard at SENTINEL (no-op)" assert clip == expected and kit.rb_value(clip, expected), ( f"clipboard should be {expected!r}, got {clip!r}")
@pytest.mark.rb(depth=2, jump_kind="value", expect="row 1 ctx -> 'Copy station title' puts " "\"Radio Caroline 319 Gold [ Hits from '60-'70 ]\" on the clipboard") def test_copy_station_title_row1(self, ax): rbr.set_clipboard(SENTINEL) win = rbr.rb_enter_stations_window(ax) assert win is not None, "Stations window did not open (status menu -> 'Open Radiola')" rows = rbr.station_rows(ax, win) assert len(rows) >= 2, f"expected 3 station rows, got {rows}" expected = rbr.STATION_2 assert rows[1][0] == expected, f"row 1's title field should be {expected!r}, got {rows[1][0]!r}"
menu = rbr.rb_reach_row_context_menu(ax, 1, win) assert menu is not None, "row 1's 'Context menu' button did not open a menu" item = rbr.menu_item_by_name(ax, menu, "Copy station title") assert item is not None, f"context menu items are {rbr.menu_item_names(ax, menu)}" rbr.press(ax, item) time.sleep(0.8) rbr.close_all_menus(ax)
clip = rbr.clipboard().strip() assert clip != SENTINEL, "'Copy station title' left the clipboard at SENTINEL (no-op)" assert clip == expected and kit.rb_value(clip, expected), ( f"clipboard should be {expected!r}, got {clip!r}")
@pytest.mark.rb(depth=2, jump_kind="value", expect="row 1 ctx -> 'Copy station URL' puts " "'http://www.rcgoldserver.eu:8192' on the clipboard") def test_copy_station_url_row1(self, ax): rbr.set_clipboard(SENTINEL) win = rbr.rb_enter_stations_window(ax) assert win is not None, "Stations window did not open (status menu -> 'Open Radiola')" rows = rbr.station_rows(ax, win) assert len(rows) >= 2, f"expected 3 station rows, got {rows}" expected = rbr.STATION_2_URL assert rows[1][1] == expected, f"row 1's url field should be {expected!r}, got {rows[1][1]!r}"
menu = rbr.rb_reach_row_context_menu(ax, 1, win) assert menu is not None, "row 1's 'Context menu' button did not open a menu" item = rbr.menu_item_by_name(ax, menu, "Copy station URL") assert item is not None, f"context menu items are {rbr.menu_item_names(ax, menu)}" rbr.press(ax, item) time.sleep(0.8) rbr.close_all_menus(ax)
clip = rbr.clipboard().strip() assert clip != SENTINEL, "'Copy station URL' left the clipboard at SENTINEL (no-op)" assert clip == expected and kit.rb_value(clip, expected), ( f"clipboard should be {expected!r}, got {clip!r}")
# ── 4. station-switch mapping (status menu -> station -> reopened menu = depth 2) ────
class TestStationSwitchMapping: """Picking status-menu station item i recomputes three observable strings: the play item's station label, its song label, and the status item's tooltip."""
@pytest.mark.rb(depth=2, jump_kind="value", expect="picking station 2 gives play-item station " "\"Radio Caroline 319 Gold [ Hits from '60-'70 ]\", song " "'Connecting...' and tooltip title+28x U+23AF+'Connecting...'") def test_station2_sets_play_item_labels_and_tooltip(self, ax): menu = rbr.rb_reach_status_menu(ax) assert menu is not None, "the status item did not open its menu" names = rbr.status_menu_favorite_names(ax, menu) assert len(names) >= 2, f"expected 3 favourite station items, got {names}" target = names[1] assert target == rbr.STATION_2, f"station item 1 should be {rbr.STATION_2!r}, got {target!r}" item = rbr.status_menu_item(ax, menu, target) assert item is not None, f"menu item {target!r} not found"
rbr.press(ax, item) time.sleep(1.8) tooltip = rbr.status_item_tooltip(ax)
menu2 = rbr.rb_reach_status_menu(ax) assert menu2 is not None, "the status menu did not reopen after switching stations" play = rbr.status_menu_play_item(ax, menu2) station_label = _sval(ax, play["station"]) song_label = _sval(ax, play["song"]) rbr.close_all_menus(ax)
observed = (station_label, song_label, tooltip) expected = (target, rbr.CONNECTING_TEXT, _expected_tooltip(target)) assert kit.rb_value(observed, expected), ( f"(station label, song label, tooltip) should be {expected!r}, observed {observed!r}")
@pytest.mark.rb(depth=2, jump_kind="value", expect="picking station 3 gives play-item station " "'Radio Caroline 259 Gold [ Happy Rock & Album Station ]' " "and song 'Connecting...'") def test_station3_sets_play_item_labels(self, ax): menu = rbr.rb_reach_status_menu(ax) assert menu is not None, "the status item did not open its menu" names = rbr.status_menu_favorite_names(ax, menu) assert len(names) >= 3, f"expected 3 favourite station items, got {names}" target = names[2] assert target == rbr.STATION_3, f"station item 2 should be {rbr.STATION_3!r}, got {target!r}" item = rbr.status_menu_item(ax, menu, target) assert item is not None, f"menu item {target!r} not found"
rbr.press(ax, item) time.sleep(1.8)
menu2 = rbr.rb_reach_status_menu(ax) assert menu2 is not None, "the status menu did not reopen after switching stations" play = rbr.status_menu_play_item(ax, menu2) station_label = _sval(ax, play["station"]) song_label = _sval(ax, play["song"]) icon_name = play["icon"].name if play["icon"] is not None else None rbr.close_all_menus(ax)
observed = (station_label, song_label) expected = (target, rbr.CONNECTING_TEXT) assert kit.rb_value(observed, expected), ( f"(station label, song label) should be {expected!r}, observed {observed!r} " f"(play icon={icon_name!r})")
# ── 5. Add-station OK-enable predicate (Stations window + sheet = depth 2) ───────────
class TestAddStationOkPredicate: """The Add-station sheet's OK button is enabled IFF both fields are non-empty. The OK button is only READ, never pressed; the sheet is always Cancelled."""
@pytest.mark.rb(depth=2, jump_kind="value", expect="sheet OK AXEnabled (empty,empty)=False, (title,empty)=False, " "(title,url)=True; Cancel leaves exactly 3 station rows") def test_add_station_ok_enabled_iff_both_fields_filled(self, ax): win = rbr.rb_enter_stations_window(ax) assert win is not None, "Stations window did not open (status menu -> 'Open Radiola')" rows_before = rbr.station_rows(ax, win) assert len(rows_before) == 3, f"expected the 3 default station rows, got {rows_before}"
sheet = rbr.rb_reach_add_station_sheet(ax, win) assert sheet is not None, "'Add station' did not open its sheet" try: ok = _sheet_ok_button(ax, sheet) assert ok is not None, "the Add-station sheet has no OK ('Add station') button" title_tf, url_tf = _sheet_fields(ax, sheet) assert title_tf is not None and url_tf is not None, ( "the Add-station sheet should expose a Title and a Url text field")
empty_both = _enabled(ax, ok) rbr.type_chars(ax, title_tf, "ab") # title only time.sleep(0.3) title_only = _enabled(ax, ok) rbr.type_chars(ax, url_tf, "ab") # title + url time.sleep(0.3) both_filled = _enabled(ax, ok) finally: # ALWAYS dismiss the sheet — never press its OK button (it would persist a # station into bookmarks.opml and leak into every later test). rbr.sheet_cancel(ax, sheet)
time.sleep(0.4) assert not rbr.sheet_present(ax), "the Add-station sheet is still open after Cancel" rows_after = rbr.station_rows(ax, win)
observed = (empty_both, title_only, both_filled, len(rows_after)) expected = (False, False, True, 3) assert kit.rb_value(observed, expected), ( "(OK enabled with nothing typed, with only the title, with title+url, " f"station rows after Cancel) should be {expected}, observed {observed}")
# ── 6. preferences tab -> window title mapping (prefs window = depth 1) ─────────────
class TestSettingsTabTitleMapping: """The preferences window has no title of its own: selecting tab X makes its AXTitle exactly X. The `Audio` tab is deliberately never selected (it crashes the app)."""
@pytest.mark.rb(depth=1, jump_kind="value", expect="selecting Appearance/Startup/Updates/Controls makes the prefs " "window AXTitle exactly that tab name") def test_each_safe_tab_becomes_the_window_title(self, ax): # Start at Appearance: the prefs window OPENS on Controls, so selecting Controls # first would pass without the tab ever having to do anything. Ending on Controls # restores the window's initial tab. tabs = ["Appearance", "Startup", "Updates", "Controls"] assert rbr.SETTINGS_TAB_UNSAFE not in tabs, "the Audio tab must never be selected" assert set(tabs) == set(rbr.SETTINGS_TABS_SAFE), ( f"the safe tab set changed: {rbr.SETTINGS_TABS_SAFE}")
observed = [] for tab in tabs: win = rbr.rb_enter_settings_tab(ax, tab) assert win is not None, f"could not select the {tab!r} preferences tab" observed.append(rbr.settings_tab_title(ax))
assert kit.rb_value(observed, tabs), ( f"prefs window titles per selected tab should be {tabs}, observed {observed}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799"""AX STATE verification for Radiola (status-bar radio player).
Owns CHECKED / ENABLED / SELECTED / FOCUSED state and every before->after state fliprecorded in recon.md `## STATE` (rows T1-T15) plus the focus row.
Everything is driven through the `ax` pytest fixture and the validated `rb_radiola`helper module (NEVER `ax_with_reset`: `verifier_helpers.ensure_panel_open()` blind-pressesevery menu-bar item and cannot recognise Radiola's status menu).
Hard prohibitions honoured here: the prefs `Audio` tab is never selected (it crashes thereference), `Remove station` / sheet OK / `Check for Updates now` / `Quit` / `Radiola Help`/ Export+Import are never pressed, and every favourite that is toggled is toggled back in a`finally` (the favourites list is persisted to bookmarks.opml and would leak)."""
from __future__ import annotations
import time
import pytest
import rb_radiola as rbrimport rb_testgen_kit as kit
# ── locator vocabulary (semantic: AXTitle/AXDescription/AXHelp text, never indices) ──
SIDEBAR_NAMES = ("My lists", "My stations", "Radio browser", "By tag", "By name", "By country")
FILE_MENU_ITEMS = ("New Station", "New Station Group", "Delete Station or Group", "Add Station to my stations", "Export stations to a file…", "Import stations from a file…", "Close", "Close All")
# ── tiny attribute readers (kept local so the tests read like prose) ─────────────────
def _attr(ax, el, name, default=None): """One AX attribute of an element, `default` when absent.""" if el is None: return default v = ax.get(el.id, [name]).get(name) return default if v is None else v
def _enabled(ax, el): return bool(_attr(ax, el, "AXEnabled", False))
def _check(ax, el): """CHECKED state of a checkbox as 0/1 (AXValue).""" v = _attr(ax, el, "AXValue", 0) try: return int(v) except Exception: return 1 if v else 0
def _help(ax, el): return str(_attr(ax, el, "AXHelp", "") or "").strip().lower()
def _mute_help_state(h): """'unmute' / 'mute' / '' — the mute checkbox's AXHelp is the state indicator, and 'unmute' must be tested BEFORE 'mute' because it contains it.""" if "unmute" in h or "un-mute" in h: return "unmute" if "mute" in h: return "mute" return ""
def _text(ax, el): return str(_attr(ax, el, "AXValue", "") or "")
def _fnum(v, nd=2): """A float AX value rounded, or None. The reference's slider AXValue is a float32, so 0.8 reads back as 0.8000000119 — always compare rounded.""" try: return round(float(v), nd) except Exception: return None
def _norm(s): return (s or "").strip().lower().rstrip(" .…")
def _checkbox_by_keywords(ax, root, keywords): """Checkbox under `root` whose visible label contains ALL keywords (EN).""" if root is None: return None for c in ax.find(role="checkbox", root_id=root.id, max_results=30): n = (c.name or "").lower() if n and all(k.lower() in n for k in keywords): return c return None
def _button_by_keywords(ax, root, keywords): if root is None: return None for b in ax.find(role="button", root_id=root.id, max_results=40): n = (b.name or "").lower() if n and any(k.lower() in n for k in keywords): return b return None
def _menu_enabled_map(ax, menu_name, wanted): """{item label -> AXEnabled} for an app menu, matched by label (exact, then punctuation-insensitive) — never by index.""" items = rbr.app_menu_items(ax, menu_name) out = {} for w in wanted: val = None for (n, en) in items: if (n or "").strip() == w: val = bool(en) break if val is None: for (n, en) in items: if _norm(n) and _norm(n) == _norm(w): val = bool(en) break out[w] = val return out
def _sidebar_selection(ax, win): """{sidebar entry label -> AXSelected} of the Stations window outline.
AXSelected is read from the row and, if the row does not carry it, from the row's own descendants (a SwiftUI-based recreation may expose it on the cell instead) — semantics over hierarchy. """ out = {} if win is None: return out for r in ax.find(role="row", root_id=win.id, max_results=40): labels = [_text(ax, l) for l in ax.find(role="label", root_id=r.id, max_results=4)] name = next((t for t in labels if t in SIDEBAR_NAMES), None) if name is None: continue sel = _attr(ax, r, "AXSelected", None) if sel is None: for kid in ax.find(root_id=r.id, max_results=6): sel = _attr(ax, kid, "AXSelected", None) if sel is not None: break out[name] = bool(sel) return out
def _status_menu_names(ax, menu): return [n for (n, _en, _c) in rbr.status_menu_items(ax, menu)]
def _restore_favorite(ax, star): """Put a station row's star back into the FAVOURITE state, whatever happened.
State-driven rather than a blind second press: the favourites list is persisted to bookmarks.opml, so a half-applied toggle would leak into every later test. """ for _ in range(3): if rbr.station_favorite_state(ax, star) is True: return True rbr.press(ax, star) time.sleep(0.8) return rbr.station_favorite_state(ax, star) is True
# ── T1 — the mute toggle and everything it disables ─────────────────────────────────
class TestMuteState:
@pytest.mark.rb(depth=1, jump_kind="transition", expect="Stations mute checkbox CHECKED 0->1 and AXHelp 'Mute'->'Unmute'; " "pressing again restores 0/'Mute'") def test_mute_checkbox_checked_and_help_flip(self, ax): win = rbr.rb_enter_stations_window(ax) assert win is not None, "Stations window did not open (status menu > Open Radiola)" cb = rbr.stations_mute_checkbox(ax, win) assert cb is not None, "no mute checkbox in the Stations window"
before = (_check(ax, cb), _mute_help_state(_help(ax, cb))) rbr.press(ax, cb) time.sleep(0.7) after = (_check(ax, cb), _mute_help_state(_help(ax, cb)))
assert kit.rb_flip(before, after), f"mute state did not flip: {before} -> {after}" assert kit.rb_value(after, (1, "unmute")), \ f"muted state should be AXValue 1 + AXHelp 'Unmute', got {after}"
rbr.press(ax, cb) time.sleep(0.7) restored = (_check(ax, cb), _mute_help_state(_help(ax, cb))) assert kit.rb_value(restored, (0, "mute")), \ f"unmuting should restore AXValue 0 + AXHelp 'Mute', got {restored}"
@pytest.mark.rb(depth=1, jump_kind="value", expect="muting DISABLES the volume slider, 'volume up' and " "'audio output volume off'; unmuting re-ENABLES all three") def test_mute_disables_volume_controls(self, ax): win = rbr.rb_enter_stations_window(ax) assert win is not None, "Stations window did not open" cb = rbr.stations_mute_checkbox(ax, win) sl = rbr.stations_volume_slider(ax, win) up = rbr.stations_volume_button(ax, win, "up") down = rbr.stations_volume_button(ax, win, "down") assert cb is not None and sl is not None, "mute checkbox / volume slider missing" assert up is not None and down is not None, "volume up/down buttons missing"
def snap(): return {"slider": _enabled(ax, sl), "volume_up": _enabled(ax, up), "volume_down": _enabled(ax, down)}
unmuted = snap() rbr.press(ax, cb) time.sleep(0.8) muted = snap() rbr.screenshot_assert( "states_mute_disables_volume_controls", "Radiola's Stations window is open and MUTED: the small speaker/mute button in " "the toolbar row shows the muted (crossed-out speaker) state, and the volume " "slider between the two volume buttons is greyed out/dimmed and cannot be " "dragged. The three 'Radio Caroline' station rows with their yellow stars are " "still listed below, and the play triangle is still shown.") rbr.press(ax, cb) time.sleep(0.8) unmuted_again = snap()
observed = {"unmuted": unmuted, "muted": muted, "unmuted_again": unmuted_again} expected = { "unmuted": {"slider": True, "volume_up": True, "volume_down": True}, "muted": {"slider": False, "volume_up": False, "volume_down": False}, "unmuted_again": {"slider": True, "volume_up": True, "volume_down": True}, } assert kit.rb_value(observed, expected), \ f"mute must disable the volume controls: {observed}"
# ── T2 — the volume slider's settable AXValue ───────────────────────────────────────
class TestVolumeSliderState:
@pytest.mark.rb(depth=1, jump_kind="value", expect="volume slider AXValue is 0.5 on a fresh launch, AXValue is " "settable, and set_value(0.8) reads back 0.8") def test_volume_slider_default_and_settable(self, ax): win = rbr.rb_enter_stations_window(ax) assert win is not None, "Stations window did not open" sl = rbr.stations_volume_slider(ax, win) assert sl is not None, "no volume slider in the Stations window"
default = _attr(ax, sl, "AXValue", None) assert default is not None, "volume slider exposes no AXValue" settable = ax.is_attribute_settable(sl.id, "AXValue") ax.set_value(sl.id, 0.8) time.sleep(0.6) after = _attr(ax, sl, "AXValue", None)
observed = {"default": _fnum(default), "settable": bool(settable), "after_set_0_8": _fnum(after)} expected = {"default": 0.5, "settable": True, "after_set_0_8": 0.8} assert kit.rb_value(observed, expected), f"slider state wrong: {observed}"
# ── T3 — the row star vs. the status menu's favourites (the app's strongest chain) ──
class TestFavoriteState:
@pytest.mark.rb(depth=1, jump_kind="transition", expect="row-0 star: favourite True->False on AXPress (read from AXHelp " "'Unmark…'->'Mark the station as a favorite'), restored to True") def test_favorite_star_state_flips(self, ax): win = rbr.rb_enter_stations_window(ax) assert win is not None, "Stations window did not open" stars = rbr.station_favorite_checkboxes(ax, win) assert stars, "no 'Favorite' star checkbox on the station rows" star = stars[0]
# NOTE: the star's AXValue is a meaningless NSButton toggle counter — the model # truth lives in AXHelp, which rbr.station_favorite_state() reads. before = rbr.station_favorite_state(ax, star) assert before is True, f"row 0 should start as a favourite, got {before!r}"
toggled = False restored = False try: rbr.press(ax, star) toggled = True time.sleep(0.8) after = rbr.station_favorite_state(ax, star) assert kit.rb_flip(before, after), \ f"favourite state did not flip: {before!r} -> {after!r}" assert kit.rb_value(after, False), f"expected non-favourite, got {after!r}" finally: if toggled: restored = _restore_favorite(ax, star) assert restored, "toggling the star back must restore the favourite"
@pytest.mark.rb(depth=2, jump_kind="value", expect="un-starring station row 0 REMOVES it from the status menu's " "favourites list; re-starring puts it back in the same order") def test_favorite_removal_updates_status_menu(self, ax): win = rbr.rb_enter_stations_window(ax) assert win is not None, "Stations window did not open" stars = rbr.station_favorite_checkboxes(ax, win) assert stars, "no 'Favorite' star checkbox on the station rows" star = stars[0] rows = rbr.station_rows(ax, win) assert rows, "no station rows in the Stations window" name = rows[0][0]
menu = rbr.rb_reach_status_menu(ax) before_names = rbr.status_menu_favorite_names(ax, menu) rbr.close_all_menus(ax) assert name in before_names, \ f"row-0 station {name!r} missing from the status menu favourites {before_names}"
toggled = False try: rbr.press(ax, star) toggled = True time.sleep(0.8) assert kit.rb_flip(True, rbr.station_favorite_state(ax, star)), \ "the star did not leave the favourite state" menu_off = rbr.rb_reach_status_menu(ax) names_off = rbr.status_menu_favorite_names(ax, menu_off) rbr.close_all_menus(ax) assert kit.rb_value(names_off, [n for n in before_names if n != name]), \ f"{name!r} should have vanished from the status menu: {names_off}" finally: if toggled: _restore_favorite(ax, star)
menu_back = rbr.rb_reach_status_menu(ax) names_back = rbr.status_menu_favorite_names(ax, menu_back) rbr.close_all_menus(ax) assert kit.rb_value(names_back, before_names), \ f"re-starring must restore the favourites list: {names_back} != {before_names}"
# ── T4/T5/T6 — Appearance checkboxes and what they do to the status menu / tooltip ──
class TestAppearanceStatusMenuState:
@pytest.mark.rb(depth=2, jump_kind="value", expect="'Show the volume control in the menu' CHECKED 0->1; the reopened " "status menu then holds a slider at 0.5 plus the two volume buttons") def test_volume_control_setting_adds_slider_to_status_menu(self, ax): rbr.rb_enter_settings_window(ax) win = rbr.rb_enter_settings_tab(ax, "Appearance") assert win is not None, "Appearance preferences tab did not open" cb = _checkbox_by_keywords(ax, win, ["volume", "menu"]) assert cb is not None, "no 'Show the volume control in the menu' checkbox"
before = _check(ax, cb) rbr.press(ax, cb) time.sleep(0.7) after = _check(ax, cb) assert kit.rb_flip(before, after), f"checkbox did not flip: {before} -> {after}"
try: menu = rbr.rb_reach_status_menu(ax) assert menu is not None, "status menu did not open" sliders = ax.find(role="slider", root_id=menu.id, max_results=4) vol_btns = [b for b in ax.find(role="button", root_id=menu.id, max_results=20) if "volume" in (b.name or "").lower()] sval = _fnum(_attr(ax, sliders[0], "AXValue", None)) if sliders else None finally: rbr.close_all_menus(ax)
observed = {"checked_before": before, "checked_after": after, "menu_has_slider": bool(sliders), "menu_slider_value": sval, "menu_has_volume_buttons": len(vol_btns) >= 2} expected = {"checked_before": 0, "checked_after": 1, "menu_has_slider": True, "menu_slider_value": 0.5, "menu_has_volume_buttons": True} assert kit.rb_value(observed, expected), \ f"volume control should appear in the status menu: {observed}"
@pytest.mark.rb(depth=2, jump_kind="value", expect="'Show the mute item in the menu' CHECKED 0->1; the reopened " "status menu then contains a 'Mute' item") def test_mute_item_setting_adds_mute_row_to_status_menu(self, ax): rbr.rb_enter_settings_window(ax) win = rbr.rb_enter_settings_tab(ax, "Appearance") assert win is not None, "Appearance preferences tab did not open" mute_cb = _checkbox_by_keywords(ax, win, ["mute", "menu"]) vol_cb = _checkbox_by_keywords(ax, win, ["volume", "menu"]) assert mute_cb is not None, "no 'Show the mute item in the menu' checkbox"
before = _check(ax, mute_cb) rbr.press(ax, mute_cb) time.sleep(0.6) after = _check(ax, mute_cb) assert kit.rb_flip(before, after), f"checkbox did not flip: {before} -> {after}" if vol_cb is not None: # ticked too, purely for the screenshot rbr.press(ax, vol_cb) time.sleep(0.6) rbr.screenshot_assert( "states_appearance_menu_checkboxes_ticked", "The Radiola preferences window is showing the Appearance tab (the 5-icon " "toolbar Controls/Appearance/Audio/Startup/Updates has Appearance highlighted). " "'Show groups in favorites:' still reads 'as a flat list', and TWO checkboxes are " "now ticked with blue checkmarks: 'Show the volume control in the menu' and " "'Show the mute item in the menu'. 'Show the \"Copy song title and artist\" item " "in the menu' stays unticked and 'Show a tooltip with the radiostation and song' " "stays ticked.")
try: menu = rbr.rb_reach_status_menu(ax) assert menu is not None, "status menu did not open" names = _status_menu_names(ax, menu) has_mute = any(n.strip().lower() in ("mute", "unmute") for n in names) rbr.screenshot_assert( "states_status_menu_volume_and_mute", "Radiola's status-bar menu is open under the right end of the macOS menu " "bar. Besides the now-playing row ('Radio Caroline' with a play triangle) " "and the 'Favorite stations' header with the three Radio Caroline entries, " "the menu now also shows a horizontal VOLUME SLIDER (half-filled, at 50%) " "flanked by a quiet-speaker and a loud-speaker button, and a 'Mute' row. " "Open Radiola / History... / Settings... / Quit are at the bottom.") finally: rbr.close_all_menus(ax)
observed = {"checked_before": before, "checked_after": after, "menu_has_mute_item": has_mute} expected = {"checked_before": 0, "checked_after": 1, "menu_has_mute_item": True} assert kit.rb_value(observed, expected), \ f"a 'Mute' item should appear in the status menu: {observed} (items={names})"
@pytest.mark.rb(depth=2, jump_kind="value", expect="unticking 'Show a tooltip with the radiostation and song' " "(CHECKED 1->0) clears the status item's AXHelp: 'Radio Caroline' -> ''") def test_tooltip_setting_clears_status_item_help(self, ax): before_tip = rbr.status_item_tooltip(ax) rbr.rb_enter_settings_window(ax) win = rbr.rb_enter_settings_tab(ax, "Appearance") assert win is not None, "Appearance preferences tab did not open" cb = _checkbox_by_keywords(ax, win, ["tooltip"]) assert cb is not None, "no 'Show a tooltip with the radiostation and song' checkbox"
before = _check(ax, cb) rbr.press(ax, cb) time.sleep(0.6) after = _check(ax, cb) assert kit.rb_flip(before, after), f"checkbox did not flip: {before} -> {after}"
after_tip = rbr.status_item_tooltip(ax) for _ in range(6): if after_tip == "": break time.sleep(0.4) after_tip = rbr.status_item_tooltip(ax)
observed = {"checked_before": before, "checked_after": after, "tooltip_before": before_tip, "tooltip_after": after_tip} expected = {"checked_before": 1, "checked_after": 0, "tooltip_before": rbr.STATION_1, "tooltip_after": ""} assert kit.rb_value(observed, expected), f"tooltip setting wrong: {observed}"
@pytest.mark.rb(depth=2, jump_kind="value", expect="'Show groups in favorites:' popup starts 'as a flat list' with a " "'✓' mark on that item; AXPress + pick 'as a submenu' sets AXValue " "to 'as a submenu'") def test_favorites_grouping_popup_state(self, ax): rbr.rb_enter_settings_window(ax) win = rbr.rb_enter_settings_tab(ax, "Appearance") assert win is not None, "Appearance preferences tab did not open"
popups = ax.find(role="popup", root_id=win.id, max_results=6) pu = None for p in popups: v = _text(ax, p).lower() if "list" in v or "submenu" in v or "margin" in v: pu = p break pu = pu or (popups[0] if popups else None) assert pu is not None, "no 'Show groups in favorites:' popup on the Appearance tab"
before = _text(ax, pu) mark = None after = before try: rbr.press(ax, pu) menu = None for _ in range(10): menus = ax.find(role="menu", root_id=pu.id, max_results=3, max_depth=2) if menus: menu = menus[-1] break time.sleep(0.2) assert menu is not None, "the popup did not open its menu" flat = rbr.menu_item_by_name(ax, menu, before) or \ rbr.menu_item_by_name(ax, menu, "flat list") assert flat is not None, "the current option is not in the popup menu" mark = _attr(ax, flat, "AXMenuItemMarkChar", None) sub = rbr.menu_item_by_name(ax, menu, "as a submenu") or \ rbr.menu_item_by_name(ax, menu, "submenu") assert sub is not None, "'as a submenu' is not offered by the popup" # A popup's menu item answers AXPick; AXPress is the fallback for a # recreation that only wires the press action. if not ax.action(sub.id, "AXPick"): rbr.press(ax, sub) time.sleep(1.0) after = _text(ax, pu) if after == before: # some pickers need the press form rbr.press(ax, sub) time.sleep(1.0) after = _text(ax, pu) finally: rbr.close_all_menus(ax)
assert kit.rb_flip(before, after), f"popup value did not flip: {before!r} -> {after!r}" observed = {"before": before, "mark_on_current": mark, "after": after} expected = {"before": "as a flat list", "mark_on_current": "✓", "after": "as a submenu"} assert kit.rb_value(observed, expected), f"grouping popup state wrong: {observed}"
# ── T7/T8/T9 — the plain preference / History checkboxes ────────────────────────────
class TestPreferenceCheckboxStates:
@pytest.mark.rb(depth=1, jump_kind="transition", expect="Startup tab 'Play last station on startup' CHECKED 0 (fresh-launch " "default) -> 1 on AXPress") def test_play_last_station_on_startup_toggles(self, ax): win = rbr.rb_enter_settings_tab(ax, "Startup") assert win is not None, "Startup preferences tab did not open" cb = _checkbox_by_keywords(ax, win, ["last station"]) or \ _checkbox_by_keywords(ax, win, ["startup"]) assert cb is not None, "no 'Play last station on startup' checkbox"
before = _check(ax, cb) assert before == 0, f"fresh-launch default should be unchecked, got {before}" rbr.press(ax, cb) time.sleep(0.6) after = _check(ax, cb) assert kit.rb_flip(before, after), f"checkbox did not flip: {before} -> {after}" assert kit.rb_value(after, 1), f"expected CHECKED 1, got {after}"
@pytest.mark.rb(depth=1, jump_kind="transition", expect="Updates tab 'Automatically check for updates' CHECKED 0 " "(fresh-launch default) -> 1 on AXPress") def test_automatic_update_check_toggles(self, ax): win = rbr.rb_enter_settings_tab(ax, "Updates") assert win is not None, "Updates preferences tab did not open" cb = _checkbox_by_keywords(ax, win, ["automatically", "updates"]) or \ _checkbox_by_keywords(ax, win, ["updates"]) assert cb is not None, "no 'Automatically check for updates' checkbox"
before = _check(ax, cb) assert before == 0, f"fresh-launch default should be unchecked, got {before}" rbr.press(ax, cb) # NB: the 'Check for Updates now' BUTTON is never pressed time.sleep(0.6) after = _check(ax, cb) assert kit.rb_flip(before, after), f"checkbox did not flip: {before} -> {after}" assert kit.rb_value(after, 1), f"expected CHECKED 1, got {after}"
@pytest.mark.rb(depth=1, jump_kind="transition", expect="History window 'Show only your favorite songs' CHECKED 0 " "(fresh-launch default) -> 1 on AXPress") def test_history_favorites_only_toggles(self, ax): win = rbr.rb_enter_history_window(ax) assert win is not None, "History window did not open (status menu > History...)" cb = rbr.history_favorites_checkbox(ax, win) assert cb is not None, "no 'Show only your favorite songs' checkbox"
before = _check(ax, cb) assert before == 0, f"fresh-launch default should be unchecked, got {before}" rbr.press(ax, cb) time.sleep(0.6) after = _check(ax, cb) assert kit.rb_flip(before, after), f"checkbox did not flip: {before} -> {after}" assert kit.rb_value(after, 1), f"expected CHECKED 1, got {after}"
# ── T10/T12/T13 + menu ENABLED consistency ──────────────────────────────────────────
class TestMenuItemStates:
@pytest.mark.rb(depth=1, jump_kind="value", expect="status-menu play item exposes a 'Mark current song as favorite' " "checkbox whose AXEnabled is False while nothing is playing") def test_play_item_favorite_checkbox_disabled_while_paused(self, ax): menu = rbr.rb_reach_status_menu(ax) assert menu is not None, "the status menu did not open" try: play = rbr.status_menu_play_item(ax, menu) fav = play.get("favorite") assert fav is not None, "no 'Mark current song as favorite' checkbox in the play item" label = (fav.name or "").lower() raw = _attr(ax, fav, "AXEnabled", "AXEnabled-missing") finally: rbr.close_all_menus(ax)
assert "favorite" in label, f"unexpected checkbox label {label!r}" assert kit.rb_value(raw, False), \ f"the favourite checkbox must stay DISABLED while paused, AXEnabled={raw!r}"
@pytest.mark.rb(depth=1, jump_kind="value", expect="Edit > 'Copy song title and artist' is AXEnabled False while no " "song is playing") def test_copy_song_title_disabled_without_song(self, ax): menu = rbr.rb_enter_app_menu(ax, "Edit") assert menu is not None, "the Edit menu is not in the AX tree" item = rbr.menu_item_by_name(ax, menu, "Copy song title and artist") assert item is not None, "Edit menu has no 'Copy song title and artist' item" raw = _attr(ax, item, "AXEnabled", "AXEnabled-missing") assert kit.rb_value(raw, False), \ f"'Copy song title and artist' must be disabled offline, AXEnabled={raw!r}"
@pytest.mark.rb(depth=1, jump_kind="transition", expect="the Control menu holds exactly ['Play']; activating it swaps the " "mutually-exclusive pair to ['Pause']") def test_control_menu_play_becomes_pause(self, ax): before = rbr.control_menu_item_names(ax) assert kit.rb_value(before, ["Play"]), \ f"the Control menu should hold exactly ['Play'], got {before}"
menu = rbr.rb_enter_app_menu(ax, "Control") assert menu is not None, "the Control menu is not in the AX tree" item = rbr.menu_item_by_name(ax, menu, "Play") assert item is not None, "no 'Play' item in the Control menu" rbr.press(ax, item)
after = before for _ in range(10): time.sleep(0.4) after = rbr.control_menu_item_names(ax) if after != before: break assert kit.rb_flip(before, after), f"Control menu did not change: {before} -> {after}" assert kit.rb_value(after, ["Pause"]), f"expected ['Pause'], got {after}"
@pytest.mark.rb(depth=1, jump_kind="value", expect="status menu ENABLED map: the 'Favorite stations' header is " "disabled while the 3 station entries and all 4 commands are enabled") def test_status_menu_enabled_map(self, ax): menu = rbr.rb_reach_status_menu(ax) assert menu is not None, "the status menu did not open" try: items = rbr.status_menu_items(ax, menu) # only ENABLED entries between the header and the commands are returned, # so its length IS the count of usable station rows (label-agnostic) enabled_stations = rbr.status_menu_favorite_names(ax, menu) finally: rbr.close_all_menus(ax) assert items, "the status menu exposed no items"
header = None for (n, en, _c) in items: if _norm(n) == "favorite stations": header = bool(en) # punctuation-insensitive command lookup: a recreation may spell the item # "History…" (U+2026) instead of "History..." cmds = {_norm(n): bool(en) for (n, en, _c) in items}
observed = {"header_enabled": header, "enabled_station_count": len(enabled_stations), "commands_enabled": [cmds.get(_norm(c)) for c in rbr.STATUS_MENU_COMMANDS]} expected = {"header_enabled": False, "enabled_station_count": 3, "commands_enabled": [True, True, True, True]} assert kit.rb_value(observed, expected), f"status menu enablement wrong: {observed}"
@pytest.mark.rb(depth=1, jump_kind="transition", expect="File menu enablement flips when a window exists: New Station / " "New Station Group / Delete Station or Group / Export… / Import… / " "Close go False->True ('Add Station to my stations' stays False, " "'Close All' stays True)") def test_file_menu_enablement_flips_with_window(self, ax): before = _menu_enabled_map(ax, "File", FILE_MENU_ITEMS) expected_before = { "New Station": False, "New Station Group": False, "Delete Station or Group": False, "Add Station to my stations": False, "Export stations to a file…": False, "Import stations from a file…": False, "Close": False, "Close All": True, } assert kit.rb_value(before, expected_before), \ f"File menu with no window should be almost fully disabled: {before}"
win = rbr.rb_enter_stations_window(ax) assert win is not None, "Stations window did not open" time.sleep(1.0) after = _menu_enabled_map(ax, "File", FILE_MENU_ITEMS)
expected_after = { "New Station": True, "New Station Group": True, "Delete Station or Group": True, "Add Station to my stations": False, "Export stations to a file…": True, "Import stations from a file…": True, "Close": True, "Close All": True, } assert kit.rb_flip(before, after), f"File menu enablement did not change: {after}" assert kit.rb_value(after, expected_after), \ f"File menu enablement with the Stations window open: {after}"
# ── T15 + focus — selection state and the sheet's focusable text field ──────────────
class TestSelectionAndFocusState:
@pytest.mark.rb(depth=1, jump_kind="transition", expect="sidebar AXSelected moves 'My stations'->'By tag'; the 3 station " "rows empty out and come back when 'My stations' is re-selected") def test_sidebar_selection_drives_station_rows(self, ax): win = rbr.rb_enter_stations_window(ax) assert win is not None, "Stations window did not open"
before_sel = _sidebar_selection(ax, win) assert before_sel.get("My stations") is True, \ f"'My stations' should start selected: {before_sel}" before_rows = len(rbr.station_rows(ax, win))
assert rbr.rb_enter_sidebar_list(ax, "By tag", win), "could not click 'By tag'" after_sel = _sidebar_selection(ax, win) after_rows = len(rbr.station_rows(ax, win))
assert rbr.rb_enter_sidebar_list(ax, "My stations", win), \ "could not click back to 'My stations'" back_rows = len(rbr.station_rows(ax, win))
assert kit.rb_flip(before_sel, after_sel), \ f"the sidebar selection did not move: {before_sel} -> {after_sel}" assert after_sel.get("By tag") is True, f"'By tag' should be selected: {after_sel}" assert kit.rb_value({"my_stations": before_rows, "by_tag": after_rows, "restored": back_rows}, {"my_stations": 3, "by_tag": 0, "restored": 3}), \ f"station rows: {before_rows} -> {after_rows} -> {back_rows}"
@pytest.mark.rb(depth=2, jump_kind="value", expect="the Add-station sheet's Title field has a SETTABLE AXFocused and " "real keystrokes land in it (field text '' -> 'radio'); sheet cancelled") def test_add_station_field_is_focusable_and_typable(self, ax): win = rbr.rb_enter_stations_window(ax) assert win is not None, "Stations window did not open" sheet = rbr.rb_reach_add_station_sheet(ax, win) assert sheet is not None, "the 'Add station' sheet did not appear" try: fields = ax.find(role="text_field", root_id=sheet.id, max_results=5) assert fields, "the Add-station sheet has no text fields" # Prefer the field whose own metadata names it (a recreation may label it); # otherwise the first editable field of the sheet — never a tree index. tf = None for f in fields: meta = " ".join(str(_attr(ax, f, a, "") or "").lower() for a in ("AXTitle", "AXDescription", "AXPlaceholderValue")) if "title" in meta or "name" in meta: tf = f break tf = tf or fields[0]
def all_text(): return "".join(_text(ax, f) for f in fields)
settable = ax.is_attribute_settable(tf.id, "AXFocused") before_text = all_text() rbr.type_chars(ax, tf, "radio") time.sleep(0.4) after_text = all_text() focused = bool(_attr(ax, tf, "AXFocused", False)) finally: rbr.sheet_cancel(ax, sheet)
observed = {"focus_settable": bool(settable), "text_before": before_text, "text_after": after_text} expected = {"focus_settable": True, "text_before": "", "text_after": "radio"} assert kit.rb_value(observed, expected), \ f"focus/typing state wrong: {observed} (AXFocused after typing={focused})"
@pytest.mark.rb(depth=1, jump_kind="value", expect="every interactive control of the Stations window (play, volume " "slider, both volume buttons, mute, Add station, Add group, Toggle " "sidebar) is AXEnabled at rest — zero disabled widgets") def test_stations_window_controls_all_enabled(self, ax): win = rbr.rb_enter_stations_window(ax) assert win is not None, "Stations window did not open"
controls = { "play": rbr.stations_play_button(ax, win), "volume_slider": rbr.stations_volume_slider(ax, win), "volume_up": rbr.stations_volume_button(ax, win, "up"), "volume_down": rbr.stations_volume_button(ax, win, "down"), "mute": rbr.stations_mute_checkbox(ax, win), "add_station": _button_by_keywords(ax, win, ["add station"]), "add_group": _button_by_keywords(ax, win, ["add group"]), "toggle_sidebar": _button_by_keywords(ax, win, ["toggle sidebar", "sidebar"]), } observed = {k: (_enabled(ax, el) if el is not None else "MISSING") for k, el in controls.items()} expected = {k: True for k in controls} assert kit.rb_value(observed, expected), \ f"all Stations controls should be visible AND enabled: {observed}"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563"""AX STRUCTURE tests for Radiola (macOS status-bar / menu-bar-extra radio player).
Everything asserted here was OBSERVED on the running reference app and is recorded inrecon.md (`## AX_TREE` / `## STRUCTURE`). The module owns the STRUCTURE lane:
* a small GATE group (jump_kind="none") for the top-level surfaces that must EXIST (status item, the app's own menu bar, "no windows at launch"), * one test per measured shape-delta S1..S12 — each asserts the before/after widget counts / element name-sets, proven with kit.rb_reach (surface jumps) or kit.rb_flip (in-place tree-shape deltas).
Radiola has NO window at launch: every surface is revealed through the status-bar item(a real CGEvent click — AXPress does nothing) or through the app's own menu bar. All ofthat is encapsulated in the deployed `rb_radiola` helpers, which are the only way thesetests touch the app (plus the `ax` fixture, which owns the AX connection).
NEVER pressed here (they crash / mutate / leave the app): the prefs "Audio" tab,"Remove station", a sheet's OK button, Quit / Quit Radiola, Radiola Help,Check For Updates…, Export/Import stations…."""
import reimport time
import pytest
import rb_radiola as rbrimport rb_testgen_kit as kit
# ── local read-only helpers (no navigation, no AX handle creation) ───────────────────
SIDEBAR_ENTRIES = ["My lists", "My stations", "Radio browser", "By tag", "By name", "By country"]
PREFS_TABS = ["Controls", "Appearance", "Audio", "Startup", "Updates"]
APP_MENU_BAR_NAMES = {"Radiola", "File", "Edit", "Control", "Window", "Help"}
def _size_wh(ax, element_id): """(width, height) of an element, tolerant of both the dict and the AXValue-string forms the AX bridge can hand back.""" raw = ax.get(element_id, ["AXSize"]).get("AXSize") if isinstance(raw, dict): return float(raw.get("width") or 0), float(raw.get("height") or 0) nums = re.findall(r"[-\d.]+", str(raw or "")) if len(nums) >= 2: try: return float(nums[-2]), float(nums[-1]) except ValueError: return 0.0, 0.0 return 0.0, 0.0
def _app_menu_bar_item_names(ax): """Titles of the APP's own menu-bar items — the system 'Apple' menu and the status item (AXRoleDescription 'status menu', empty title) are excluded.""" si = rbr.status_item(ax) si_id = getattr(si, "id", None) names = [] for m in ax.find(role="menu_bar_item", max_results=24, max_depth=6): if si_id is not None and m.id == si_id: continue rd = ax.get(m.id, ["AXRoleDescription"]).get("AXRoleDescription") or "" if rd == "status menu": continue n = (m.name or "").strip() if n and n != "Apple": names.append(n) return names
def _named_buttons(ax, root_id): """Named buttons under root_id, minus the window's traffic-light controls (a recreation's framework may or may not give those an AXTitle/AXDescription).""" skip = {"close", "minimize", "zoom", "full screen", "enter full screen", "exit full screen", "restore", "toolbar"} return {n for n in rbr.buttons(ax, root_id).keys() if n.strip().lower() not in skip}
def _enabled(ax, element): return ax.get(element.id, ["AXEnabled"]).get("AXEnabled")
def _sidebar_texts(ax, win): return [t for (_el, t) in rbr.sidebar_labels(ax, win)]
def _menu_item_names(ax, menu): return [n for (n, _en, _cc) in rbr.status_menu_items(ax, menu)]
# ── (a) GATE — the top-level surfaces of recon `## STRUCTURE` must exist ─────────────
class TestStructureGate: """Existence-only checks (jump_kind="none"). Deliberately capped at 4 tests: an existence assertion is the weakest evidence, so the shape-delta tests below carry the lane."""
@pytest.mark.rb(depth=0, jump_kind="none") def test_gate_status_item_is_a_status_menu_with_a_real_frame(self, ax): si = rbr.status_item(ax) assert si is not None, "no status-bar item found — Radiola's only entry point" assert si.role == "menu_bar_item", f"status item role is {si.role!r}" rd = ax.get(si.id, ["AXRoleDescription"]).get("AXRoleDescription") assert rd == "status menu", f"AXRoleDescription is {rd!r}, expected 'status menu'" w, h = _size_wh(ax, si.id) assert w > 0 and h > 0, f"status item frame is degenerate: {w}x{h}" assert "AXPress" in (si.actions or []), f"status item actions: {si.actions}"
@pytest.mark.rb(depth=0, jump_kind="none") def test_gate_app_menu_bar_exposes_exactly_the_six_named_menus(self, ax): names = _app_menu_bar_item_names(ax) assert set(names) == APP_MENU_BAR_NAMES, f"menu-bar items: {names}" for n in sorted(APP_MENU_BAR_NAMES): assert rbr.app_menu(ax, n) is not None, f"menu {n!r} does not resolve" assert rbr.app_menu_items(ax, n), f"menu {n!r} carries no items" # two menu bars: the app's own one plus the status-item bar assert len(ax.find(role="menu_bar", max_results=6, max_depth=2)) >= 2
@pytest.mark.rb(depth=0, jump_kind="none") def test_gate_no_windows_at_launch(self, ax): titles = rbr.window_titles(ax) assert titles == [], f"a status-bar app must open no window at launch: {titles}" assert rbr.find_window(ax, "Stations") is None assert rbr.find_window(ax, "History") is None assert rbr.settings_window(ax) is None assert not rbr.sheet_present(ax)
# ── menu-bar inventory (still depth 0, but a VALUE claim, not mere existence) ─────────
class TestMenuBarInventory:
@pytest.mark.rb(depth=0, jump_kind="value", expect="the app's menu bar carries Radiola(>=7 items incl About " "Radiola/Settings…/Quit), File(>=8 items incl New Station and " "Export/Import stations), Control == exactly ['Play'] while " "paused, and Help containing 'Radiola Help'") def test_app_menus_expose_their_expected_item_populations(self, ax): radiola = [n for (n, _e) in rbr.app_menu_items(ax, "Radiola") if n] assert "About Radiola" in radiola, radiola assert any(n.startswith("Settings") or n.startswith("Preferences") for n in radiola), radiola assert any(n.startswith("Quit") for n in radiola), radiola assert len(radiola) >= 7, radiola
file_named = [n for (n, _e) in rbr.app_menu_items(ax, "File") if n] for kw in ("New Station", "New Station Group", "Delete Station or Group", "Add Station to my stations", "Export stations", "Import stations", "Close All"): assert any(kw in n for n in file_named), f"File menu lacks {kw!r}: {file_named}" assert len(file_named) >= 8, file_named
assert any("Radiola Help" in n for (n, _e) in rbr.app_menu_items(ax, "Help")) # The Control menu holds exactly ONE item while paused (Play; Pause is hidden). assert kit.rb_value(rbr.control_menu_item_names(ax), ["Play"]), \ rbr.control_menu_item_names(ax)
# ── (b) shape deltas that CROSS INTO A NEW SURFACE — proven with kit.rb_reach ────────
class TestSurfaceReachDeltas:
@pytest.mark.rb(depth=1, jump_kind="reach", expect="S1: 0 menus under the status item -> 1 AXMenu with 11 items " "incl 'Open Radiola'/'History...'/'Settings...'/'Quit'") def test_s1_status_item_click_grows_a_menu(self, ax): si = rbr.status_item(ax) assert si is not None assert ax.find(role="menu", root_id=si.id, max_results=4, max_depth=2) == [] before = kit.rb_showing(ax) menu = rbr.rb_reach_status_menu(ax) after = kit.rb_showing(ax) assert menu is not None, "the status menu never appeared after a real click" items = _menu_item_names(ax, menu) assert len(items) == 11, f"status menu has {len(items)} items: {items}" for cmd in rbr.STATUS_MENU_COMMANDS: assert cmd in items, f"{cmd!r} missing from {items}" assert "Favorite stations" in items assert kit.rb_reach(before, after, target="Open Radiola", source=None) rbr.screenshot_assert( "structure_status_menu_open", "Radiola's status-bar menu is open as a drop-down under the RIGHT end of the " "macOS menu bar: a play triangle with 'Radio Caroline' on the first row, a " "greyed-out 'Favorite stations' section header, three 'Radio Caroline' station " "entries, then the commands Open Radiola, History..., Settings... and Quit. " "No application window is open behind it.") rbr.close_all_menus(ax)
@pytest.mark.rb(depth=1, jump_kind="reach", expect="S2: window_titles [] -> ['Stations'] with 3 station text " "fields, a 0.5 volume slider and Add station/Add group/Remove " "station buttons") def test_s2_open_radiola_creates_the_stations_window(self, ax): assert rbr.window_titles(ax) == [] before = kit.rb_showing(ax) win = rbr.rb_enter_stations_window(ax) after = kit.rb_showing(ax) assert win is not None, "'Open Radiola' did not reveal the Stations window" assert rbr.window_titles(ax) == ["Stations"], rbr.window_titles(ax) btns = _named_buttons(ax, win.id) for b in ("Add station", "Add group", "Remove station", "Toggle sidebar"): assert b in btns, f"{b!r} missing from Stations buttons {sorted(btns)}" assert rbr.stations_play_button(ax, win) is not None assert rbr.stations_volume_slider(ax, win) is not None assert len(rbr.station_rows(ax, win)) == 3 assert len(ax.find(role="split_group", root_id=win.id, max_results=3)) >= 1 assert len(ax.find(role="toolbar", root_id=win.id, max_results=3)) >= 1 assert kit.rb_reach(before, after, target="Stations", source=None) rbr.screenshot_assert( "structure_stations_window", "The 'Stations' window is open. On the left a sidebar lists 'My lists' with " "'My stations' selected, and 'Radio browser' with 'By tag', 'By name', 'By " "country'. A toolbar across the top holds a play triangle, the station name " "'Radio Caroline' and a volume slider with decrease / mute / increase icons. " "The main pane lists 3 'Radio Caroline' stations, each row showing a star, a " "'...' context button and the station URL, and the bottom edge has the " "buttons Add station, Add group and Remove station.")
@pytest.mark.rb(depth=1, jump_kind="reach", expect="S3: no History window -> window 'History' with a table, the " "label 'No records yet' and the 'Show only your favorite " "songs' checkbox") def test_s3_history_command_creates_the_history_window(self, ax): assert rbr.find_window(ax, "History") is None before = kit.rb_showing(ax) win = rbr.rb_enter_history_window(ax) after = kit.rb_showing(ax) assert win is not None, "'History...' did not reveal the History window" assert "History" in rbr.window_titles(ax), rbr.window_titles(ax) assert "No records yet" in rbr.label_values(ax, win.id) assert len(ax.find(role="table", root_id=win.id, max_results=3)) >= 1 cb = rbr.history_favorites_checkbox(ax, win) assert cb is not None and "favorite" in (cb.name or "").lower() assert rbr.station_rows(ax, win) == [] assert kit.rb_reach(before, after, target="No records yet", source=None)
@pytest.mark.rb(depth=1, jump_kind="reach", expect="S4: no prefs window -> window titled 'Controls' whose toolbar " "carries the 5 tab buttons Controls/Appearance/Audio/Startup/" "Updates") def test_s4_settings_command_creates_the_preferences_window(self, ax): assert rbr.settings_window(ax) is None before = kit.rb_showing(ax) win = rbr.rb_enter_settings_window(ax) after = kit.rb_showing(ax) assert win is not None, "'Settings...' did not reveal the preferences window" assert rbr.settings_tab_title(ax) == "Controls", rbr.settings_tab_title(ax) toolbars = ax.find(role="toolbar", root_id=win.id, max_results=3) assert toolbars, "the preferences window has no toolbar" tab_names = set(rbr.settings_tab_buttons(ax, win).keys()) for tab in PREFS_TABS: # 'Audio' is only ever LOOKED AT, never pressed assert tab in tab_names, f"tab {tab!r} missing from {sorted(tab_names)}" assert kit.rb_reach(before, after, target="Appearance", source=None)
@pytest.mark.rb(depth=2, jump_kind="reach", expect="S8: no sheet -> 1 sheet with 'To add a station, fill out the " "following information:' + Title:/Url: labels, 2 text fields, " "a DISABLED 'Add station' and 'Cancel'; Cancel restores 3 rows") def test_s8_add_station_button_reaches_a_modal_sheet(self, ax): win = rbr.rb_enter_stations_window(ax) assert win is not None assert not rbr.sheet_present(ax) before = kit.rb_showing(ax) sheet = rbr.rb_reach_add_station_sheet(ax, win) after = kit.rb_showing(ax) assert sheet is not None, "'Add station' did not open a sheet" labels = rbr.label_values(ax, sheet.id) assert "To add a station, fill out the following information:" in labels, labels assert "Title:" in labels and "Url:" in labels, labels fields = ax.find(role="text_field", root_id=sheet.id, max_results=6) assert len(fields) == 2, f"sheet has {len(fields)} text fields" sheet_btns = rbr.buttons(ax, sheet.id) assert "Cancel" in sheet_btns, sorted(sheet_btns) ok = rbr.find_by_keywords(list(sheet_btns.values()), ["add station"]) assert ok is not None, sorted(sheet_btns) assert _enabled(ax, ok) in (False, 0), "the sheet's OK button must start disabled" assert kit.rb_reach(before, after, target="To add a station", source=None) rbr.screenshot_assert( "structure_add_station_sheet", "A modal sheet has dropped down over the 'Stations' window. It reads 'To add " "a station, fill out the following information:' and shows an empty 'Title:' " "field and an empty 'Url:' field, with a greyed-out 'Add station' button and " "an enabled 'Cancel' button at the bottom right. The station list and sidebar " "of the Stations window are dimmed behind the sheet.") assert rbr.sheet_cancel(ax, sheet) # NEVER press the sheet's OK button assert not rbr.sheet_present(ax) assert len(rbr.station_rows(ax, win)) == 3, "Cancel must not add a station"
@pytest.mark.rb(depth=2, jump_kind="reach", expect="S9: no sheet -> 1 sheet with 'To add a group, fill out the " "following information:' + a single Title: field, a DISABLED " "'Add group' and 'Cancel'; Cancel restores 3 rows") def test_s9_add_group_button_reaches_a_smaller_sheet(self, ax): win = rbr.rb_enter_stations_window(ax) assert win is not None assert not rbr.sheet_present(ax) before = kit.rb_showing(ax) sheet = rbr.rb_reach_add_group_sheet(ax, win) after = kit.rb_showing(ax) assert sheet is not None, "'Add group' did not open a sheet" labels = rbr.label_values(ax, sheet.id) assert "To add a group, fill out the following information:" in labels, labels assert "Title:" in labels, labels assert not any("Url" in l for l in labels), labels fields = ax.find(role="text_field", root_id=sheet.id, max_results=6) assert len(fields) == 1, f"the group sheet has {len(fields)} text fields" sheet_btns = rbr.buttons(ax, sheet.id) assert "Cancel" in sheet_btns, sorted(sheet_btns) ok = rbr.find_by_keywords(list(sheet_btns.values()), ["add group"]) assert ok is not None, sorted(sheet_btns) assert _enabled(ax, ok) in (False, 0), "the sheet's OK button must start disabled" assert kit.rb_reach(before, after, target="To add a group", source=None) assert rbr.sheet_cancel(ax, sheet) # NEVER press the sheet's OK button assert not rbr.sheet_present(ax) assert len(rbr.station_rows(ax, win)) == 3, "Cancel must not add a group"
@pytest.mark.rb(depth=1, jump_kind="reach", expect="S11: 'Radiola > About Radiola' -> a new window carrying the " "'Radiola icon' image, the 'Copyright © 2020 Alex Sokolov...' " "label and 2 links") def test_s11_about_menu_item_creates_the_about_panel(self, ax): assert rbr.window_titles(ax) == [] before = kit.rb_showing(ax) menu = rbr.rb_enter_app_menu(ax, "Radiola") assert menu is not None, "the Radiola app menu has no AXMenu" item = rbr.menu_item_by_name(ax, menu, "About Radiola") assert item is not None, rbr.menu_item_names(ax, menu) assert rbr.press(ax, item) about = None deadline = time.time() + 6.0 while about is None and time.time() < deadline: for w in rbr.windows(ax): if any("Alex Sokolov" in v for v in rbr.label_values(ax, w.id, 40)): about = w break if about is None: time.sleep(0.3) after = kit.rb_showing(ax) assert about is not None, f"no About panel appeared: {rbr.window_titles(ax)}" imgs = ax.find(role="image", root_id=about.id, max_results=8) assert any((i.name or "") == "Radiola icon" for i in imgs), [i.name for i in imgs] assert len(ax.find(role="link", root_id=about.id, max_results=6)) == 2 assert any("Radiola" == v for v in rbr.label_values(ax, about.id, 40)) assert kit.rb_reach(before, after, target="Alex Sokolov", source=None)
# ── (b) IN-PLACE shape deltas — widget-count / name-set flips, proven with rb_flip ───
class TestInPlaceShapeDeltas:
@pytest.mark.rb(depth=2, jump_kind="transition", expect="S5: sidebar 'By tag' -> the 3 station rows and the Add " "station/Add group/Remove station/Context menu/Favorite " "widgets all disappear, only the player buttons remain") def test_s5_by_tag_empties_the_station_pane(self, ax): win = rbr.rb_enter_stations_window(ax) assert win is not None before_rows = rbr.station_rows(ax, win) before_btns = _named_buttons(ax, win.id) assert len(before_rows) == 3, before_rows assert len(rbr.station_favorite_checkboxes(ax, win)) == 3 assert {"Add station", "Add group", "Remove station", "Context menu"} <= before_btns, sorted(before_btns)
assert rbr.rb_enter_sidebar_list(ax, "By tag", win), "no 'By tag' sidebar entry"
after_rows = rbr.station_rows(ax, win) after_btns = _named_buttons(ax, win.id) assert after_rows == [], after_rows assert rbr.station_favorite_checkboxes(ax, win) == [] vanished = before_btns - after_btns assert {"Add station", "Add group", "Remove station", "Context menu"} <= vanished, sorted(vanished) assert "Toggle sidebar" in after_btns, sorted(after_btns) assert len(after_btns) <= 5, sorted(after_btns) assert kit.rb_flip(before_btns, after_btns) assert _sidebar_texts(ax, win) == SIDEBAR_ENTRIES
@pytest.mark.rb(depth=2, jump_kind="transition", expect="S6: sidebar back to 'My stations' -> 0 rows become the 3 " "default Radio Caroline rows again with their exact URLs") def test_s6_my_stations_restores_the_three_rows(self, ax): win = rbr.rb_enter_stations_window(ax) assert win is not None assert rbr.rb_enter_sidebar_list(ax, "By tag", win) mid_rows = rbr.station_rows(ax, win) assert mid_rows == [], mid_rows
assert rbr.rb_enter_sidebar_list(ax, "My stations", win)
after_rows = rbr.station_rows(ax, win) assert kit.rb_flip(mid_rows, after_rows) assert len(after_rows) == 3, after_rows assert [t for (t, _u) in after_rows] == list(rbr.DEFAULT_STATIONS), after_rows assert [u for (_t, u) in after_rows] == [rbr.STATION_1_URL, rbr.STATION_2_URL, rbr.STATION_3_URL], after_rows assert {"Add station", "Add group", "Remove station"} <= _named_buttons(ax, win.id)
@pytest.mark.rb(depth=1, jump_kind="transition", expect="S7: 'Toggle sidebar' -> the 6 sidebar labels (My lists/My " "stations/Radio browser/By tag/By name/By country) drop to 0 " "and a second press restores all 6") def test_s7_toggle_sidebar_hides_and_restores_six_labels(self, ax): win = rbr.rb_enter_stations_window(ax) assert win is not None before = _sidebar_texts(ax, win) assert before == SIDEBAR_ENTRIES, before
toggle = rbr.buttons(ax, win.id).get("Toggle sidebar") assert toggle is not None, sorted(_named_buttons(ax, win.id)) assert rbr.press(ax, toggle) time.sleep(1.0) collapsed = _sidebar_texts(ax, win) assert collapsed == [], collapsed assert kit.rb_flip(before, collapsed) # the station list itself is untouched by collapsing the sidebar assert len(rbr.station_rows(ax, win)) == 3
assert rbr.press(ax, toggle) time.sleep(1.0) restored = _sidebar_texts(ax, win) assert restored == SIDEBAR_ENTRIES, restored assert kit.rb_flip(collapsed, restored)
@pytest.mark.rb(depth=2, jump_kind="transition", expect="S10: ticking Appearance 'Show the volume control in the menu' " "+ 'Show the mute item in the menu' grows the status menu from " "11 items / 0 sliders to 14 items incl 'Mute' / 1 slider") def test_s10_appearance_checkboxes_grow_the_status_menu(self, ax): menu = rbr.rb_reach_status_menu(ax) assert menu is not None before_items = _menu_item_names(ax, menu) before_sliders = len(ax.find(role="slider", root_id=menu.id, max_results=5)) assert len(before_items) == 11, before_items assert before_sliders == 0 assert "Mute" not in before_items, before_items rbr.close_all_menus(ax)
win = rbr.rb_enter_settings_tab(ax, "Appearance") # never the Audio tab assert win is not None assert rbr.settings_tab_title(ax) == "Appearance", rbr.settings_tab_title(ax) boxes = list(rbr.checkboxes(ax, win.id).values()) assert len(boxes) == 4, [b.name for b in boxes] vol = rbr.find_by_keywords(boxes, ["volume control"]) mute = rbr.find_by_keywords(boxes, ["mute item"]) assert vol is not None and mute is not None, [b.name for b in boxes] assert rbr.press(ax, vol) time.sleep(0.4) assert rbr.press(ax, mute) time.sleep(0.6)
menu2 = rbr.rb_reach_status_menu(ax) assert menu2 is not None after_items = _menu_item_names(ax, menu2) after_sliders = len(ax.find(role="slider", root_id=menu2.id, max_results=5)) assert len(after_items) == 14, after_items assert "Mute" in after_items, after_items assert after_sliders == 1, after_sliders assert kit.rb_flip((len(before_items), before_sliders, "Mute" in before_items), (len(after_items), after_sliders, "Mute" in after_items)) rbr.close_all_menus(ax)
@pytest.mark.rb(depth=1, jump_kind="transition", expect="S12: the Window app-menu has no 'Stations' entry until the " "Stations window is opened, then it lists it alongside " "Minimize/Zoom/Bring All to Front") def test_s12_window_menu_lists_the_opened_window(self, ax): before = [n for (n, _e) in rbr.app_menu_items(ax, "Window") if n] assert before, "the Window menu is empty" assert "Stations" not in before, before assert any("Minimize" in n for n in before), before
win = rbr.rb_enter_stations_window(ax) assert win is not None time.sleep(1.0)
after = [n for (n, _e) in rbr.app_menu_items(ax, "Window") if n] assert "Stations" in after, after assert any("Minimize" in n for n in after), after assert len(after) >= len(before) + 1, (before, after) assert kit.rb_flip(set(before), set(after))
# ── panel inventory: the exact widget population of a revealed surface ───────────────
class TestPanelInventory:
@pytest.mark.rb(depth=1, jump_kind="value", expect="each of the 3 station rows carries 1 'Favorite' checkbox, 1 " "'Context menu' button and 2 text fields (title + url) -> 3/3/6") def test_station_rows_each_expose_a_favorite_and_a_context_button(self, ax): win = rbr.rb_enter_stations_window(ax) assert win is not None rows = rbr.station_rows(ax, win) favs = rbr.station_favorite_checkboxes(ax, win) ctxs = rbr.station_context_buttons(ax, win) fields = ax.find(role="text_field", root_id=win.id, max_results=20) observed = (len(rows), len(favs), len(ctxs), len(fields)) assert kit.rb_value(observed, (3, 3, 3, 6)), ( f"rows/favorites/context-buttons/text-fields = {observed}") for c in ctxs: assert "AXShowMenu" in (c.actions or []), c.actions assert rbr.station_favorite_state(ax, favs[0]) is True
@pytest.mark.rb(depth=2, jump_kind="value", expect="prefs tab populations: Appearance -> title 'Appearance', 4 " "checkboxes + 1 popup; Startup -> title 'Startup', exactly 1 " "checkbox 'Play last station on startup'") def test_prefs_tabs_have_their_own_widget_population(self, ax): win = rbr.rb_enter_settings_tab(ax, "Appearance") # never the Audio tab assert win is not None appearance = (rbr.settings_tab_title(ax), len(rbr.checkboxes(ax, win.id)), len(ax.find(role="popup", root_id=win.id, max_results=6))) assert kit.rb_value(appearance, ("Appearance", 4, 1)), appearance boxes = rbr.checkboxes(ax, win.id) assert rbr.find_by_keywords(list(boxes.values()), ["volume control"]) is not None assert rbr.find_by_keywords(list(boxes.values()), ["mute item"]) is not None assert "Show groups in favorites:" in rbr.label_values(ax, win.id) rbr.screenshot_assert( "structure_prefs_appearance", "The Radiola preferences window is showing its Appearance tab: a toolbar of 5 " "icons labelled Controls, Appearance, Audio, Startup and Updates with " "Appearance selected/highlighted, the window title reading 'Appearance', a " "'Show groups in favorites:' dropdown currently reading 'as a flat list', and " "four checkboxes about showing the volume control in the menu, the mute item " "in the menu, the 'Copy song title and artist' item, and a tooltip with the " "radiostation and song (only the last one ticked).")
win2 = rbr.rb_enter_settings_tab(ax, "Startup") assert win2 is not None startup_boxes = list(rbr.checkboxes(ax, win2.id).keys()) startup = (rbr.settings_tab_title(ax), len(startup_boxes)) assert kit.rb_value(startup, ("Startup", 1)), (startup, startup_boxes) assert kit.rb_value(startup_boxes[0], "Play last station on startup"), startup_boxes
@pytest.mark.rb(depth=1, jump_kind="value", expect="History window population: 1 table with 1 column, 0 rows, the " "label 'No records yet' and exactly 1 checkbox 'Show only your " "favorite songs'") def test_history_window_is_an_empty_table_with_one_checkbox(self, ax): win = rbr.rb_enter_history_window(ax) assert win is not None tables = ax.find(role="table", root_id=win.id, max_results=3) boxes = list(rbr.checkboxes(ax, win.id).keys()) observed = (len(tables), len(rbr.station_rows(ax, win)), len(boxes)) assert kit.rb_value(observed, (1, 0, 1)), ( f"tables/rows/checkboxes = {observed}, checkboxes={boxes}") assert kit.rb_value(boxes[0], "Show only your favorite songs"), boxes assert kit.rb_value(rbr.label_values(ax, win.id), "No records yet"), \ rbr.label_values(ax, win.id) assert len(ax.find(role="column", root_id=win.id, max_results=4)) >= 1 rbr.screenshot_assert( "structure_history_window", "The small 'History' window is open and empty: it shows only the centred grey " "text 'No records yet' inside an empty list area, with a 'Show only your " "favorite songs' checkbox (unticked) below it. No station rows are listed.")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685"""AX TEXT-content tests for Radiola (macOS status-bar radio player).
Every expected string below was OBSERVED on the running reference app and is recorded inrecon.md `## TEXT` / `## AX_TREE`. Radiola has NO window at launch, so almost all of itstext lives behind the status menu or behind a window that has to be revealed first — hencemost tests declare depth 1-2 and back it with an `rbr.rb_enter_*` / `rbr.rb_reach_*` call.
Contract notes: * plain `ax` fixture ONLY (`ax_with_reset` blind-presses every menu-bar item and leaves stray system menus open — see recon `## APP`). * never press: prefs `Audio` tab (crashes the app), `Remove station`, a sheet's OK button, `Check for Updates now`, `Quit`, `Quit Radiola`, `Radiola Help`, Export/Import stations. * every menu test finishes with `rbr.close_all_menus(ax)`."""
from __future__ import annotations
import time
import pytest
import rb_radiola as rbrimport rb_testgen_kit as kit
# ── expected text, verbatim from recon `## TEXT` ────────────────────────────────────────
DEFAULT_TOOLTIP = "Radio Caroline"SEP_LINE = "⎯" * 28 # 28x U+23AF HORIZONTAL LINE EXTENSIONSTATUS_MENU_HEADER = "Favorite stations"PLAY_ITEM_FAVORITE_TITLE = "Mark current song as favorite"PLAY_ICON_PAUSED = "Play"
SIDEBAR_LABELS = ("My lists", "My stations", "Radio browser", "By tag", "By name", "By country")STATION_ROWS = ((rbr.STATION_1, rbr.STATION_1_URL), (rbr.STATION_2, rbr.STATION_2_URL), (rbr.STATION_3, rbr.STATION_3_URL))
HISTORY_EMPTY_TEXT = "No records yet"HISTORY_CHECKBOX = "Show only your favorite songs"
ADD_STATION_LABELS = ("To add a station, fill out the following information:", "Title:", "Url:")ADD_GROUP_LABELS = ("To add a group, fill out the following information:", "Title:")
CONTROLS_LABELS = ("Left mouse button:", "Middle mouse button:", "Right mouse button:", "Mouse wheel:", "You can always open the menu with Control+Mouse Click", "Media key handling:", "Previous and next track buttons:", "Global shortcut to show stations", "Global shortcut to show history")CONTROLS_POPUP_VALUES = ("shows the popup menu", "shows the popup menu", "shows the popup menu", "does nothing", "always", "does nothing")
APPEARANCE_LABEL = "Show groups in favorites:"APPEARANCE_POPUP_VALUE = "as a flat list"TOOLTIP_CHECKBOX = "Show a tooltip with the radiostation and song"APPEARANCE_CHECKBOXES = ("Show the volume control in the menu", "Show the mute item in the menu", 'Show the "Copy song title and artist" item in the menu', TOOLTIP_CHECKBOX)
STARTUP_CHECKBOX = "Play last station on startup"UPDATES_BUTTON = "Check for Updates now" # NEVER pressUPDATES_CHECKBOX = "Automatically check for updates"
ABOUT_APP_LABEL = "Radiola"ABOUT_COPYRIGHT = "Copyright © 2020 Alex Sokolov. All rights reserved."ABOUT_LINKS = ("project's homepage", "project's issues page")ABOUT_CREDITS_PREFIX = ("You can learn a bit more about the program on the " "project's homepage.")
# ── tiny local read helpers (no navigation — they never affect declared depth) ──────────
def _text(ax, el): """AXValue of an element as a plain string ('' when absent).""" if el is None: return None return str(rbr._val(ax, el.id) or "")
def _title(ax, el): """AXTitle (falling back to the element's AXTitle/AXDescription name).""" if el is None: return None t = ax.get(el.id, ["AXTitle"]).get("AXTitle") if t in (None, ""): t = el.name or "" return str(t)
def _help(ax, el): if el is None: return None return str(ax.get(el.id, ["AXHelp"]).get("AXHelp") or "")
def _popup_text(ax, el): """The string a popup button currently DISPLAYS (AXValue on AppKit, AXTitle on some SwiftUI/Qt builds).""" if el is None: return None v = rbr._val(ax, el.id) if v in (None, ""): v = el.name or "" return str(v)
def _wait_until(read, ok, timeout=5.0, step=0.25): """Poll `read()` until `ok(value)`; return the last value read.""" val = read() t0 = time.time() while not ok(val) and time.time() - t0 < timeout: time.sleep(step) val = read() return val
def _label_texts(ax, root_id=None): """Every readable static-text string under `root_id`.
Locate by SEMANTICS, not by framework internals: AppKit publishes a static text's string in AXValue (what `rbr.label_values` reads) while some SwiftUI/Qt builds publish it as AXTitle/AXDescription, so union both. """ out = [] for l in ax.find(role="label", root_id=root_id, max_results=80): for t in (rbr._val(ax, l.id), l.name): s = str(t or "").strip() if s and s not in out: out.append(s) return out
def _toolbar_labels(ax, win): """(song_text, station_text, station_element) of the Stations window toolbar.
Preferred locator: the two labels that carry an AXHelp (the reference marks exactly those two that way). Fallback for a recreation that omits AXHelp: the window's static texts minus the sidebar entries, in tree order (song first, station second). """ labs = rbr.stations_station_labels(ax, win) if len(labs) < 2: side = {t for (_e, t) in rbr.sidebar_labels(ax, win)} labs = [(l, str(rbr._val(ax, l.id) or "")) for l in ax.find(role="label", root_id=win.id, max_results=80) if str(rbr._val(ax, l.id) or "") not in side] if len(labs) < 2: return None, None, None return str(labs[0][1] or ""), str(labs[1][1] or ""), labs[1][0]
def _with_and_without_text(values): """(#widgets that carry text, #widgets that do not) — text-accessibility census.""" with_text = [v for v in values if v is not None and str(v).strip()] return len(with_text), len(values) - len(with_text)
def _label_census(ax, root_id=None): """(total static-text widgets, how many actually expose readable text) under root_id.""" vals = [] for l in ax.find(role="label", root_id=root_id, max_results=80): v = rbr._val(ax, l.id) if v in (None, ""): v = l.name vals.append(str(v or "")) have, _without = _with_and_without_text(vals) return len(vals), have
# ────────────────────────────────────────────────────────────────────────────────────────# 1. the status item itself (the only always-present surface)# ────────────────────────────────────────────────────────────────────────────────────────
class TestStatusItemText:
@pytest.mark.rb(depth=0, jump_kind="value", expect="status-item AXHelp tooltip reads 'Radio Caroline' on a fresh launch") def test_status_item_tooltip_default_station(self, ax): si = rbr.status_item(ax) assert si is not None, "no status-bar item found" tip = rbr.status_item_tooltip(ax) # non-empty, and the character count matches the actual text length assert tip.strip(), f"status-item tooltip is empty: {tip!r}" assert len(tip) == len(DEFAULT_TOOLTIP), f"tooltip {tip!r} has {len(tip)} chars" assert "\n" not in tip, f"paused tooltip must be a single line, got {tip!r}" assert kit.rb_value(tip, DEFAULT_TOOLTIP)
@pytest.mark.rb(depth=1, jump_kind="value", expect="status-item tooltip == the status menu's first favourite entry 'Radio Caroline'") def test_tooltip_matches_first_favorite_entry(self, ax): tip = rbr.status_item_tooltip(ax) menu = rbr.rb_reach_status_menu(ax) try: assert menu is not None, "status menu did not open" favs = rbr.status_menu_favorite_names(ax, menu) assert favs, "status menu exposes no favourite station entries" assert kit.rb_value(tip, favs[0]) assert kit.rb_value(favs[0], DEFAULT_TOOLTIP) finally: rbr.close_all_menus(ax)
# ────────────────────────────────────────────────────────────────────────────────────────# 2. the status menu (depth 1)# ────────────────────────────────────────────────────────────────────────────────────────
class TestStatusMenuText:
@pytest.mark.rb(depth=1, jump_kind="value", expect="status menu shows header 'Favorite stations', the 3 exact station titles and the 4 command titles") def test_status_menu_header_stations_and_commands(self, ax): menu = rbr.rb_reach_status_menu(ax) try: assert menu is not None, "status menu did not open" items = rbr.status_menu_items(ax, menu) names = [n for (n, _en, _c) in items]
header = [(n, en) for (n, en, _c) in items if n == STATUS_MENU_HEADER] assert header, f"no '{STATUS_MENU_HEADER}' header; items={names}" assert not header[0][1], "the 'Favorite stations' header must be DISABLED" assert kit.rb_value(header[0][0], STATUS_MENU_HEADER)
favs = rbr.status_menu_favorite_names(ax, menu) assert kit.rb_value(favs, list(rbr.DEFAULT_STATIONS)), \ f"favourite entries {favs!r}" # the third title carries a LITERAL '&' entity in the reference assert kit.rb_value(favs[2], "&")
cmds = [n for n in names if n in rbr.STATUS_MENU_COMMANDS] assert kit.rb_value(cmds, list(rbr.STATUS_MENU_COMMANDS)), \ f"command items {cmds!r} of {names!r}"
rbr.screenshot_assert( "text_status_menu", "Radiola's status menu is open under the right end of the macOS menu bar: a " "play triangle with the station name 'Radio Caroline' at the top, then a " "greyed-out 'Favorite stations' header followed by three entries " "'Radio Caroline', \"Radio Caroline 319 Gold [ Hits from '60-'70 ]\" and " "'Radio Caroline 259 Gold [ Happy Rock & Album Station ]', then the " "commands Open Radiola, History..., Settings... and Quit.") finally: rbr.close_all_menus(ax)
@pytest.mark.rb(depth=1, jump_kind="value", expect="status-menu now-playing item: song '', station 'Radio Caroline', icon 'Play', checkbox 'Mark current song as favorite'") def test_status_menu_play_item_labels(self, ax): menu = rbr.rb_reach_status_menu(ax) try: assert menu is not None, "status menu did not open" info = rbr.status_menu_play_item(ax, menu) song_el, station_el = info.get("song"), info.get("station") assert song_el is not None and station_el is not None, \ f"now-playing item exposes {len(info.get('labels') or [])} labels, expected 2"
song = _text(ax, song_el) station = _text(ax, station_el) icon_title = _title(ax, info.get("icon")) fav_title = _title(ax, info.get("favorite"))
assert kit.rb_value(song, ""), f"paused song label should be empty, got {song!r}" assert kit.rb_value(station, DEFAULT_TOOLTIP) assert kit.rb_value(icon_title, PLAY_ICON_PAUSED) assert kit.rb_value(fav_title, PLAY_ITEM_FAVORITE_TITLE)
# text census for the now-playing view: 1 label with content, 1 without have, missing = _with_and_without_text([song, station]) assert (have, missing) == (1, 1), \ f"expected exactly one populated label while paused, got {have}/{have + missing}" finally: rbr.close_all_menus(ax)
# ────────────────────────────────────────────────────────────────────────────────────────# 3. the Stations window (depth 1)# ────────────────────────────────────────────────────────────────────────────────────────
class TestStationsWindowText:
@pytest.mark.rb(depth=1, jump_kind="value", expect="Stations sidebar labels read My lists / My stations / Radio browser / By tag / By name / By country") def test_stations_sidebar_labels(self, ax): win = rbr.rb_enter_stations_window(ax) assert win is not None, "the Stations window was not revealed" labels = [t for (_el, t) in rbr.sidebar_labels(ax, win)] assert len(labels) == len(SIDEBAR_LABELS), f"sidebar labels: {labels!r}" assert all(t.strip() for t in labels), f"blank sidebar label in {labels!r}" assert kit.rb_value(labels, list(SIDEBAR_LABELS)) # each sidebar entry's character count matches its expected string assert [len(t) for t in labels] == [len(t) for t in SIDEBAR_LABELS]
# text-accessibility census: every sidebar entry plus the current-station label # exposes readable text; the idle song label is the app's only blank static text. total, with_text = _label_census(ax, win.id) assert total >= len(SIDEBAR_LABELS) + 1, f"only {total} static texts in the window" assert with_text >= len(SIDEBAR_LABELS) + 1, \ f"only {with_text}/{total} static texts expose readable text" assert total - with_text <= 2, \ f"{total - with_text} blank labels (expected at most the idle song label)"
@pytest.mark.rb(depth=1, jump_kind="value", expect="the 3 station rows read their exact (title, url) pairs, e.g. ('Radio Caroline', 'http://sc3.radiocaroline.net:8030')") def test_stations_row_titles_and_urls(self, ax): win = rbr.rb_enter_stations_window(ax) assert win is not None, "the Stations window was not revealed" rows = [tuple(r) for r in rbr.station_rows(ax, win)] assert len(rows) == 3, f"station rows: {rows!r}" assert kit.rb_value(rows, list(STATION_ROWS)), f"station rows: {rows!r}" # every row cell carries text (no blank titles / urls) cells = [c for row in rows for c in row] have, missing = _with_and_without_text(cells) assert (have, missing) == (6, 0), f"{missing} blank row cells in {rows!r}" assert kit.rb_value(rows[2][0], "&")
@pytest.mark.rb(depth=1, jump_kind="value", expect="Stations toolbar: song label '' and station label 'Radio Caroline' (AXHelp 'Radio Caroline')") def test_stations_toolbar_song_and_station_labels(self, ax): win = rbr.rb_enter_stations_window(ax) assert win is not None, "the Stations window was not revealed" song, station, station_el = _toolbar_labels(ax, win) assert station_el is not None, "no song + station labels in the Stations toolbar"
assert kit.rb_value(song, ""), f"idle song label should be empty, got {song!r}" assert kit.rb_value(station, DEFAULT_TOOLTIP) assert len(station) == len(DEFAULT_TOOLTIP) # the station label repeats its text as its own tooltip in the reference assert kit.rb_value(_help(ax, station_el), DEFAULT_TOOLTIP) # text census: exactly one of the two toolbar labels carries content while idle have, missing = _with_and_without_text([song, station]) assert (have, missing) == (1, 1), f"toolbar labels: {song!r} / {station!r}"
rbr.screenshot_assert( "text_stations_window", "Radiola's 'Stations' window: a left sidebar listing 'My lists' with the selected " "'My stations', and 'Radio browser' with 'By tag', 'By name', 'By country'; a " "toolbar with a play triangle, the current station text 'Radio Caroline' and a " "volume slider; and three station rows 'Radio Caroline', " "\"Radio Caroline 319 Gold [ Hits from '60-'70 ]\" and " "'Radio Caroline 259 Gold [ Happy Rock & Album Station ]' with their " "http:// urls, each with a yellow star and a '...' button; Add station / " "Add group / Remove station sit at the bottom.")
# ────────────────────────────────────────────────────────────────────────────────────────# 4. the History window (depth 1)# ────────────────────────────────────────────────────────────────────────────────────────
class TestHistoryWindowText:
@pytest.mark.rb(depth=1, jump_kind="value", expect="History window shows the placeholder 'No records yet' and the checkbox 'Show only your favorite songs'") def test_history_placeholder_and_checkbox_text(self, ax): win = rbr.rb_enter_history_window(ax) assert win is not None, "the History window was not revealed" labels = _label_texts(ax, win.id) assert HISTORY_EMPTY_TEXT in labels, f"History labels: {labels!r}" assert kit.rb_value(labels, HISTORY_EMPTY_TEXT) # character count of the placeholder + census of the window's static texts placeholder = [t for t in labels if t == HISTORY_EMPTY_TEXT][0] assert len(placeholder) == len(HISTORY_EMPTY_TEXT) total, with_text = _label_census(ax, win.id) assert with_text >= 1, f"no readable static text in the History window ({total} labels)" assert total - with_text <= 1, f"{total - with_text} blank labels: {labels!r}"
cb = rbr.history_favorites_checkbox(ax, win) assert cb is not None, "no 'favorite songs' checkbox in the History window" assert kit.rb_value(cb.name, HISTORY_CHECKBOX)
rbr.screenshot_assert( "text_history_window", "Radiola's small 'History' window is open and empty: the centred grey text " "'No records yet' fills the table area and an unticked checkbox labelled " "'Show only your favorite songs' sits at the bottom.")
# ────────────────────────────────────────────────────────────────────────────────────────# 5. the preferences window — one test per TAB (never touch the Audio tab)# ────────────────────────────────────────────────────────────────────────────────────────
class TestPreferencesControlsText:
@pytest.mark.rb(depth=1, jump_kind="value", expect="prefs Controls tab shows its 9 labels, e.g. 'Left mouse button:' and 'You can always open the menu with Control+Mouse Click'") def test_prefs_controls_labels(self, ax): win = rbr.rb_enter_settings_window(ax) assert win is not None, "the preferences window was not revealed" assert kit.rb_value(rbr.settings_tab_title(ax), "Controls")
labels = _label_texts(ax, win.id) missing = [t for t in CONTROLS_LABELS if t not in labels] assert not missing, f"missing Controls labels {missing!r}; got {labels!r}" found = sorted({t for t in labels if t in CONTROLS_LABELS}) assert kit.rb_value(found, sorted(CONTROLS_LABELS)) # census: every static text in the Controls pane exposes readable text total, with_text = _label_census(ax, win.id) assert with_text >= len(CONTROLS_LABELS), \ f"only {with_text}/{total} Controls static texts are readable" assert total - with_text <= 1, f"{total - with_text} blank Controls labels"
@pytest.mark.rb(depth=1, jump_kind="value", expect="prefs Controls popups read 'shows the popup menu' x3, 'does nothing' x2 and 'always'") def test_prefs_controls_popup_values(self, ax): win = rbr.rb_enter_settings_window(ax) assert win is not None, "the preferences window was not revealed" popups = ax.find(role="popup", root_id=win.id, max_results=20) values = [_popup_text(ax, p) for p in popups] assert len(values) == len(CONTROLS_POPUP_VALUES), f"popup values: {values!r}" have, missing = _with_and_without_text(values) assert (have, missing) == (6, 0), f"{missing} popups render no text: {values!r}" assert kit.rb_value(sorted(values), sorted(CONTROLS_POPUP_VALUES)), \ f"popup values: {values!r}"
class TestPreferencesAppearanceText:
@pytest.mark.rb(depth=1, jump_kind="value", expect="prefs Appearance shows 'Show groups in favorites:' + popup 'as a flat list' and the 4 checkbox titles") def test_prefs_appearance_labels_and_checkboxes(self, ax): win = rbr.rb_enter_settings_tab(ax, "Appearance") assert win is not None, "the Appearance settings tab was not reached" assert kit.rb_value(rbr.settings_tab_title(ax), "Appearance")
labels = _label_texts(ax, win.id) assert APPEARANCE_LABEL in labels, f"Appearance labels: {labels!r}" assert kit.rb_value(labels, APPEARANCE_LABEL)
popups = ax.find(role="popup", root_id=win.id, max_results=5) assert popups, "no 'Show groups in favorites' popup" assert kit.rb_value(_popup_text(ax, popups[0]), APPEARANCE_POPUP_VALUE)
cbs = rbr.checkboxes(ax, win.id) missing = [t for t in APPEARANCE_CHECKBOXES if t not in cbs] assert not missing, f"missing Appearance checkboxes {missing!r}; got {sorted(cbs)!r}" found = sorted(t for t in cbs if t in APPEARANCE_CHECKBOXES) assert kit.rb_value(found, sorted(APPEARANCE_CHECKBOXES))
rbr.screenshot_assert( "text_prefs_appearance", "Radiola's preferences window titled 'Appearance' with a five-icon toolbar " "(Controls, Appearance, Audio, Startup, Updates) and Appearance selected; the " "pane shows a 'Show groups in favorites:' dropdown reading 'as a flat list' and " "four checkboxes: 'Show the volume control in the menu', 'Show the mute item in " "the menu', 'Show the \"Copy song title and artist\" item in the menu' and the " "ticked 'Show a tooltip with the radiostation and song'.")
class TestPreferencesStartupUpdatesText:
@pytest.mark.rb(depth=1, jump_kind="value", expect="prefs Startup tab shows the single checkbox 'Play last station on startup'") def test_prefs_startup_checkbox_text(self, ax): win = rbr.rb_enter_settings_tab(ax, "Startup") assert win is not None, "the Startup settings tab was not reached" assert kit.rb_value(rbr.settings_tab_title(ax), "Startup") names = sorted(rbr.checkboxes(ax, win.id)) assert names == [STARTUP_CHECKBOX], f"Startup checkboxes: {names!r}" assert kit.rb_value(names, STARTUP_CHECKBOX)
@pytest.mark.rb(depth=1, jump_kind="value", expect="prefs Updates tab shows button 'Check for Updates now' and checkbox 'Automatically check for updates'") def test_prefs_updates_button_and_checkbox_text(self, ax): win = rbr.rb_enter_settings_tab(ax, "Updates") assert win is not None, "the Updates settings tab was not reached" assert kit.rb_value(rbr.settings_tab_title(ax), "Updates")
# the button's TITLE only — it is NEVER pressed (Sparkle network panel). titles = sorted(rbr.buttons(ax, win.id)) assert UPDATES_BUTTON in titles, f"Updates buttons: {titles!r}" assert kit.rb_value(titles, UPDATES_BUTTON) assert all(t.strip() for t in titles), f"blank button title in {titles!r}"
names = sorted(rbr.checkboxes(ax, win.id)) assert names == [UPDATES_CHECKBOX], f"Updates checkboxes: {names!r}" assert kit.rb_value(names, UPDATES_CHECKBOX)
# ────────────────────────────────────────────────────────────────────────────────────────# 6. modal sheets (depth 2) — opened and ALWAYS cancelled, never confirmed# ────────────────────────────────────────────────────────────────────────────────────────
class TestSheetText:
@pytest.mark.rb(depth=2, jump_kind="value", expect="Add-station sheet reads 'To add a station, fill out the following information:' / 'Title:' / 'Url:' and Add-group reads its 2 labels") def test_add_station_and_group_sheet_labels(self, ax): win = rbr.rb_enter_stations_window(ax) assert win is not None, "the Stations window was not revealed" try: sheet = rbr.rb_reach_add_station_sheet(ax, win) assert sheet is not None, "the 'Add station' sheet did not appear" labels = _label_texts(ax, sheet.id) missing = [t for t in ADD_STATION_LABELS if t not in labels] assert not missing, f"missing Add-station labels {missing!r}; got {labels!r}" assert kit.rb_value(sorted(t for t in labels if t in ADD_STATION_LABELS), sorted(ADD_STATION_LABELS)) # the two entry fields are EMPTY when the sheet opens assert rbr.text_field_values(ax, sheet.id) == [], "sheet fields are prefilled" rbr.screenshot_assert( "text_add_station_sheet", "A modal sheet drops over Radiola's 'Stations' window reading 'To add a " "station, fill out the following information:' with empty 'Title:' and " "'Url:' text fields, a greyed-out 'Add station' button and an enabled " "'Cancel' button.") assert rbr.sheet_cancel(ax, sheet) time.sleep(0.4)
sheet2 = rbr.rb_reach_add_group_sheet(ax, win) assert sheet2 is not None, "the 'Add group' sheet did not appear" labels2 = _label_texts(ax, sheet2.id) missing2 = [t for t in ADD_GROUP_LABELS if t not in labels2] assert not missing2, f"missing Add-group labels {missing2!r}; got {labels2!r}" assert kit.rb_value(sorted(t for t in labels2 if t in ADD_GROUP_LABELS), sorted(ADD_GROUP_LABELS)) finally: rbr.sheet_cancel(ax) # never confirm — the OPML would be rewritten
# ────────────────────────────────────────────────────────────────────────────────────────# 7. the About panel (depth 1)# ────────────────────────────────────────────────────────────────────────────────────────
class TestAboutPanelText:
@pytest.mark.rb(depth=1, jump_kind="value", expect="About panel reads 'Radiola', 'Copyright (c) 2020 Alex Sokolov. All rights reserved.', links 'project's homepage'/'project's issues page' and credits starting 'You can learn a bit more...'") def test_about_panel_text(self, ax): menu = rbr.rb_enter_app_menu(ax, "Radiola") assert menu is not None, "the 'Radiola' app menu is missing" item = rbr.menu_item_by_name(ax, menu, "About Radiola") assert item is not None, f"no 'About Radiola' item in {rbr.menu_item_names(ax, menu)!r}" rbr.press(ax, item)
labels = _wait_until(lambda: _label_texts(ax), lambda ls: any(ABOUT_COPYRIGHT in l for l in ls), timeout=8.0) assert ABOUT_APP_LABEL in labels, f"About labels: {labels!r}" assert ABOUT_COPYRIGHT in labels, f"About labels: {labels!r}" assert kit.rb_value(labels, ABOUT_COPYRIGHT) # the version label is a build constant — deliberately NOT asserted.
links = sorted((l.name or "") for l in ax.find(role="link", max_results=10)) assert kit.rb_value(links, sorted(ABOUT_LINKS)), f"About links: {links!r}" assert all(t.strip() for t in links), f"a link renders no text: {links!r}"
areas = ax.find(role="text_area", max_results=5) assert areas, "the About panel exposes no credits text area" credits = max((_text(ax, a) or "" for a in areas), key=len) assert credits.startswith(ABOUT_CREDITS_PREFIX), f"credits start: {credits[:120]!r}" assert len(credits) >= len(ABOUT_CREDITS_PREFIX) assert kit.rb_value(credits, ABOUT_CREDITS_PREFIX)
rbr.screenshot_assert( "text_about_panel", "Radiola's About panel: the round app icon on the left, the title 'Radiola' with " "a version line under it, the line 'Copyright © 2020 Alex Sokolov. All rights " "reserved.', and a credits paragraph beginning 'You can learn a bit more about " "the program on the project's homepage.' containing two blue links, " "\"project's homepage\" and \"project's issues page\".") # no status/context menu was opened here (AXPress on a menu ITEM does not open # the menu of a background app), so nothing needs closing.
# ────────────────────────────────────────────────────────────────────────────────────────# 8. text that CHANGES after an interaction# ────────────────────────────────────────────────────────────────────────────────────────
class TestTextChanges:
@pytest.mark.rb(depth=1, jump_kind="transition", expect="Stations song label flips '' -> 'Connecting...' after pressing the play button") def test_song_label_changes_to_connecting(self, ax): win = rbr.rb_enter_stations_window(ax) assert win is not None, "the Stations window was not revealed" before, _st, _el = _toolbar_labels(ax, win) assert kit.rb_value(before, ""), f"song label before play: {before!r}"
btn = rbr.stations_play_button(ax, win) assert btn is not None, "no play button in the Stations window" assert rbr.press(ax, btn), "AXPress on the play button failed"
after = _wait_until(lambda: _toolbar_labels(ax, win)[0], lambda v: bool(v), timeout=6.0) assert kit.rb_flip(before, after, "Stations song label"), \ f"song label did not change: {before!r} -> {after!r}" assert kit.rb_value(after, rbr.CONNECTING_TEXT)
rbr.screenshot_assert( "text_playing_state", "Radiola's 'Stations' window right after the play button was pressed: the " "toolbar triangle has become a pause bar and the word 'Connecting...' is shown " "above the station name 'Radio Caroline'; the three station rows are unchanged.")
@pytest.mark.rb(depth=2, jump_kind="value", expect="after picking status-menu station 2 the tooltip reads \"<title>\\n⎯*28\\nConnecting...\" and the play-item station label becomes that title") def test_status_menu_station_selection_text(self, ax): menu = rbr.rb_reach_status_menu(ax) try: assert menu is not None, "status menu did not open" before_station = _text(ax, rbr.status_menu_play_item(ax, menu).get("station")) assert kit.rb_value(before_station, DEFAULT_TOOLTIP)
item = rbr.status_menu_item(ax, menu, rbr.STATION_2) assert item is not None, "station 2 is not in the status menu" rbr.press(ax, item) time.sleep(1.0)
expected_tip = rbr.STATION_2 + "\n" + SEP_LINE + "\n" + rbr.CONNECTING_TEXT tip = _wait_until(lambda: rbr.status_item_tooltip(ax), lambda v: rbr.CONNECTING_TEXT in v, timeout=6.0) assert kit.rb_value(tip, expected_tip), f"tooltip: {tip!r}"
menu2 = rbr.rb_reach_status_menu(ax) assert menu2 is not None, "status menu did not re-open" after_station = _text(ax, rbr.status_menu_play_item(ax, menu2).get("station")) assert kit.rb_flip(before_station, after_station, "play-item station label") assert kit.rb_value(after_station, rbr.STATION_2) finally: rbr.close_all_menus(ax)
@pytest.mark.rb(depth=1, jump_kind="transition", expect="preferences window title flips 'Controls' -> 'Startup' when the Startup tab is selected") def test_prefs_tab_switch_changes_window_title(self, ax): win = rbr.rb_enter_settings_window(ax) assert win is not None, "the preferences window was not revealed" before = rbr.settings_tab_title(ax) assert kit.rb_value(before, "Controls"), f"initial prefs title: {before!r}"
assert rbr.rb_enter_settings_tab(ax, "Startup") is not None, \ "the Startup tab was not reached" after = rbr.settings_tab_title(ax) assert kit.rb_flip(before, after, "preferences window title"), \ f"title did not change: {before!r} -> {after!r}" assert kit.rb_value(after, "Startup")
@pytest.mark.rb(depth=1, jump_kind="value", expect="unticking 'Show a tooltip with the radiostation and song' makes the status-item tooltip read ''") def test_untick_tooltip_option_clears_status_tooltip(self, ax): before_tip = rbr.status_item_tooltip(ax) win = rbr.rb_enter_settings_tab(ax, "Appearance") assert win is not None, "the Appearance settings tab was not reached" cbs = rbr.checkboxes(ax, win.id) cb = cbs.get(TOOLTIP_CHECKBOX) or rbr.find_by_keywords(list(cbs.values()), ["tooltip"]) assert cb is not None, f"no tooltip checkbox; got {sorted(cbs)!r}" assert kit.rb_value(cb.name, TOOLTIP_CHECKBOX) try: assert rbr.press(ax, cb), "AXPress on the tooltip checkbox failed" after_tip = _wait_until(lambda: rbr.status_item_tooltip(ax), lambda v: v == "", timeout=4.0) assert kit.rb_value(before_tip, DEFAULT_TOOLTIP) assert kit.rb_flip(before_tip, after_tip, "status-item tooltip") assert kit.rb_value(after_tip, "") finally: rbr.press(ax, cb) # restore the default so nothing leaks time.sleep(0.3)
# ────────────────────────────────────────────────────────────────────────────────────────# 9. text that is NOT in the AX tree — the radio-browser search panel (recon ## UNREACHED)# ────────────────────────────────────────────────────────────────────────────────────────
class TestVisualOnlyText:
@pytest.mark.rb(depth=2, jump_kind="transition", expect="switching the sidebar to 'By tag' empties the station rows (3 -> 0); the search panel's own text is visual-only") def test_radio_browser_search_panel_is_visual_only(self, ax): win = rbr.rb_enter_stations_window(ax) assert win is not None, "the Stations window was not revealed" before_rows = rbr.station_rows(ax, win) assert kit.rb_value(len(before_rows), 3), f"rows before: {before_rows!r}"
assert rbr.rb_enter_sidebar_list(ax, "By tag", win), \ "the 'By tag' sidebar entry could not be selected" after_rows = rbr.station_rows(ax, win)
rbr.screenshot_assert( "text_search_panel", "Radiola's 'Stations' window with 'By tag' selected under 'Radio browser' in the " "sidebar: the window has widened and the local station list is empty; across the " "top of the content pane sits the internet-search bar — a 'contains' dropdown on " "the left, a rounded Search field with a magnifier glyph and the placeholder " "'Search' in the middle, and a 'sort by votes' dropdown on the right. None of " "that text is exposed through accessibility, so it is judged visually.")
assert kit.rb_flip(len(before_rows), len(after_rows), "station row count"), \ f"rows unchanged: {before_rows!r} -> {after_rows!r}" assert after_rows == [], f"rows after switching to 'By tag': {after_rows!r}"123456789101112131415161718192021222324252627282930313233343536{ "ax_total": 91, "vlm_total": 15, "ax_by_lane": { "test_ax_buttons.py": 17, "test_ax_computation.py": 15, "test_ax_states.py": 20, "test_ax_structure.py": 19, "test_ax_text.py": 20 }, "vlm_by_dir": { "buttons": 2, "computation": 1, "states": 2, "structure": 4, "text": 6 }, "vlm_names": [ "buttons_add_station_sheet.png", "buttons_prefs_appearance_tab.png", "computation_mute_disables_volume.png", "states_appearance_menu_checkboxes_ticked.png", "states_status_menu_volume_and_mute.png", "structure_add_station_sheet.png", "structure_history_window.png", "structure_prefs_appearance.png", "structure_status_menu_open.png", "text_add_station_sheet.png", "text_history_window.png", "text_playing_state.png", "text_prefs_appearance.png", "text_search_panel.png", "text_status_menu.png" ], "frozen_at": "stage2_finalize"}macos/shuang886-terminader/tests/fixtures/rbtest/gamma.txtAdded+1
macos/shuang886-terminader/tests/fixtures/rbtest/readme.mdAdded+3
macos/shuang886-terminader/tests/fixtures/rbtest/subdir/nested.txtAdded+1
macos/shuang886-terminader/tests/rb_testgen_kit.pyAdded+575
macos/shuang886-terminader/tests/requirements.txtAdded+3
macos/shuang886-terminader/tests/terminader_helpers.pyAdded+671
macos/shuang886-terminader/tests/test_ax_buttons.pyAdded+579
macos/shuang886-terminader/tests/test_ax_computation.pyAdded+702
macos/shuang886-terminader/tests/test_ax_menus.pyAdded+409
macos/shuang886-terminader/tests/test_ax_states.pyAdded+605
macos/shuang886-terminader/tests/test_ax_structure.pyAdded+705
macos/shuang886-terminader/tests/test_ax_text.pyAdded+561
macos/shuang886-terminader/tests/testcase_counts.jsonAdded+48
macos/shuang886-terminader/tests/verifier_helpers.pyAdded+753
macos/shuang886-terminader/vlm_assertions.jsonAdded+309
macos/sn4k3-uvtools/LICENSEAdded+661
macos/sn4k3-uvtools/instance.jsonAdded+10
macos/sn4k3-uvtools/reference/build.shAdded+234
macos/sn4k3-uvtools/reference/launch.shAdded+53
macos/sn4k3-uvtools/tests/ax_helpers.pyAdded+849
macos/sn4k3-uvtools/tests/conftest.pyAdded+584
macos/sn4k3-uvtools/tests/rb_testgen_kit.pyAdded+575
macos/sn4k3-uvtools/tests/requirements.txtAdded+3
macos/sn4k3-uvtools/tests/test_ax_buttons.pyAdded+681
macos/sn4k3-uvtools/tests/test_ax_computation.pyAdded+667
macos/sn4k3-uvtools/tests/test_ax_menus.pyAdded+604
macos/sn4k3-uvtools/tests/test_ax_states.pyAdded+855
macos/sn4k3-uvtools/tests/test_ax_structure.pyAdded+421
macos/sn4k3-uvtools/tests/test_ax_text.pyAdded+695
macos/sn4k3-uvtools/tests/testcase_counts.jsonAdded+37
macos/sn4k3-uvtools/tests/uv_helpers.pyAdded+615
macos/sn4k3-uvtools/tests/verifier_helpers.pyAdded+753
macos/sn4k3-uvtools/vlm_assertions.jsonAdded+205
macos/sokoloffa-radiola/LICENSEAdded+21
macos/sokoloffa-radiola/instance.jsonAdded+10
macos/sokoloffa-radiola/reference/build.shAdded+102
macos/sokoloffa-radiola/reference/launch.shAdded+48
macos/sokoloffa-radiola/tests/ax_helpers.pyAdded+849
macos/sokoloffa-radiola/tests/conftest.pyAdded+584
macos/sokoloffa-radiola/tests/rb_radiola.pyAdded+789
macos/sokoloffa-radiola/tests/rb_testgen_kit.pyAdded+575
macos/sokoloffa-radiola/tests/requirements.txtAdded+3
macos/sokoloffa-radiola/tests/test_ax_buttons.pyAdded+621
macos/sokoloffa-radiola/tests/test_ax_computation.pyAdded+629
macos/sokoloffa-radiola/tests/test_ax_states.pyAdded+799
macos/sokoloffa-radiola/tests/test_ax_structure.pyAdded+563
macos/sokoloffa-radiola/tests/test_ax_text.pyAdded+685
macos/sokoloffa-radiola/tests/testcase_counts.jsonAdded+36
macos/sokoloffa-radiola/tests/verifier_helpers.pyAdded
macos/sokoloffa-radiola/vlm_assertions.jsonAdded