diff --git a/macos/shuang886-terminader/tests/fixtures/rbtest/gamma.txt b/macos/shuang886-terminader/tests/fixtures/rbtest/gamma.txt new file mode 100644 index 0000000000000000000000000000000000000000..aadae79c527ba55582bf2b40455ea04781835d5c --- /dev/null +++ b/macos/shuang886-terminader/tests/fixtures/rbtest/gamma.txt @@ -0,0 +1 @@ +gamma-content diff --git a/macos/shuang886-terminader/tests/fixtures/rbtest/readme.md b/macos/shuang886-terminader/tests/fixtures/rbtest/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..38b7dd4c1f31fddb4854ff02eb0400c0e1d88e88 --- /dev/null +++ b/macos/shuang886-terminader/tests/fixtures/rbtest/readme.md @@ -0,0 +1,3 @@ +# Heading One + +Some *markdown* body text. diff --git a/macos/shuang886-terminader/tests/fixtures/rbtest/subdir/nested.txt b/macos/shuang886-terminader/tests/fixtures/rbtest/subdir/nested.txt new file mode 100644 index 0000000000000000000000000000000000000000..79c53955ef856f16f2107446bc721c8879a1bd2e --- /dev/null +++ b/macos/shuang886-terminader/tests/fixtures/rbtest/subdir/nested.txt @@ -0,0 +1 @@ +nested diff --git a/macos/shuang886-terminader/tests/rb_testgen_kit.py b/macos/shuang886-terminader/tests/rb_testgen_kit.py new file mode 100644 index 0000000000000000000000000000000000000000..ccbbdd3c6136513161c133fbb4cefcfb0386d55c --- /dev/null +++ b/macos/shuang886-terminader/tests/rb_testgen_kit.py @@ -0,0 +1,575 @@ +#!/usr/bin/env python3 +"""RB TestGen Kit (macOS/AX port of the Linux v7.5 kit) — a test's NAVIGATION +DEPTH and JUMP RIGOR are DECLARED (not inferred), uniformly recorded, and +self-auditable. + +DIFFERENCE FROM LINUX: macOS tests are **pytest** (methods on Test* classes taking +the `ax` fixture, plain asserts) — NOT standalone scripts calling R.record(). So the +DECLARATION is a pytest marker on the test method: + + import rb_testgen_kit as kit + + @pytest.mark.rb(depth=1, jump_kind="reach", expect="Preferences window visible") + def test_prefs_opens(self, ax_with_reset): + before = kit.rb_showing(ax_with_reset) + helpers.rb_reach_prefs(ax_with_reset) # a nav helper you name rb_reach_* / rb_enter_* + after = kit.rb_showing(ax_with_reset) + assert kit.rb_reach(before, after, target="Preferences", source="menu bar") + +conftest.py's pytest_runtest_makereport hook reads the marker + the test outcome and +writes {name, passed, depth, jump_kind, tier, expect} so the runner can fold it into +_results.json. The audits below then read those records (+ the test SOURCE). + +jump_kind (verbatim strings — the audit/stats key off them): + "none" no trigger; existence/structure only -> tier 0 + "liveness" only "did not crash / still alive" -> tier 1 (weak; avoid) + "reach" a real surface jump: the TARGET surface's element + APPEARED and the SOURCE surface's element DISAPPEARED -> tier 2 + "transition" a state flip (CHECKED/ENABLED/mode) before->after -> tier 2 + "value" a specific expected value/content was asserted -> tier 3 + +DEPTH is the number of surfaces crossed before the assertion (0 = home/first screen, +1 = one dialog/panel/submenu, 2+ = deeper). A flat-tree read of a deep element is +depth 0 — depth counts surfaces the test actually navigated through. + +REACH PROOF (so "reach" cannot be faked by reading a flat tree): + before = rb_showing(ax) + + 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('')" + python3 -c "import rb_testgen_kit as k; k.rb_lint('')" + python3 -c "import rb_testgen_kit as k; k.rb_lint_sources('')" + python3 -c "import rb_testgen_kit as k; k.rb_audit_depth('','')" +""" +from __future__ import annotations + +import ast +import glob +import json +import os +import re + +JUMP_KINDS = {"none": 0, "liveness": 1, "reach": 2, "transition": 2, "value": 3} + +# Double-axis quota TARGETS (fractions) — goals rb_audit REPORTS, NOT a hard gate. +QUOTAS = { + "existence_max": 0.30, # jump_kind=="none" share of ALL tests + "interactive_min": 0.60, # reach|transition|value share of ALL tests + "depth_ge1_min": 0.40, # depth>=1 share of INTERACTIVE tests + "depth_ge2_min": 0.10, # depth>=2 share of INTERACTIVE tests + "value_min": 0.25, # jump_kind=="value" share of INTERACTIVE tests +} + +# Depth family: a test "crosses a surface" iff it calls a member of the depth family. +# macOS accepts BOTH the naming convention rb_enter_*/rb_reach_* (write your own nav +# helper and NAME it so) AND the existing verifier_helpers/ax_helpers navigation +# functions (whitelist below) — so tests can reuse the mature reveal/navigate helpers. +DEPTH_FWD_RE = re.compile(r"^rb_(enter|reach)[a-z0-9_]*$") +DEPTH_BACK_RE = re.compile(r"^rb_back[a-z0-9_]*$") +# verifier_helpers / ax_helpers navigation functions that OPEN or move to a new surface. +FWD_WHITELIST = { + "ensure_ui_visible", "ensure_panel_open", "open_actions_menu", "open_menu", + "open_settings", "open_preferences", "open_dialog", "open_panel", "open_window", + "navigate_month", "navigate", "switch_tab", "switch_mode", "switch_page", + "select_tab", "reveal_window", "show_panel", "show_menu", +} +BACK_WHITELIST = { + "dismiss_menus", "dismiss_panel", "dismiss_any_dialog", "close_panel", + "close_window", "go_back", +} +# pytest fixtures that themselves navigate into a surface during setup (so a test taking +# one legitimately has depth>=1 without a nav call in its own body). `ax` does NOT navigate. +_NAV_FIXTURES = {"ax_with_reset", "open_panel"} +# MEASURED-TIER verdict families (ported from keliang): a tier2/3 jump_kind must be BACKED +# by its verdict function — transition->rb_flip*, value->rb_value*, reach->rb_reach* — whose +# bool result is the test's assertion. Self-named wrappers count by prefix. +TIER_FLIP_RE = re.compile(r"^rb_flip[a-z0-9_]*$") +TIER_VALUE_RE = re.compile(r"^rb_value[a-z0-9_]*$") +_JK_FAMILY = {"transition": "flip", "value": "value", "reach": "reach"} +# normalize plural (v73prep) / singular module names so a JSON module ("button") and a +# file stem ("buttons") join. +_MODULE_ALIAS = {"menus": "menu", "buttons": "button", "states": "state", + "structures": "structure", "texts": "text", + "computations": "computation", "workflows": "workflow"} + +_DEPTH = 0 # module-global surface counter for rb_enter/rb_back + + +def tier_of(jump_kind: str) -> int: + return JUMP_KINDS.get(jump_kind, 2) + + +def rb_reset_depth() -> None: + global _DEPTH + _DEPTH = 0 + + +def rb_enter(_surface: str = "") -> int: + """Call right after your test navigates into a new surface (dialog/panel/submenu).""" + global _DEPTH + _DEPTH += 1 + return _DEPTH + + +def rb_back() -> int: + global _DEPTH + _DEPTH = max(0, _DEPTH - 1) + return _DEPTH + + +def _walk_tree_nodes(node, out, seen): + """Yield 'role|name' for a macOS AXHelper.tree() dict node (+children).""" + if not isinstance(node, dict) or seen[0] >= 8000: + return + seen[0] += 1 + role = str(node.get("role") or "") + name = str(node.get("name") or node.get("value") or "") + if role or name: + out.add(f"{role}|{name}") + for c in (node.get("children") or []): + _walk_tree_nodes(c, out, seen) + + +def rb_showing(ax, max_depth: int = 12) -> set: + """Snapshot the currently-reachable AX subtree under the app as {"role|name"}. + macOS AX has no AT-SPI SHOWING/VISIBLE state, so we approximate "showing" by the + live AX tree (AXChildren) the app currently exposes — a new window/sheet/popover + adds its elements; a dismissed one removes them. Feed before+after a trigger to + rb_reach() so a 'reach' test proves a REAL surface change, not a flat-tree read. + Safe no-op (empty set) if `ax` cannot produce a tree.""" + out: set = set() + try: + tree = ax.tree(max_depth=max_depth) # AXHelper.tree() -> nested dict + except Exception: + return out + _walk_tree_nodes(tree, out, [0]) + return out + + +def rb_reach(before, after, target: str, source: str | None = None) -> bool: + """True-jump verdict: the TARGET surface's discriminating element newly APPEARED + AND (if given) the SOURCE surface's discriminating element DISAPPEARED. This is + what separates a real surface jump from reading an element that was always there.""" + before = set(before or []) + after = set(after or []) + t = target.lower() + appeared = any(t in k.lower() for k in (after - before)) + if source is None: + return appeared + s = source.lower() + src_before = any(s in k.lower() for k in before) + src_after = any(s in k.lower() for k in after) + return appeared and src_before and not src_after + + +def rb_flip(before, after, expect: str = "") -> bool: + """In-page STATE-FLIP verdict (tier2 `transition`): the observed state actually CHANGED + before->after (a CHECKED/ENABLED/mode/selection value read the two times). Pass its bool + as the test's assertion. Does NOT touch depth — an in-page flip is depth 0 unless you + navigated a surface to reach the control. You MAY write your own `rb_flip_()` 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_()` 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 | " + "{audit_depth|audit_tier} [results_dir]}") diff --git a/macos/shuang886-terminader/tests/requirements.txt b/macos/shuang886-terminader/tests/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..feef67ce2aadbaa26d12e6b01cff7b8ce89ecb5c --- /dev/null +++ b/macos/shuang886-terminader/tests/requirements.txt @@ -0,0 +1,3 @@ +pytest +pytest-check +pyobjc diff --git a/macos/shuang886-terminader/tests/terminader_helpers.py b/macos/shuang886-terminader/tests/terminader_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..893f9f116e2f605981d6000bc44bba8d9c0abbb2 --- /dev/null +++ b/macos/shuang886-terminader/tests/terminader_helpers.py @@ -0,0 +1,671 @@ +"""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 the +pytest 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_*` so +rb_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 prompt +The toolbar button on the trailing edge toggles between the two; its accessibility name +is the SF Symbol description ("terminal" in GUI mode, "Window" in CLI mode) and its +AXHelp is "Switch to Terminal" / "Switch to graphical interface". +""" + +from __future__ import annotations + +import json +import os +import re +import subprocess +import time +from 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 CLI +TOGGLE_NAME_CLI = "Window" # shown while in CLI mode -> press to get GUI +TOGGLE_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.doc +PASTE_HELP = "Paste selected items" +POPOUT_NAME = "rectangle.portrait.and.arrow.forward" +FOLDER_ICON_NAME = "Move" # folder.fill +FILE_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 = 36 +KC_DELETE = 51 +KC_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 " ➜ " 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 " 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 > .""" + 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) diff --git a/macos/shuang886-terminader/tests/test_ax_buttons.py b/macos/shuang886-terminader/tests/test_ax_buttons.py new file mode 100644 index 0000000000000000000000000000000000000000..b020584b9ec91c6773011d63d0541bdc4a28347b --- /dev/null +++ b/macos/shuang886-terminader/tests/test_ax_buttons.py @@ -0,0 +1,579 @@ +"""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 state +flip, 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 the +deployed conftest.py, and every interaction goes through the shared driver module +`terminader_helpers` (alias `th`). No absolute app paths, no `open -a`, no +AXUIElementCreateApplication, 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 os +import re +import sys +import 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+2014 +STATUS_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 ('.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 " + "' ➜' 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 ' 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 ' ' 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 ' 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, 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) diff --git a/macos/shuang886-terminader/tests/test_ax_computation.py b/macos/shuang886-terminader/tests/test_ax_computation.py new file mode 100644 index 0000000000000000000000000000000000000000..c8daf7679dc35160ae8f983b03fc374729db0a6f --- /dev/null +++ b/macos/shuang886-terminader/tests/test_ax_computation.py @@ -0,0 +1,702 @@ +"""COMPUTATION lane — Terminader. + +Terminader's CLI surface is a REAL command engine, so this lane is a genuine +input -> 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 rows +C1-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 of +the app under test. + +Portability: nothing here knows where the app is installed. The `ax` fixture launches it and +hands over an AXHelper; all driving goes through the shared `terminader_helpers` module. +""" + +from __future__ import annotations + +import json +import os +import subprocess +import sys +import time +from 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 driver +import 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 /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 ' % ' 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 ' ➜' 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 ' % 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 '/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 '/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}") diff --git a/macos/shuang886-terminader/tests/test_ax_menus.py b/macos/shuang886-terminader/tests/test_ax_menus.py new file mode 100644 index 0000000000000000000000000000000000000000..48699762ca9a8b8ff196d4f71f4e1c6b1d2de505 --- /dev/null +++ b/macos/shuang886-terminader/tests/test_ax_menus.py @@ -0,0 +1,409 @@ +"""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 in +recon.md (`## MENUS`, `## AX_TREE`, `## VISUAL`). Nothing here knows where the app is +installed: the `ax` / `ax_with_reset` fixtures from conftest.py hand each test an +AXHelper 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 parent +container 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 os +import sys +import 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", ".") + +# ── 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 /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'") diff --git a/macos/shuang886-terminader/tests/test_ax_states.py b/macos/shuang886-terminader/tests/test_ax_states.py new file mode 100644 index 0000000000000000000000000000000000000000..47fe52b80974e8f3282fa4d5079d93ff38bf2e91 --- /dev/null +++ b/macos/shuang886-terminader/tests/test_ax_states.py @@ -0,0 +1,605 @@ +"""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 the +reference 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 — no +absolute app paths, no `open -a`, no AXUIElementCreateApplication, no preference seeding. +""" + +from __future__ import annotations + +import os +import re +import sys +import time + +import pytest + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +import terminader_helpers as th # noqa: E402 +import 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.08333333333333333 +SLIDER_INCREMENT = 0.1 # AXIncrement step +ICON_BASE, ICON_SPAN = 32.0, 480.0 # largest icon extent == 32 + value * 480 +SPLITTER_VALUE = 140.0 # sidebar width +BADGE_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 ' ➜ ' 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})") diff --git a/macos/shuang886-terminader/tests/test_ax_structure.py b/macos/shuang886-terminader/tests/test_ax_structure.py new file mode 100644 index 0000000000000000000000000000000000000000..8fe1873385edccf183d92343e95f5d26c77abdd1 --- /dev/null +++ b/macos/shuang886-terminader/tests/test_ax_structure.py @@ -0,0 +1,705 @@ +"""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 exclusively +through `terminader_helpers` (`th.rb_enter_*` / `th.rb_reach_*`) so the SAME file drives +the 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 os +import re +import sys +import 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 "|", 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 ' 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 + " + "' 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 ' {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 " + "' ➜' prompt with a yellow block cursor along the bottom. No icon grid, " + "no ' 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 + ' 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 ' 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| 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 ' % ', " + "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" diff --git a/macos/shuang886-terminader/tests/test_ax_text.py b/macos/shuang886-terminader/tests/test_ax_text.py new file mode 100644 index 0000000000000000000000000000000000000000..31106073ebf06b1aa9cbd157302792fcdb26e1b6 --- /dev/null +++ b/macos/shuang886-terminader/tests/test_ax_text.py @@ -0,0 +1,561 @@ +"""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 the +reference app produced. + +pytest only: `Test*` classes, methods take the `ax` fixture (conftest launches the +app fresh per test and hands over an AXHelper). No argparse, no __main__, no +self-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'), the +free-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 os +import re +import sys +import 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", ".") + +EM_DASH = "—" # '—' U+2014, used by the pop-out title +SEARCH_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 ' ' -> '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, 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 ' 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 ' % ' + 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}") diff --git a/macos/shuang886-terminader/tests/testcase_counts.json b/macos/shuang886-terminader/tests/testcase_counts.json new file mode 100644 index 0000000000000000000000000000000000000000..5585f653a11b7861b6388da8d7b36baf8d2e3c6a --- /dev/null +++ b/macos/shuang886-terminader/tests/testcase_counts.json @@ -0,0 +1,48 @@ +{ + "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" + ] +} \ No newline at end of file diff --git a/macos/shuang886-terminader/tests/verifier_helpers.py b/macos/shuang886-terminader/tests/verifier_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..ce369cdae8db3a7427890d1636f8f5a3201dbef1 --- /dev/null +++ b/macos/shuang886-terminader/tests/verifier_helpers.py @@ -0,0 +1,753 @@ +""" +verifier_helpers.py — High-level AX testing patterns for macOS app verification. + +v6 core library. Encodes all robust testing patterns as reusable functions +so verifier agents call high-level APIs instead of building from scratch. + +Depends on: ax_helpers.py (AXHelper class) +""" + +import datetime +import os +import re +import signal +import subprocess +import time +from collections import Counter + +# --------------------------------------------------------------------------- +# Key codes (macOS virtual key codes) +# --------------------------------------------------------------------------- +KC_LEFT_ARROW = 123 +KC_RIGHT_ARROW = 124 +KC_UP_ARROW = 126 +KC_DOWN_ARROW = 125 +KC_SPACE = 49 +KC_RETURN = 36 +KC_TAB = 48 +KC_ESCAPE = 53 +KC_Q = 12 +KC_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": , "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)" + ) diff --git a/macos/shuang886-terminader/vlm_assertions.json b/macos/shuang886-terminader/vlm_assertions.json new file mode 100644 index 0000000000000000000000000000000000000000..cd4e39582f5f2e9003d67bc7dc95cdaa3f9d2c39 --- /dev/null +++ b/macos/shuang886-terminader/vlm_assertions.json @@ -0,0 +1,309 @@ +{ + "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 ' ➜' 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 ' % ' 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 ' ➜' 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 ' % 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 ' 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 ' ➜' prompt with a yellow block cursor along the bottom. No icon grid, no ' 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 ' 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, 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 + } +} \ No newline at end of file diff --git a/macos/sn4k3-uvtools/LICENSE b/macos/sn4k3-uvtools/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..0ad25db4bd1d86c452db3f9602ccdbe172438f52 --- /dev/null +++ b/macos/sn4k3-uvtools/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + 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 for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification 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 of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. 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 work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a 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 visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation 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 to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients 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 to +produce it from the Program, in the form of source code under the +terms 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 independent +works, 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 not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-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 excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the 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 install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional 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 you +add to a covered work, you may (if authorized by the copyright holders of +that 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 "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form 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 expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered 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 automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent 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 anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain 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 limiting +any implied license or other defenses to infringement that may +otherwise 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 or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License 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 the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES 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 OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy 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 greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + 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 . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific 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 +. diff --git a/macos/sn4k3-uvtools/instance.json b/macos/sn4k3-uvtools/instance.json new file mode 100644 index 0000000000000000000000000000000000000000..708ef4be22d4b172f8095360a4e9b356ae659302 --- /dev/null +++ b/macos/sn4k3-uvtools/instance.json @@ -0,0 +1,10 @@ +{ + "schema_version": 1, + "instance_id": "macos/sn4k3-uvtools", + "platform": "macos", + "repo": "https://github.com/sn4k3/UVtools", + "commit": "f56dc0407dccc459ea4f033cb3efc4815295ab88", + "patches": [], + "package": null, + "license": null +} \ No newline at end of file diff --git a/macos/sn4k3-uvtools/reference/build.sh b/macos/sn4k3-uvtools/reference/build.sh new file mode 100644 index 0000000000000000000000000000000000000000..1508f25f07cdaf921c07d83554274da27282916e --- /dev/null +++ b/macos/sn4k3-uvtools/reference/build.sh @@ -0,0 +1,234 @@ +#!/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=1 +export DOTNET_NOLOGO=1 +export 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 ;; +esac +echo "==> 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)" + fi +fi + +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" +fi +echo "==> 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 /([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 minimal +done + +# 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" < + + + + CFBundleDevelopmentRegion + en + CFBundleIconFile + UVtools.icns + CFBundleIdentifier + com.UVtools + CFBundleDisplayName + UVtools + CFBundleName + UVtools + CFBundleVersion + ${VERSION} + LSMinimumSystemVersion + 10.15 + CFBundleExecutable + UVtools + CFBundleInfoDictionaryVersion + 6.0 + CFBundlePackageType + APPL + CFBundleShortVersionString + ${VERSION} + CFBundleSupportedPlatforms + + MacOSX + + LSApplicationCategoryType + public.app-category.utilities + NSHighResolutionCapable + + NSHumanReadableCopyright + Copyright © 2020 PTRTECH. All rights reserved. + + +PLIST + +# Entitlements (generated inline). +cat > "$APP/Contents/UVtools.entitlements" <<'ENTITLEMENTS' + + + + + com.apple.security.cs.allow-jit + + com.apple.security.cs.allow-unsigned-executable-memory + + com.apple.security.cs.disable-library-validation + + com.apple.security.cs.allow-dyld-environment-variables + + + +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 || true +fi + +# 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 || true diff --git a/macos/sn4k3-uvtools/reference/launch.sh b/macos/sn4k3-uvtools/reference/launch.sh new file mode 100644 index 0000000000000000000000000000000000000000..61a669b79195872254345f1f51e1e27501c5121b --- /dev/null +++ b/macos/sn4k3-uvtools/reference/launch.sh @@ -0,0 +1,53 @@ +#!/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 1 +fi + +BIN="$APP/Contents/MacOS/UVtools" +if [ ! -x "$BIN" ]; then + echo "ERROR: executable not found at $BIN" >&2 + exit 1 +fi + +# 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" "$@" +fi diff --git a/macos/sn4k3-uvtools/tests/ax_helpers.py b/macos/sn4k3-uvtools/tests/ax_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..2418d7b8c75891c2d08906848d6a36517cb98135 --- /dev/null +++ b/macos/sn4k3-uvtools/tests/ax_helpers.py @@ -0,0 +1,849 @@ +import os +import re +import time +import warnings +import subprocess +from dataclasses import dataclass, field +from typing import Optional +from 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", +} + + +@dataclass +class 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 None diff --git a/macos/sn4k3-uvtools/tests/conftest.py b/macos/sn4k3-uvtools/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..21a9b7debd04c0633d77a60d8269102790a13e84 --- /dev/null +++ b/macos/sn4k3-uvtools/tests/conftest.py @@ -0,0 +1,584 @@ +""" +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 json +import os +import signal +import subprocess +import tempfile +import 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 _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 ` whose ARGUMENT merely contains the bundle path. + + A running .app's argv0 is /Contents/MacOS/, so we require that inner + executable path. The old bare-substring test (`app_path in args`) also matched the + lingering `open -W ` 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 == /Contents/MacOS/. + 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 ` 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//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//... — 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.fixture +def app_process(app_path): + pid = _launch_app(app_path) + yield pid + _kill_pid(pid) + + +@pytest.fixture +def 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.fixture +def 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")) diff --git a/macos/sn4k3-uvtools/tests/rb_testgen_kit.py b/macos/sn4k3-uvtools/tests/rb_testgen_kit.py new file mode 100644 index 0000000000000000000000000000000000000000..ccbbdd3c6136513161c133fbb4cefcfb0386d55c --- /dev/null +++ b/macos/sn4k3-uvtools/tests/rb_testgen_kit.py @@ -0,0 +1,575 @@ +#!/usr/bin/env python3 +"""RB TestGen Kit (macOS/AX port of the Linux v7.5 kit) — a test's NAVIGATION +DEPTH and JUMP RIGOR are DECLARED (not inferred), uniformly recorded, and +self-auditable. + +DIFFERENCE FROM LINUX: macOS tests are **pytest** (methods on Test* classes taking +the `ax` fixture, plain asserts) — NOT standalone scripts calling R.record(). So the +DECLARATION is a pytest marker on the test method: + + import rb_testgen_kit as kit + + @pytest.mark.rb(depth=1, jump_kind="reach", expect="Preferences window visible") + def test_prefs_opens(self, ax_with_reset): + before = kit.rb_showing(ax_with_reset) + helpers.rb_reach_prefs(ax_with_reset) # a nav helper you name rb_reach_* / rb_enter_* + after = kit.rb_showing(ax_with_reset) + assert kit.rb_reach(before, after, target="Preferences", source="menu bar") + +conftest.py's pytest_runtest_makereport hook reads the marker + the test outcome and +writes {name, passed, depth, jump_kind, tier, expect} so the runner can fold it into +_results.json. The audits below then read those records (+ the test SOURCE). + +jump_kind (verbatim strings — the audit/stats key off them): + "none" no trigger; existence/structure only -> tier 0 + "liveness" only "did not crash / still alive" -> tier 1 (weak; avoid) + "reach" a real surface jump: the TARGET surface's element + APPEARED and the SOURCE surface's element DISAPPEARED -> tier 2 + "transition" a state flip (CHECKED/ENABLED/mode) before->after -> tier 2 + "value" a specific expected value/content was asserted -> tier 3 + +DEPTH is the number of surfaces crossed before the assertion (0 = home/first screen, +1 = one dialog/panel/submenu, 2+ = deeper). A flat-tree read of a deep element is +depth 0 — depth counts surfaces the test actually navigated through. + +REACH PROOF (so "reach" cannot be faked by reading a flat tree): + before = rb_showing(ax) + + 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('')" + python3 -c "import rb_testgen_kit as k; k.rb_lint('')" + python3 -c "import rb_testgen_kit as k; k.rb_lint_sources('')" + python3 -c "import rb_testgen_kit as k; k.rb_audit_depth('','')" +""" +from __future__ import annotations + +import ast +import glob +import json +import os +import re + +JUMP_KINDS = {"none": 0, "liveness": 1, "reach": 2, "transition": 2, "value": 3} + +# Double-axis quota TARGETS (fractions) — goals rb_audit REPORTS, NOT a hard gate. +QUOTAS = { + "existence_max": 0.30, # jump_kind=="none" share of ALL tests + "interactive_min": 0.60, # reach|transition|value share of ALL tests + "depth_ge1_min": 0.40, # depth>=1 share of INTERACTIVE tests + "depth_ge2_min": 0.10, # depth>=2 share of INTERACTIVE tests + "value_min": 0.25, # jump_kind=="value" share of INTERACTIVE tests +} + +# Depth family: a test "crosses a surface" iff it calls a member of the depth family. +# macOS accepts BOTH the naming convention rb_enter_*/rb_reach_* (write your own nav +# helper and NAME it so) AND the existing verifier_helpers/ax_helpers navigation +# functions (whitelist below) — so tests can reuse the mature reveal/navigate helpers. +DEPTH_FWD_RE = re.compile(r"^rb_(enter|reach)[a-z0-9_]*$") +DEPTH_BACK_RE = re.compile(r"^rb_back[a-z0-9_]*$") +# verifier_helpers / ax_helpers navigation functions that OPEN or move to a new surface. +FWD_WHITELIST = { + "ensure_ui_visible", "ensure_panel_open", "open_actions_menu", "open_menu", + "open_settings", "open_preferences", "open_dialog", "open_panel", "open_window", + "navigate_month", "navigate", "switch_tab", "switch_mode", "switch_page", + "select_tab", "reveal_window", "show_panel", "show_menu", +} +BACK_WHITELIST = { + "dismiss_menus", "dismiss_panel", "dismiss_any_dialog", "close_panel", + "close_window", "go_back", +} +# pytest fixtures that themselves navigate into a surface during setup (so a test taking +# one legitimately has depth>=1 without a nav call in its own body). `ax` does NOT navigate. +_NAV_FIXTURES = {"ax_with_reset", "open_panel"} +# MEASURED-TIER verdict families (ported from keliang): a tier2/3 jump_kind must be BACKED +# by its verdict function — transition->rb_flip*, value->rb_value*, reach->rb_reach* — whose +# bool result is the test's assertion. Self-named wrappers count by prefix. +TIER_FLIP_RE = re.compile(r"^rb_flip[a-z0-9_]*$") +TIER_VALUE_RE = re.compile(r"^rb_value[a-z0-9_]*$") +_JK_FAMILY = {"transition": "flip", "value": "value", "reach": "reach"} +# normalize plural (v73prep) / singular module names so a JSON module ("button") and a +# file stem ("buttons") join. +_MODULE_ALIAS = {"menus": "menu", "buttons": "button", "states": "state", + "structures": "structure", "texts": "text", + "computations": "computation", "workflows": "workflow"} + +_DEPTH = 0 # module-global surface counter for rb_enter/rb_back + + +def tier_of(jump_kind: str) -> int: + return JUMP_KINDS.get(jump_kind, 2) + + +def rb_reset_depth() -> None: + global _DEPTH + _DEPTH = 0 + + +def rb_enter(_surface: str = "") -> int: + """Call right after your test navigates into a new surface (dialog/panel/submenu).""" + global _DEPTH + _DEPTH += 1 + return _DEPTH + + +def rb_back() -> int: + global _DEPTH + _DEPTH = max(0, _DEPTH - 1) + return _DEPTH + + +def _walk_tree_nodes(node, out, seen): + """Yield 'role|name' for a macOS AXHelper.tree() dict node (+children).""" + if not isinstance(node, dict) or seen[0] >= 8000: + return + seen[0] += 1 + role = str(node.get("role") or "") + name = str(node.get("name") or node.get("value") or "") + if role or name: + out.add(f"{role}|{name}") + for c in (node.get("children") or []): + _walk_tree_nodes(c, out, seen) + + +def rb_showing(ax, max_depth: int = 12) -> set: + """Snapshot the currently-reachable AX subtree under the app as {"role|name"}. + macOS AX has no AT-SPI SHOWING/VISIBLE state, so we approximate "showing" by the + live AX tree (AXChildren) the app currently exposes — a new window/sheet/popover + adds its elements; a dismissed one removes them. Feed before+after a trigger to + rb_reach() so a 'reach' test proves a REAL surface change, not a flat-tree read. + Safe no-op (empty set) if `ax` cannot produce a tree.""" + out: set = set() + try: + tree = ax.tree(max_depth=max_depth) # AXHelper.tree() -> nested dict + except Exception: + return out + _walk_tree_nodes(tree, out, [0]) + return out + + +def rb_reach(before, after, target: str, source: str | None = None) -> bool: + """True-jump verdict: the TARGET surface's discriminating element newly APPEARED + AND (if given) the SOURCE surface's discriminating element DISAPPEARED. This is + what separates a real surface jump from reading an element that was always there.""" + before = set(before or []) + after = set(after or []) + t = target.lower() + appeared = any(t in k.lower() for k in (after - before)) + if source is None: + return appeared + s = source.lower() + src_before = any(s in k.lower() for k in before) + src_after = any(s in k.lower() for k in after) + return appeared and src_before and not src_after + + +def rb_flip(before, after, expect: str = "") -> bool: + """In-page STATE-FLIP verdict (tier2 `transition`): the observed state actually CHANGED + before->after (a CHECKED/ENABLED/mode/selection value read the two times). Pass its bool + as the test's assertion. Does NOT touch depth — an in-page flip is depth 0 unless you + navigated a surface to reach the control. You MAY write your own `rb_flip_()` 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_()` 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 | " + "{audit_depth|audit_tier} [results_dir]}") diff --git a/macos/sn4k3-uvtools/tests/requirements.txt b/macos/sn4k3-uvtools/tests/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..feef67ce2aadbaa26d12e6b01cff7b8ce89ecb5c --- /dev/null +++ b/macos/sn4k3-uvtools/tests/requirements.txt @@ -0,0 +1,3 @@ +pytest +pytest-check +pyobjc diff --git a/macos/sn4k3-uvtools/tests/test_ax_buttons.py b/macos/sn4k3-uvtools/tests/test_ax_buttons.py new file mode 100644 index 0000000000000000000000000000000000000000..6df2c8f465fd7bc05972ea9918520a7facfc4b16 --- /dev/null +++ b/macos/sn4k3-uvtools/tests/test_ax_buttons.py @@ -0,0 +1,681 @@ +"""AX BUTTON tests for UVtools 4.4.2 (macos-sn4k3-uvtools). + +Every test asserts the OBSERVED CONSEQUENCE of pressing a button (a value change, a +text 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 AXPress +but carry junk AXTitles ("Avalonia.Controls.PathIcon"). Buttons are therefore found by +the label rendered inside them (uv.find_button_by_label), by their real AXTitle where +they 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 so +the SAME test drives the reference app and a recreation. + +NEVER activated here (recon's destructive list): the Issues-tab `Detect` button, the +Benchmark `Start` button, and every `Actions > ...` layer item (they mutate/export the +loaded file). The Actions drop-down is only OPENED and inspected. +""" + +import os, sys, time +import pytest +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import rb_testgen_kit as kit +import 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.55 +ZOOM_ROTATED = 0.43 +OUTLINE_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. diff --git a/macos/sn4k3-uvtools/tests/test_ax_computation.py b/macos/sn4k3-uvtools/tests/test_ax_computation.py new file mode 100644 index 0000000000000000000000000000000000000000..d55ab70b635c2cc61b1f1b8729b78ff7b7729c6b --- /dev/null +++ b/macos/sn4k3-uvtools/tests/test_ax_computation.py @@ -0,0 +1,667 @@ +import os, sys, time +import pytest +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import rb_testgen_kit as kit +import 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 press +STEP_SETTLE = 0.8 +# step of the "Input millimeters:" spinner, as observed on the reference +MM_STEP = 0.5 +# geometric tolerance when pairing a row label with the widget on its row +ROW_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: 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") diff --git a/macos/sn4k3-uvtools/tests/test_ax_menus.py b/macos/sn4k3-uvtools/tests/test_ax_menus.py new file mode 100644 index 0000000000000000000000000000000000000000..125c6c22ca9ab9817f18ef449be32e70fe87b275 --- /dev/null +++ b/macos/sn4k3-uvtools/tests/test_ax_menus.py @@ -0,0 +1,604 @@ +"""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, time +import pytest +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import rb_testgen_kit as kit +import 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. diff --git a/macos/sn4k3-uvtools/tests/test_ax_states.py b/macos/sn4k3-uvtools/tests/test_ax_states.py new file mode 100644 index 0000000000000000000000000000000000000000..7caf382247ed5341c59f2304d150af2e9b8d76a1 --- /dev/null +++ b/macos/sn4k3-uvtools/tests/test_ax_states.py @@ -0,0 +1,855 @@ +import os, sys, time +import pytest +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import rb_testgen_kit as kit +import 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.xml diff --git a/macos/sn4k3-uvtools/tests/test_ax_structure.py b/macos/sn4k3-uvtools/tests/test_ax_structure.py new file mode 100644 index 0000000000000000000000000000000000000000..df467fc67b6976fcf277240c4357dc39c52a344c --- /dev/null +++ b/macos/sn4k3-uvtools/tests/test_ax_structure.py @@ -0,0 +1,421 @@ +"""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 in +recon.md (## APP / ## AX_TREE / ## STRUCTURE). Nothing is hard-coded about where the app +lives: the `ax` fixture (conftest.py) launches it and hands over an AXHelper, and every +element lookup goes through the validated helpers in uv_helpers.py, so the SAME module +drives 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 every +test starts from a fully populated workspace. DYNAMIC values from recon (RAM/LO in the +window title, the render-time label, used material / material cost) are never asserted. +""" + +import os, sys, time +import pytest +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import rb_testgen_kit as kit +import 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 tree +CANDIDATE_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 tree +ROLE_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 pooled +TABULAR_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" diff --git a/macos/sn4k3-uvtools/tests/test_ax_text.py b/macos/sn4k3-uvtools/tests/test_ax_text.py new file mode 100644 index 0000000000000000000000000000000000000000..587fc48161e8acbab81827a6c74ef3e0c553be7b --- /dev/null +++ b/macos/sn4k3-uvtools/tests/test_ax_text.py @@ -0,0 +1,695 @@ +"""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 in +recon.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 same +already-reset state (Information tab selected, layer 0, thumbnail 1/2). + +DYNAMIC values are never asserted by value: the `RAM: … MB` / `LO: …ms` tail of the +window title, the render-time label, and the `Used material:` / `Material cost:` +numbers (recomputed asynchronously) — for those only the label prefix + a positive +number is checked. In the About dialog only the field LABELS are asserted, never the +machine-specific values. +""" + +import os, sys, time +import pytest +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import rb_testgen_kit as kit +import 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 `/` 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 `/` 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]}" diff --git a/macos/sn4k3-uvtools/tests/testcase_counts.json b/macos/sn4k3-uvtools/tests/testcase_counts.json new file mode 100644 index 0000000000000000000000000000000000000000..d5e6115139c826418dd4e45f87cf475891a788b7 --- /dev/null +++ b/macos/sn4k3-uvtools/tests/testcase_counts.json @@ -0,0 +1,37 @@ +{ + "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" +} \ No newline at end of file diff --git a/macos/sn4k3-uvtools/tests/uv_helpers.py b/macos/sn4k3-uvtools/tests/uv_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..26f62703fe5094ce039acb0413c4be7ccea86930 --- /dev/null +++ b/macos/sn4k3-uvtools/tests/uv_helpers.py @@ -0,0 +1,615 @@ +"""UVtools AX test helpers — shared by the generated test_ax_*.py modules. + +Portable by construction: every function takes the `ax` AXHelper handed over by the +pytest `ax` fixture (the harness launches the app), never a path or a pid, so the SAME +test 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 json +import os +import re +import subprocess +import time + +import Quartz +from ApplicationServices import AXUIElementCopyAttributeValue + +KC_ESCAPE = 53 +KC_RETURN = 36 +KC_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 depth +def 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: + pass diff --git a/macos/sn4k3-uvtools/tests/verifier_helpers.py b/macos/sn4k3-uvtools/tests/verifier_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..ce369cdae8db3a7427890d1636f8f5a3201dbef1 --- /dev/null +++ b/macos/sn4k3-uvtools/tests/verifier_helpers.py @@ -0,0 +1,753 @@ +""" +verifier_helpers.py — High-level AX testing patterns for macOS app verification. + +v6 core library. Encodes all robust testing patterns as reusable functions +so verifier agents call high-level APIs instead of building from scratch. + +Depends on: ax_helpers.py (AXHelper class) +""" + +import datetime +import os +import re +import signal +import subprocess +import time +from collections import Counter + +# --------------------------------------------------------------------------- +# Key codes (macOS virtual key codes) +# --------------------------------------------------------------------------- +KC_LEFT_ARROW = 123 +KC_RIGHT_ARROW = 124 +KC_UP_ARROW = 126 +KC_DOWN_ARROW = 125 +KC_SPACE = 49 +KC_RETURN = 36 +KC_TAB = 48 +KC_ESCAPE = 53 +KC_Q = 12 +KC_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": , "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)" + ) diff --git a/macos/sn4k3-uvtools/vlm_assertions.json b/macos/sn4k3-uvtools/vlm_assertions.json new file mode 100644 index 0000000000000000000000000000000000000000..50149ec5b9512587e935cdacd513d955aea69a66 --- /dev/null +++ b/macos/sn4k3-uvtools/vlm_assertions.json @@ -0,0 +1,205 @@ +{ + "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 + } +} \ No newline at end of file diff --git a/macos/sokoloffa-radiola/LICENSE b/macos/sokoloffa-radiola/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..72773dc562d14664d6a81b66f52fd1571562b3d5 --- /dev/null +++ b/macos/sokoloffa-radiola/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 Alexander Sokolov + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, 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 THE +SOFTWARE. diff --git a/macos/sokoloffa-radiola/instance.json b/macos/sokoloffa-radiola/instance.json new file mode 100644 index 0000000000000000000000000000000000000000..5bccde4257a863634cfb82753e1b747208cce260 --- /dev/null +++ b/macos/sokoloffa-radiola/instance.json @@ -0,0 +1,10 @@ +{ + "schema_version": 1, + "instance_id": "macos/sokoloffa-radiola", + "platform": "macos", + "repo": "https://github.com/SokoloffA/radiola", + "commit": "3321ca281afc222544b7e67e64f64f7f13051925", + "patches": [], + "package": null, + "license": null +} \ No newline at end of file diff --git a/macos/sokoloffa-radiola/reference/build.sh b/macos/sokoloffa-radiola/reference/build.sh new file mode 100644 index 0000000000000000000000000000000000000000..30c0c97b052508feb8c2ecaa548e7b2135931875 --- /dev/null +++ b/macos/sokoloffa-radiola/reference/build.sh @@ -0,0 +1,102 @@ +#!/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 1 +fi +xcodebuild -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 1 +fi + +# --------------------------------------------------------------------------- +# 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/^/ /' diff --git a/macos/sokoloffa-radiola/reference/launch.sh b/macos/sokoloffa-radiola/reference/launch.sh new file mode 100644 index 0000000000000000000000000000000000000000..b02706a63d5ef6509a091dc309d32c3617840e2d --- /dev/null +++ b/macos/sokoloffa-radiola/reference/launch.sh @@ -0,0 +1,48 @@ +#!/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)" + break +done + +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 1 +fi + +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)." diff --git a/macos/sokoloffa-radiola/tests/ax_helpers.py b/macos/sokoloffa-radiola/tests/ax_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..2418d7b8c75891c2d08906848d6a36517cb98135 --- /dev/null +++ b/macos/sokoloffa-radiola/tests/ax_helpers.py @@ -0,0 +1,849 @@ +import os +import re +import time +import warnings +import subprocess +from dataclasses import dataclass, field +from typing import Optional +from 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", +} + + +@dataclass +class 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 None diff --git a/macos/sokoloffa-radiola/tests/conftest.py b/macos/sokoloffa-radiola/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..21a9b7debd04c0633d77a60d8269102790a13e84 --- /dev/null +++ b/macos/sokoloffa-radiola/tests/conftest.py @@ -0,0 +1,584 @@ +""" +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 json +import os +import signal +import subprocess +import tempfile +import 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 _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 ` whose ARGUMENT merely contains the bundle path. + + A running .app's argv0 is /Contents/MacOS/, so we require that inner + executable path. The old bare-substring test (`app_path in args`) also matched the + lingering `open -W ` 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 == /Contents/MacOS/. + 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 ` 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//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//... — 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.fixture +def app_process(app_path): + pid = _launch_app(app_path) + yield pid + _kill_pid(pid) + + +@pytest.fixture +def 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.fixture +def 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")) diff --git a/macos/sokoloffa-radiola/tests/rb_radiola.py b/macos/sokoloffa-radiola/tests/rb_radiola.py new file mode 100644 index 0000000000000000000000000000000000000000..e5e51dfd20927fcf43d22fba83a2976d55134c48 --- /dev/null +++ b/macos/sokoloffa-radiola/tests/rb_radiola.py @@ -0,0 +1,789 @@ +"""rb_radiola.py — shared, PORTABLE navigation/observation helpers for the Radiola +AX test suite. + +Radiola is a macOS *status-bar* (accessory / LSBackgroundOnly) app: it has NO window at +launch. Every surface has to be revealed through the status-bar item or through the app's +own menu bar. The helpers below encapsulate the reveal steps that were verified against +the running reference app, and are written so a faithful recreation is driven by exactly +the 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 depth +from 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 json +import os +import subprocess +import 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: + pass diff --git a/macos/sokoloffa-radiola/tests/rb_testgen_kit.py b/macos/sokoloffa-radiola/tests/rb_testgen_kit.py new file mode 100644 index 0000000000000000000000000000000000000000..ccbbdd3c6136513161c133fbb4cefcfb0386d55c --- /dev/null +++ b/macos/sokoloffa-radiola/tests/rb_testgen_kit.py @@ -0,0 +1,575 @@ +#!/usr/bin/env python3 +"""RB TestGen Kit (macOS/AX port of the Linux v7.5 kit) — a test's NAVIGATION +DEPTH and JUMP RIGOR are DECLARED (not inferred), uniformly recorded, and +self-auditable. + +DIFFERENCE FROM LINUX: macOS tests are **pytest** (methods on Test* classes taking +the `ax` fixture, plain asserts) — NOT standalone scripts calling R.record(). So the +DECLARATION is a pytest marker on the test method: + + import rb_testgen_kit as kit + + @pytest.mark.rb(depth=1, jump_kind="reach", expect="Preferences window visible") + def test_prefs_opens(self, ax_with_reset): + before = kit.rb_showing(ax_with_reset) + helpers.rb_reach_prefs(ax_with_reset) # a nav helper you name rb_reach_* / rb_enter_* + after = kit.rb_showing(ax_with_reset) + assert kit.rb_reach(before, after, target="Preferences", source="menu bar") + +conftest.py's pytest_runtest_makereport hook reads the marker + the test outcome and +writes {name, passed, depth, jump_kind, tier, expect} so the runner can fold it into +_results.json. The audits below then read those records (+ the test SOURCE). + +jump_kind (verbatim strings — the audit/stats key off them): + "none" no trigger; existence/structure only -> tier 0 + "liveness" only "did not crash / still alive" -> tier 1 (weak; avoid) + "reach" a real surface jump: the TARGET surface's element + APPEARED and the SOURCE surface's element DISAPPEARED -> tier 2 + "transition" a state flip (CHECKED/ENABLED/mode) before->after -> tier 2 + "value" a specific expected value/content was asserted -> tier 3 + +DEPTH is the number of surfaces crossed before the assertion (0 = home/first screen, +1 = one dialog/panel/submenu, 2+ = deeper). A flat-tree read of a deep element is +depth 0 — depth counts surfaces the test actually navigated through. + +REACH PROOF (so "reach" cannot be faked by reading a flat tree): + before = rb_showing(ax) + + 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('')" + python3 -c "import rb_testgen_kit as k; k.rb_lint('')" + python3 -c "import rb_testgen_kit as k; k.rb_lint_sources('')" + python3 -c "import rb_testgen_kit as k; k.rb_audit_depth('','')" +""" +from __future__ import annotations + +import ast +import glob +import json +import os +import re + +JUMP_KINDS = {"none": 0, "liveness": 1, "reach": 2, "transition": 2, "value": 3} + +# Double-axis quota TARGETS (fractions) — goals rb_audit REPORTS, NOT a hard gate. +QUOTAS = { + "existence_max": 0.30, # jump_kind=="none" share of ALL tests + "interactive_min": 0.60, # reach|transition|value share of ALL tests + "depth_ge1_min": 0.40, # depth>=1 share of INTERACTIVE tests + "depth_ge2_min": 0.10, # depth>=2 share of INTERACTIVE tests + "value_min": 0.25, # jump_kind=="value" share of INTERACTIVE tests +} + +# Depth family: a test "crosses a surface" iff it calls a member of the depth family. +# macOS accepts BOTH the naming convention rb_enter_*/rb_reach_* (write your own nav +# helper and NAME it so) AND the existing verifier_helpers/ax_helpers navigation +# functions (whitelist below) — so tests can reuse the mature reveal/navigate helpers. +DEPTH_FWD_RE = re.compile(r"^rb_(enter|reach)[a-z0-9_]*$") +DEPTH_BACK_RE = re.compile(r"^rb_back[a-z0-9_]*$") +# verifier_helpers / ax_helpers navigation functions that OPEN or move to a new surface. +FWD_WHITELIST = { + "ensure_ui_visible", "ensure_panel_open", "open_actions_menu", "open_menu", + "open_settings", "open_preferences", "open_dialog", "open_panel", "open_window", + "navigate_month", "navigate", "switch_tab", "switch_mode", "switch_page", + "select_tab", "reveal_window", "show_panel", "show_menu", +} +BACK_WHITELIST = { + "dismiss_menus", "dismiss_panel", "dismiss_any_dialog", "close_panel", + "close_window", "go_back", +} +# pytest fixtures that themselves navigate into a surface during setup (so a test taking +# one legitimately has depth>=1 without a nav call in its own body). `ax` does NOT navigate. +_NAV_FIXTURES = {"ax_with_reset", "open_panel"} +# MEASURED-TIER verdict families (ported from keliang): a tier2/3 jump_kind must be BACKED +# by its verdict function — transition->rb_flip*, value->rb_value*, reach->rb_reach* — whose +# bool result is the test's assertion. Self-named wrappers count by prefix. +TIER_FLIP_RE = re.compile(r"^rb_flip[a-z0-9_]*$") +TIER_VALUE_RE = re.compile(r"^rb_value[a-z0-9_]*$") +_JK_FAMILY = {"transition": "flip", "value": "value", "reach": "reach"} +# normalize plural (v73prep) / singular module names so a JSON module ("button") and a +# file stem ("buttons") join. +_MODULE_ALIAS = {"menus": "menu", "buttons": "button", "states": "state", + "structures": "structure", "texts": "text", + "computations": "computation", "workflows": "workflow"} + +_DEPTH = 0 # module-global surface counter for rb_enter/rb_back + + +def tier_of(jump_kind: str) -> int: + return JUMP_KINDS.get(jump_kind, 2) + + +def rb_reset_depth() -> None: + global _DEPTH + _DEPTH = 0 + + +def rb_enter(_surface: str = "") -> int: + """Call right after your test navigates into a new surface (dialog/panel/submenu).""" + global _DEPTH + _DEPTH += 1 + return _DEPTH + + +def rb_back() -> int: + global _DEPTH + _DEPTH = max(0, _DEPTH - 1) + return _DEPTH + + +def _walk_tree_nodes(node, out, seen): + """Yield 'role|name' for a macOS AXHelper.tree() dict node (+children).""" + if not isinstance(node, dict) or seen[0] >= 8000: + return + seen[0] += 1 + role = str(node.get("role") or "") + name = str(node.get("name") or node.get("value") or "") + if role or name: + out.add(f"{role}|{name}") + for c in (node.get("children") or []): + _walk_tree_nodes(c, out, seen) + + +def rb_showing(ax, max_depth: int = 12) -> set: + """Snapshot the currently-reachable AX subtree under the app as {"role|name"}. + macOS AX has no AT-SPI SHOWING/VISIBLE state, so we approximate "showing" by the + live AX tree (AXChildren) the app currently exposes — a new window/sheet/popover + adds its elements; a dismissed one removes them. Feed before+after a trigger to + rb_reach() so a 'reach' test proves a REAL surface change, not a flat-tree read. + Safe no-op (empty set) if `ax` cannot produce a tree.""" + out: set = set() + try: + tree = ax.tree(max_depth=max_depth) # AXHelper.tree() -> nested dict + except Exception: + return out + _walk_tree_nodes(tree, out, [0]) + return out + + +def rb_reach(before, after, target: str, source: str | None = None) -> bool: + """True-jump verdict: the TARGET surface's discriminating element newly APPEARED + AND (if given) the SOURCE surface's discriminating element DISAPPEARED. This is + what separates a real surface jump from reading an element that was always there.""" + before = set(before or []) + after = set(after or []) + t = target.lower() + appeared = any(t in k.lower() for k in (after - before)) + if source is None: + return appeared + s = source.lower() + src_before = any(s in k.lower() for k in before) + src_after = any(s in k.lower() for k in after) + return appeared and src_before and not src_after + + +def rb_flip(before, after, expect: str = "") -> bool: + """In-page STATE-FLIP verdict (tier2 `transition`): the observed state actually CHANGED + before->after (a CHECKED/ENABLED/mode/selection value read the two times). Pass its bool + as the test's assertion. Does NOT touch depth — an in-page flip is depth 0 unless you + navigated a surface to reach the control. You MAY write your own `rb_flip_()` 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_()` 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 | " + "{audit_depth|audit_tier} [results_dir]}") diff --git a/macos/sokoloffa-radiola/tests/requirements.txt b/macos/sokoloffa-radiola/tests/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..feef67ce2aadbaa26d12e6b01cff7b8ce89ecb5c --- /dev/null +++ b/macos/sokoloffa-radiola/tests/requirements.txt @@ -0,0 +1,3 @@ +pytest +pytest-check +pyobjc diff --git a/macos/sokoloffa-radiola/tests/test_ax_buttons.py b/macos/sokoloffa-radiola/tests/test_ax_buttons.py new file mode 100644 index 0000000000000000000000000000000000000000..43858fd798bb04776482fbbb09ce1e9adfe75aaa --- /dev/null +++ b/macos/sokoloffa-radiola/tests/test_ax_buttons.py @@ -0,0 +1,621 @@ +"""AX BUTTON tests for Radiola (macOS status-bar radio player). + +Every test drives a button that recon `## BUTTONS` (B1-B13) recorded a MEASURED +consequence 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 rbr +import 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" diff --git a/macos/sokoloffa-radiola/tests/test_ax_computation.py b/macos/sokoloffa-radiola/tests/test_ax_computation.py new file mode 100644 index 0000000000000000000000000000000000000000..9c5fbb6a9b155b943b5ec5ab53aafce660456491 --- /dev/null +++ b/macos/sokoloffa-radiola/tests/test_ax_computation.py @@ -0,0 +1,629 @@ +"""COMPUTATION lane for Radiola (macOS status-bar radio player). + +Radiola is NOT a calculator: it has no arithmetic UI. Its deterministic +input -> 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-read +from 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 rbr +import rb_testgen_kit as kit + +# ── the recorded arithmetic constants ──────────────────────────────────────────────── +VOL_DEFAULT = 0.5 # fresh launch (defaults deleted) always starts here +VOL_STEP = 0.05 # +/- per press of volume up / audio output volume off +VOL_MAX = 1.0 # clamp ceiling +VOL_MIN = 0.0 # clamp floor +ND = 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}") diff --git a/macos/sokoloffa-radiola/tests/test_ax_states.py b/macos/sokoloffa-radiola/tests/test_ax_states.py new file mode 100644 index 0000000000000000000000000000000000000000..0d2fd1b993e6dc03483912612823737e57836cfc --- /dev/null +++ b/macos/sokoloffa-radiola/tests/test_ax_states.py @@ -0,0 +1,799 @@ +"""AX STATE verification for Radiola (status-bar radio player). + +Owns CHECKED / ENABLED / SELECTED / FOCUSED state and every before->after state flip +recorded 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-presses +every menu-bar item and cannot recognise Radiola's status menu). + +Hard prohibitions honoured here: the prefs `Audio` tab is never selected (it crashes the +reference), `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 rbr +import 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}" diff --git a/macos/sokoloffa-radiola/tests/test_ax_structure.py b/macos/sokoloffa-radiola/tests/test_ax_structure.py new file mode 100644 index 0000000000000000000000000000000000000000..6ed65fa91b90f9c481ebd934642be367d1f0a8c1 --- /dev/null +++ b/macos/sokoloffa-radiola/tests/test_ax_structure.py @@ -0,0 +1,563 @@ +"""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 in +recon.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 of +that is encapsulated in the deployed `rb_radiola` helpers, which are the only way these +tests 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 re +import time + +import pytest + +import rb_radiola as rbr +import 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.") diff --git a/macos/sokoloffa-radiola/tests/test_ax_text.py b/macos/sokoloffa-radiola/tests/test_ax_text.py new file mode 100644 index 0000000000000000000000000000000000000000..e8b91c068d12954478ef88992b54de7ec58d70b5 --- /dev/null +++ b/macos/sokoloffa-radiola/tests/test_ax_text.py @@ -0,0 +1,685 @@ +"""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 in +recon.md `## TEXT` / `## AX_TREE`. Radiola has NO window at launch, so almost all of its +text lives behind the status menu or behind a window that has to be revealed first — hence +most 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 rbr +import rb_testgen_kit as kit + +# ── expected text, verbatim from recon `## TEXT` ──────────────────────────────────────── + +DEFAULT_TOOLTIP = "Radio Caroline" +SEP_LINE = "⎯" * 28 # 28x U+23AF HORIZONTAL LINE EXTENSION +STATUS_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 press +UPDATES_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 \"\\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}" diff --git a/macos/sokoloffa-radiola/tests/testcase_counts.json b/macos/sokoloffa-radiola/tests/testcase_counts.json new file mode 100644 index 0000000000000000000000000000000000000000..c6a4b95bbd6e62355859e5800de6ebd1a261bf0f --- /dev/null +++ b/macos/sokoloffa-radiola/tests/testcase_counts.json @@ -0,0 +1,36 @@ +{ + "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" +} \ No newline at end of file diff --git a/macos/sokoloffa-radiola/tests/verifier_helpers.py b/macos/sokoloffa-radiola/tests/verifier_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..ce369cdae8db3a7427890d1636f8f5a3201dbef1 --- /dev/null +++ b/macos/sokoloffa-radiola/tests/verifier_helpers.py @@ -0,0 +1,753 @@ +""" +verifier_helpers.py — High-level AX testing patterns for macOS app verification. + +v6 core library. Encodes all robust testing patterns as reusable functions +so verifier agents call high-level APIs instead of building from scratch. + +Depends on: ax_helpers.py (AXHelper class) +""" + +import datetime +import os +import re +import signal +import subprocess +import time +from collections import Counter + +# --------------------------------------------------------------------------- +# Key codes (macOS virtual key codes) +# --------------------------------------------------------------------------- +KC_LEFT_ARROW = 123 +KC_RIGHT_ARROW = 124 +KC_UP_ARROW = 126 +KC_DOWN_ARROW = 125 +KC_SPACE = 49 +KC_RETURN = 36 +KC_TAB = 48 +KC_ESCAPE = 53 +KC_Q = 12 +KC_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)" + ) diff --git a/macos/sokoloffa-radiola/vlm_assertions.json b/macos/sokoloffa-radiola/vlm_assertions.json new file mode 100644 index 0000000000000000000000000000000000000000..f026406a6e640f05efce8db86dbfea5e8b66f39b --- /dev/null +++ b/macos/sokoloffa-radiola/vlm_assertions.json @@ -0,0 +1,218 @@ +{ + "schema_version": 2, + "instance_id": "macos/sokoloffa-radiola", + "grading": { + "mode": "deferred", + "model": null, + "scored_separately": true + }, + "totals": { + "assertions": 15, + "with_verdict": 0, + "calibrated": 0, + "usable": null, + "scored_records": 0, + "unbacked_records": 0 + }, + "assertions": [ + { + "id": "buttons_add_station_sheet.png", + "screenshot": "buttons_add_station_sheet.png", + "assertion": "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.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "buttons_add_station_sheet.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "buttons_prefs_appearance_tab.png", + "screenshot": "buttons_prefs_appearance_tab.png", + "assertion": "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).", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "buttons_prefs_appearance_tab.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "computation_mute_disables_volume.png", + "screenshot": "computation_mute_disables_volume.png", + "assertion": "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.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "computation_mute_disables_volume.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "states_appearance_menu_checkboxes_ticked.png", + "screenshot": "states_appearance_menu_checkboxes_ticked.png", + "assertion": "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.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "states_appearance_menu_checkboxes_ticked.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "states_status_menu_volume_and_mute.png", + "screenshot": "states_status_menu_volume_and_mute.png", + "assertion": "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.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "states_status_menu_volume_and_mute.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "structure_status_menu_open.png", + "screenshot": "structure_status_menu_open.png", + "assertion": "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.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "structure_status_menu_open.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "structure_add_station_sheet.png", + "screenshot": "structure_add_station_sheet.png", + "assertion": "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.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "structure_add_station_sheet.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "structure_prefs_appearance.png", + "screenshot": "structure_prefs_appearance.png", + "assertion": "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).", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "structure_prefs_appearance.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "structure_history_window.png", + "screenshot": "structure_history_window.png", + "assertion": "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.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "structure_history_window.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "text_status_menu.png", + "screenshot": "text_status_menu.png", + "assertion": "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.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "text_status_menu.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "text_history_window.png", + "screenshot": "text_history_window.png", + "assertion": "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.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "text_history_window.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "text_prefs_appearance.png", + "screenshot": "text_prefs_appearance.png", + "assertion": "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'.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "text_prefs_appearance.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "text_add_station_sheet.png", + "screenshot": "text_add_station_sheet.png", + "assertion": "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.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "text_add_station_sheet.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "text_playing_state.png", + "screenshot": "text_playing_state.png", + "assertion": "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.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "text_playing_state.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "text_search_panel.png", + "screenshot": "text_search_panel.png", + "assertion": "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.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "text_search_panel.png", + "rigor": null, + "verdict": null, + "calibration": null + } + ], + "merged_from_files": 5, + "source_shapes": { + "dict_str": 15 + } +} \ No newline at end of file diff --git a/macos/sqlitebrowser-sqlitebrowser/LICENSE b/macos/sqlitebrowser-sqlitebrowser/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..da2fad5a25ca6cbe2ed2d5c399da1ed60258b595 --- /dev/null +++ b/macos/sqlitebrowser-sqlitebrowser/LICENSE @@ -0,0 +1,9 @@ +DB Browser for SQLite is bi-licensed under the Mozilla Public License +Version 2, as well as the GNU General Public License Version 3 or later. + +Modification or redistribution is permitted under the conditions of these licenses. + +Check `LICENSE-GPL-3.0` for the full text of the GNU General Public License Version 3. +Check `LICENSE-MPL-2.0` for the full text of the Mozilla Public License Version 2. +Check `LICENSE-MIT` for the full text of the MIT License. and that is the license for the `nalgeon/sqlean` library. +Check `LICENSE-PLUGINS` for other rights regarding included third-party resources. diff --git a/macos/sqlitebrowser-sqlitebrowser/instance.json b/macos/sqlitebrowser-sqlitebrowser/instance.json new file mode 100644 index 0000000000000000000000000000000000000000..67f544282e78058f18f5606dbddcfbf1c141449b --- /dev/null +++ b/macos/sqlitebrowser-sqlitebrowser/instance.json @@ -0,0 +1,10 @@ +{ + "schema_version": 1, + "instance_id": "macos/sqlitebrowser-sqlitebrowser", + "platform": "macos", + "repo": "https://github.com/sqlitebrowser/sqlitebrowser", + "commit": "5733cb75d623434a3b06f497e919cca1e206cf03", + "patches": [], + "package": null, + "license": null +} \ No newline at end of file diff --git a/macos/sqlitebrowser-sqlitebrowser/reference/build.sh b/macos/sqlitebrowser-sqlitebrowser/reference/build.sh new file mode 100644 index 0000000000000000000000000000000000000000..1ceb6a413cd1f700215becc23be6fb0521d1eb65 --- /dev/null +++ b/macos/sqlitebrowser-sqlitebrowser/reference/build.sh @@ -0,0 +1,137 @@ +#!/usr/bin/env bash +# +# Standalone, reproducible build script for "DB Browser for SQLite" (sqlitebrowser) +# on macOS. Produces a fully self-contained "DB Browser for SQLite.app". +# +# Everything the build needs lives inside this script. On a fresh `git clone` +# into which only build.sh (and launch.sh) are copied, `bash build.sh` produces +# the .app. +# +# Project facts that shape this script: +# * It is a Qt5 + CMake project (find_package(Qt5 REQUIRED ...)); the code uses +# QDesktopWidget / QRegExp / QTextCodec, which are removed in Qt6, so we build +# against Homebrew's keg-only `qt@5` (5.15.x) rather than the system Qt6. +# * `find_package(SQLite3)` must resolve to a SQLite header that declares +# sqlite3_load_extension(); the macOS SDK header omits it, so we point +# SQLite3_INCLUDE_DIR/LIBRARY at Homebrew's `sqlite`. +# * The bundled libs (qscintilla/qhexedit/qcustomplot) declare +# cmake_minimum_required(<3.5), which CMake 4.x rejects; we pass +# -DCMAKE_POLICY_VERSION_MINIMUM=3.5 to configure them anyway. +# * src/app.plist leaves @EXECUTABLE@/@ICON@ for CMake to fill, but no CMake +# variables feed them, so the generated Info.plist has empty +# CFBundleExecutable/CFBundleIconFile. We fix those post-build (build +# artifact only -- no source edit). +# * macdeployqt bundles the Qt frameworks + the required cocoa platform plugin +# and rewrites linkage to @executable_path, yielding a portable .app. +# +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd "$SCRIPT_DIR" + +APP_NAME="DB Browser for SQLite" +BUILD_DIR="$SCRIPT_DIR/build" + +# --------------------------------------------------------------------------- +# 0. Ensure Homebrew is on PATH (works on both Apple Silicon and Intel) +# --------------------------------------------------------------------------- +if ! command -v brew >/dev/null 2>&1; then + for b in /opt/homebrew/bin/brew /usr/local/bin/brew; do + if [ -x "$b" ]; then eval "$("$b" shellenv)"; break; fi + done +fi +if ! command -v brew >/dev/null 2>&1; then + echo "ERROR: Homebrew is required but was not found on PATH." >&2 + exit 1 +fi + +# --------------------------------------------------------------------------- +# 1. Dependencies (idempotent -- brew install is a no-op if already present) +# --------------------------------------------------------------------------- +echo ">>> Installing/verifying build dependencies ..." +for formula in cmake ninja sqlite; do + brew list --versions "$formula" >/dev/null 2>&1 || brew install "$formula" +done +if ! brew list --versions qt@5 >/dev/null 2>&1; then + # The VM image carries Homebrew's modular Qt 6 formulae. They link the same executable names + # as the keg-only Qt 5 package and make `brew install qt@5` abort before the build starts. + for formula in $(brew list --formula | grep -E '^qt(base|3d|charts|connectivity|datavis3d|declarative|multimedia|networkauth|positioning|quick3d|remoteobjects|scxml|sensors|serialport|speech|svg|tools|webchannel|websockets)$' || true); do + brew unlink "$formula" >/dev/null 2>&1 || true + done + brew install qt@5 +fi + +QT5_PREFIX="$(brew --prefix qt@5)" +SQLITE_PREFIX="$(brew --prefix sqlite)" + +if [ ! -x "$QT5_PREFIX/bin/qmake" ]; then + echo "ERROR: qt@5 not found at $QT5_PREFIX" >&2 + exit 1 +fi +echo ">>> Using Qt5 at: $QT5_PREFIX" +echo ">>> Using SQLite at: $SQLITE_PREFIX" + +# --------------------------------------------------------------------------- +# 2. Configure (CMake / Ninja, Release, native arch) +# --------------------------------------------------------------------------- +echo ">>> Configuring ..." +rm -rf "$BUILD_DIR" +mkdir -p "$BUILD_DIR" + +cmake -S "$SCRIPT_DIR" -B "$BUILD_DIR" -G Ninja \ + -DCMAKE_BUILD_TYPE=Release \ + -DCMAKE_POLICY_VERSION_MINIMUM=3.5 \ + -DCMAKE_PREFIX_PATH="$QT5_PREFIX" \ + -DSQLite3_INCLUDE_DIR="$SQLITE_PREFIX/include" \ + -DSQLite3_LIBRARY="$SQLITE_PREFIX/lib/libsqlite3.dylib" + +# --------------------------------------------------------------------------- +# 3. Build +# --------------------------------------------------------------------------- +echo ">>> Building ..." +cmake --build "$BUILD_DIR" -j "$(sysctl -n hw.ncpu)" + +APP="$BUILD_DIR/$APP_NAME.app" +if [ ! -d "$APP" ]; then + echo "ERROR: expected app bundle not produced: $APP" >&2 + exit 1 +fi + +# --------------------------------------------------------------------------- +# 4. Fix bundle metadata that CMake left blank (build artifact, not source) +# - CFBundleExecutable was configured from @EXECUTABLE@ -> empty +# - CFBundleIconFile was configured from @ICON@ -> empty +# --------------------------------------------------------------------------- +echo ">>> Fixing Info.plist and bundling icon ..." +PLIST="$APP/Contents/Info.plist" +/usr/libexec/PlistBuddy -c "Set :CFBundleExecutable $APP_NAME" "$PLIST" 2>/dev/null \ + || /usr/libexec/PlistBuddy -c "Add :CFBundleExecutable string $APP_NAME" "$PLIST" + +mkdir -p "$APP/Contents/Resources" +if [ -f "$SCRIPT_DIR/src/macapp.icns" ]; then + cp -f "$SCRIPT_DIR/src/macapp.icns" "$APP/Contents/Resources/macapp.icns" + /usr/libexec/PlistBuddy -c "Set :CFBundleIconFile macapp.icns" "$PLIST" 2>/dev/null \ + || /usr/libexec/PlistBuddy -c "Add :CFBundleIconFile string macapp.icns" "$PLIST" +fi + +# --------------------------------------------------------------------------- +# 5. Bundle Qt frameworks + plugins -> self-contained, relocatable .app +# --------------------------------------------------------------------------- +echo ">>> Running macdeployqt ..." +"$QT5_PREFIX/bin/macdeployqt" "$APP" -verbose=1 + +# --------------------------------------------------------------------------- +# 6. Deliver the .app to the output directory +# --------------------------------------------------------------------------- +OUT_DIR="${APP_OUTPUT_DIR:-$SCRIPT_DIR}" +mkdir -p "$OUT_DIR" +OUT_APP="$OUT_DIR/$APP_NAME.app" +# Only copy when the output location differs from where it was built. +if [ "$(cd "$OUT_DIR" && pwd)" != "$BUILD_DIR" ]; then + rm -rf "$OUT_APP" + ditto "$APP" "$OUT_APP" +fi + +echo "" +echo ">>> BUILD SUCCEEDED" +echo ">>> App bundle: $OUT_APP" diff --git a/macos/sqlitebrowser-sqlitebrowser/reference/launch.sh b/macos/sqlitebrowser-sqlitebrowser/reference/launch.sh new file mode 100644 index 0000000000000000000000000000000000000000..1253b7b5fa03d03f35a875a36dac5b147820ce47 --- /dev/null +++ b/macos/sqlitebrowser-sqlitebrowser/reference/launch.sh @@ -0,0 +1,44 @@ +#!/usr/bin/env bash +# +# Launch script for "DB Browser for SQLite". +# +# The .app produced by build.sh is fully self-contained (Qt frameworks and the +# cocoa platform plugin are bundled and linkage is rewritten to +# @executable_path), so no DYLD_* variables are required. We still export +# QT_PLUGIN_PATH pointing at the bundled plugins as a defensive measure, and run +# the inner Mach-O binary directly so it deterministically inherits this +# environment (macOS `open` does not forward shell env vars to the launched app). +# +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +APP_NAME="DB Browser for SQLite" + +# Locate the built .app relative to the script (no hardcoded absolute paths). +APP="" +for cand in \ + "${APP_OUTPUT_DIR:-}/$APP_NAME.app" \ + "$SCRIPT_DIR/$APP_NAME.app" \ + "$SCRIPT_DIR/build/$APP_NAME.app"; do + if [ -n "${cand#/}" ] && [ -d "$cand" ]; then + APP="$cand" + break + fi +done + +if [ -z "$APP" ]; then + echo "ERROR: '$APP_NAME.app' not found. Run build.sh first." >&2 + exit 1 +fi + +BIN="$APP/Contents/MacOS/$APP_NAME" +if [ ! -x "$BIN" ]; then + echo "ERROR: executable not found inside bundle: $BIN" >&2 + exit 1 +fi + +# Point Qt at the bundle's own plugins (harmless with a self-contained bundle). +export QT_PLUGIN_PATH="$APP/Contents/PlugIns" + +echo ">>> Launching: $APP" +exec "$BIN" "$@" diff --git a/macos/sqlitebrowser-sqlitebrowser/tests/ax_helpers.py b/macos/sqlitebrowser-sqlitebrowser/tests/ax_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..2418d7b8c75891c2d08906848d6a36517cb98135 --- /dev/null +++ b/macos/sqlitebrowser-sqlitebrowser/tests/ax_helpers.py @@ -0,0 +1,849 @@ +import os +import re +import time +import warnings +import subprocess +from dataclasses import dataclass, field +from typing import Optional +from 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", +} + + +@dataclass +class 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 None diff --git a/macos/sqlitebrowser-sqlitebrowser/tests/conftest.py b/macos/sqlitebrowser-sqlitebrowser/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..21a9b7debd04c0633d77a60d8269102790a13e84 --- /dev/null +++ b/macos/sqlitebrowser-sqlitebrowser/tests/conftest.py @@ -0,0 +1,584 @@ +""" +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 json +import os +import signal +import subprocess +import tempfile +import 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.fixture +def app_process(app_path): + pid = _launch_app(app_path) + yield pid + _kill_pid(pid) + + +@pytest.fixture +def 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.fixture +def 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")) diff --git a/macos/sqlitebrowser-sqlitebrowser/tests/rb_testgen_kit.py b/macos/sqlitebrowser-sqlitebrowser/tests/rb_testgen_kit.py new file mode 100644 index 0000000000000000000000000000000000000000..ccbbdd3c6136513161c133fbb4cefcfb0386d55c --- /dev/null +++ b/macos/sqlitebrowser-sqlitebrowser/tests/rb_testgen_kit.py @@ -0,0 +1,575 @@ +#!/usr/bin/env python3 +"""RB TestGen Kit (macOS/AX port of the Linux v7.5 kit) — a test's NAVIGATION +DEPTH and JUMP RIGOR are DECLARED (not inferred), uniformly recorded, and +self-auditable. + +DIFFERENCE FROM LINUX: macOS tests are **pytest** (methods on Test* classes taking +the `ax` fixture, plain asserts) — NOT standalone scripts calling R.record(). So the +DECLARATION is a pytest marker on the test method: + + import rb_testgen_kit as kit + + @pytest.mark.rb(depth=1, jump_kind="reach", expect="Preferences window visible") + def test_prefs_opens(self, ax_with_reset): + before = kit.rb_showing(ax_with_reset) + helpers.rb_reach_prefs(ax_with_reset) # a nav helper you name rb_reach_* / rb_enter_* + after = kit.rb_showing(ax_with_reset) + assert kit.rb_reach(before, after, target="Preferences", source="menu bar") + +conftest.py's pytest_runtest_makereport hook reads the marker + the test outcome and +writes {name, passed, depth, jump_kind, tier, expect} so the runner can fold it into +<module>_results.json. The audits below then read those records (+ the test SOURCE). + +jump_kind (verbatim strings — the audit/stats key off them): + "none" no trigger; existence/structure only -> tier 0 + "liveness" only "did not crash / still alive" -> tier 1 (weak; avoid) + "reach" a real surface jump: the TARGET surface's element + APPEARED and the SOURCE surface's element DISAPPEARED -> tier 2 + "transition" a state flip (CHECKED/ENABLED/mode) before->after -> tier 2 + "value" a specific expected value/content was asserted -> tier 3 + +DEPTH is the number of surfaces crossed before the assertion (0 = home/first screen, +1 = one dialog/panel/submenu, 2+ = deeper). A flat-tree read of a deep element is +depth 0 — depth counts surfaces the test actually navigated through. + +REACH PROOF (so "reach" cannot be faked by reading a flat tree): + before = rb_showing(ax) + <trigger: click the menu item / status item> + after = rb_showing(ax) + ok = rb_reach(before, after, target="Preferences", source="menu bar") + +SELF-AUDIT (report-only — goals, NOT a hard gate on finalize): + python3 -c "import rb_testgen_kit as k; k.rb_audit('<results_dir>')" + python3 -c "import rb_testgen_kit as k; k.rb_lint('<results_dir>')" + python3 -c "import rb_testgen_kit as k; k.rb_lint_sources('<testgen_dir>')" + python3 -c "import rb_testgen_kit as k; k.rb_audit_depth('<testgen_dir>','<results_dir>')" +""" +from __future__ import annotations + +import ast +import glob +import json +import os +import re + +JUMP_KINDS = {"none": 0, "liveness": 1, "reach": 2, "transition": 2, "value": 3} + +# Double-axis quota TARGETS (fractions) — goals rb_audit REPORTS, NOT a hard gate. +QUOTAS = { + "existence_max": 0.30, # jump_kind=="none" share of ALL tests + "interactive_min": 0.60, # reach|transition|value share of ALL tests + "depth_ge1_min": 0.40, # depth>=1 share of INTERACTIVE tests + "depth_ge2_min": 0.10, # depth>=2 share of INTERACTIVE tests + "value_min": 0.25, # jump_kind=="value" share of INTERACTIVE tests +} + +# Depth family: a test "crosses a surface" iff it calls a member of the depth family. +# macOS accepts BOTH the naming convention rb_enter_*/rb_reach_* (write your own nav +# helper and NAME it so) AND the existing verifier_helpers/ax_helpers navigation +# functions (whitelist below) — so tests can reuse the mature reveal/navigate helpers. +DEPTH_FWD_RE = re.compile(r"^rb_(enter|reach)[a-z0-9_]*$") +DEPTH_BACK_RE = re.compile(r"^rb_back[a-z0-9_]*$") +# verifier_helpers / ax_helpers navigation functions that OPEN or move to a new surface. +FWD_WHITELIST = { + "ensure_ui_visible", "ensure_panel_open", "open_actions_menu", "open_menu", + "open_settings", "open_preferences", "open_dialog", "open_panel", "open_window", + "navigate_month", "navigate", "switch_tab", "switch_mode", "switch_page", + "select_tab", "reveal_window", "show_panel", "show_menu", +} +BACK_WHITELIST = { + "dismiss_menus", "dismiss_panel", "dismiss_any_dialog", "close_panel", + "close_window", "go_back", +} +# pytest fixtures that themselves navigate into a surface during setup (so a test taking +# one legitimately has depth>=1 without a nav call in its own body). `ax` does NOT navigate. +_NAV_FIXTURES = {"ax_with_reset", "open_panel"} +# MEASURED-TIER verdict families (ported from keliang): a tier2/3 jump_kind must be BACKED +# by its verdict function — transition->rb_flip*, value->rb_value*, reach->rb_reach* — whose +# bool result is the test's assertion. Self-named wrappers count by prefix. +TIER_FLIP_RE = re.compile(r"^rb_flip[a-z0-9_]*$") +TIER_VALUE_RE = re.compile(r"^rb_value[a-z0-9_]*$") +_JK_FAMILY = {"transition": "flip", "value": "value", "reach": "reach"} +# normalize plural (v73prep) / singular module names so a JSON module ("button") and a +# file stem ("buttons") join. +_MODULE_ALIAS = {"menus": "menu", "buttons": "button", "states": "state", + "structures": "structure", "texts": "text", + "computations": "computation", "workflows": "workflow"} + +_DEPTH = 0 # module-global surface counter for rb_enter/rb_back + + +def tier_of(jump_kind: str) -> int: + return JUMP_KINDS.get(jump_kind, 2) + + +def rb_reset_depth() -> None: + global _DEPTH + _DEPTH = 0 + + +def rb_enter(_surface: str = "") -> int: + """Call right after your test navigates into a new surface (dialog/panel/submenu).""" + global _DEPTH + _DEPTH += 1 + return _DEPTH + + +def rb_back() -> int: + global _DEPTH + _DEPTH = max(0, _DEPTH - 1) + return _DEPTH + + +def _walk_tree_nodes(node, out, seen): + """Yield 'role|name' for a macOS AXHelper.tree() dict node (+children).""" + if not isinstance(node, dict) or seen[0] >= 8000: + return + seen[0] += 1 + role = str(node.get("role") or "") + name = str(node.get("name") or node.get("value") or "") + if role or name: + out.add(f"{role}|{name}") + for c in (node.get("children") or []): + _walk_tree_nodes(c, out, seen) + + +def rb_showing(ax, max_depth: int = 12) -> set: + """Snapshot the currently-reachable AX subtree under the app as {"role|name"}. + macOS AX has no AT-SPI SHOWING/VISIBLE state, so we approximate "showing" by the + live AX tree (AXChildren) the app currently exposes — a new window/sheet/popover + adds its elements; a dismissed one removes them. Feed before+after a trigger to + rb_reach() so a 'reach' test proves a REAL surface change, not a flat-tree read. + Safe no-op (empty set) if `ax` cannot produce a tree.""" + out: set = set() + try: + tree = ax.tree(max_depth=max_depth) # AXHelper.tree() -> nested dict + except Exception: + return out + _walk_tree_nodes(tree, out, [0]) + return out + + +def rb_reach(before, after, target: str, source: str | None = None) -> bool: + """True-jump verdict: the TARGET surface's discriminating element newly APPEARED + AND (if given) the SOURCE surface's discriminating element DISAPPEARED. This is + what separates a real surface jump from reading an element that was always there.""" + before = set(before or []) + after = set(after or []) + t = target.lower() + appeared = any(t in k.lower() for k in (after - before)) + if source is None: + return appeared + s = source.lower() + src_before = any(s in k.lower() for k in before) + src_after = any(s in k.lower() for k in after) + return appeared and src_before and not src_after + + +def rb_flip(before, after, expect: str = "") -> bool: + """In-page STATE-FLIP verdict (tier2 `transition`): the observed state actually CHANGED + before->after (a CHECKED/ENABLED/mode/selection value read the two times). Pass its bool + as the test's assertion. Does NOT touch depth — an in-page flip is depth 0 unless you + navigated a surface to reach the control. You MAY write your own `rb_flip_<what>()` wrapper.""" + try: + return before != after + except Exception: + return False + + +def rb_value(observed, expected) -> bool: + """VALUE verdict (tier3 `value`): a specific expected value/content matched what you + OBSERVED on the reference. Pass its bool as the test's assertion. Tolerant: exact match, + else the stringified `expected` appears in the stringified `observed` (mirrors rb_reach's + tolerant match). Does NOT touch depth. You MAY write your own `rb_value_<what>()` wrapper.""" + if observed is None: + return False + if observed == expected: + return True + try: + return bool(str(expected)) and str(expected) in str(observed) + except Exception: + return False + + +def rb_connect(app_name: str | None = None, wait_for_ready: bool = False): + """PORTABLE app acquisition for STANDALONE use — attach BY NAME to the running app + via AXHelper (never spawn, never hardcode the install path), so the SAME test drives + the reference AND the recreation. In normal pytest runs the `ax` fixture already does + this; use rb_connect only for a script run outside pytest. Returns an AXHelper or None.""" + try: + from ax_helpers import AXHelper + except Exception: + return None + name = (app_name or os.environ.get("APP_NAME") or "").strip() + if not name: + return None + try: + return AXHelper(name, wait_for_ready=wait_for_ready) + except Exception: + return None + + +class RBResults: + """Optional standalone recorder (parity with the Linux kit). In pytest mode the + conftest hook records depth/jump instead; keep this for scripts that self-run.""" + + def __init__(self, module: str, results_dir: str): + self.module = module + self.results_dir = results_dir + self.tests: list[dict] = [] + rb_reset_depth() + + def record(self, name: str, passed, *, depth: int | None = None, + jump_kind: str = "none", expect: str = "", msg: str = "") -> None: + if jump_kind not in JUMP_KINDS: + jump_kind = "none" + d = _DEPTH if depth is None else int(depth) + p = bool(passed) + self.tests.append({ + "name": name, "passed": p, "status": "passed" if p else "failed", + "depth": max(0, d), "jump_kind": jump_kind, "tier": tier_of(jump_kind), + "expect": str(expect), "message": str(msg), + }) + self._flush() + + def _flush(self) -> None: + payload = {"module": self.module, "tests": self.tests, + "passed": sum(1 for t in self.tests if t["passed"]), + "total": len(self.tests)} + for p in (os.path.join(self.results_dir, self.module, f"{self.module}_results.json"), + os.path.join(self.results_dir, f"{self.module}_results.json")): + try: + os.makedirs(os.path.dirname(p), exist_ok=True) + with open(p, "w") as f: + json.dump(payload, f, indent=2) + except Exception: + pass + + +def _load_all(results_dir: str) -> list[dict]: + """Every per-test record under results_dir (module subdirs included).""" + recs: list[dict] = [] + seen_files = set() + for pat in (os.path.join(results_dir, "*_results.json"), + os.path.join(results_dir, "*", "*_results.json"), + os.path.join(results_dir, "results", "*_results.json")): + for path in glob.glob(pat): + key = os.path.relpath(path, results_dir) + if key in seen_files or os.path.basename(path) == "baseline_results.json": + continue + seen_files.add(key) + try: + data = json.load(open(path)) + except Exception: + continue + for t in (data.get("tests", []) if isinstance(data, dict) else []): + if isinstance(t, dict) and "name" in t: + recs.append(t) + return recs + + +def rb_audit(results_dir: str, quotas: dict | None = None) -> dict: + """Aggregate declared depth/jump_kind and check the double-axis quotas. Prints + PASS/GAP per quota so the orchestrator can target its Improve round. REPORT-ONLY.""" + q = quotas or QUOTAS + recs = _load_all(results_dir) + n = len(recs) + if not n: + print(f"[rb_audit] no records under {results_dir}") + return {"total": 0} + kinds = [r.get("jump_kind", "none") for r in recs] + none_n = sum(1 for k in kinds if k == "none") + live_n = sum(1 for k in kinds if k == "liveness") + inter = [r for r in recs if r.get("jump_kind") in ("reach", "transition", "value")] + ni = len(inter) or 1 + d1 = sum(1 for r in inter if int(r.get("depth", 0) or 0) >= 1) + d2 = sum(1 for r in inter if int(r.get("depth", 0) or 0) >= 2) + val = sum(1 for r in inter if r.get("jump_kind") == "value") + + def line(label, got, need, kind): + ok = got >= need if kind == "min" else got <= need + return (ok, f" [{'ok ' if ok else 'GAP'}] {label}: {got:.0%} " + f"({'>=' if kind == 'min' else '<='} {need:.0%})") + + checks = [ + line("existence(none)/all", none_n / n, q["existence_max"], "max"), + line("interactive/all", len(inter) / n, q["interactive_min"], "min"), + line("depth>=1 /interactive", d1 / ni, q["depth_ge1_min"], "min"), + line("depth>=2 /interactive", d2 / ni, q["depth_ge2_min"], "min"), + line("value(tier3)/interactive", val / ni, q["value_min"], "min"), + ] + print(f"[rb_audit] {results_dir} total={n} interactive={len(inter)} " + f"none={none_n} liveness={live_n} depth>=1={d1} depth>=2={d2} value={val}") + for _ok, msg in checks: + print(msg) + passed = all(ok for ok, _ in checks) + print(f"[rb_audit] {'ALL TARGETS MET' if passed else 'some targets below — try a deeper reach/value test, or finalize (goals, NOT a hard gate)'}") + return {"total": n, "interactive": len(inter), "none": none_n, "liveness": live_n, + "depth_ge1": d1, "depth_ge2": d2, "value": val, "passed": passed} + + +def rb_lint(results_dir: str) -> list: + """Flag weak/inconsistent declarations: reach/transition/value with empty expect, + liveness (tier1), unknown jump_kind, negative depth. Prints + returns the issues.""" + recs = _load_all(results_dir) + issues = [] + for r in recs: + jk = r.get("jump_kind", "none") + nm = r.get("name", "?") + if jk not in JUMP_KINDS: + issues.append(f"{nm}: unknown jump_kind {jk!r}") + if jk in ("reach", "transition", "value") and not str(r.get("expect", "")).strip(): + issues.append(f"{nm}: jump_kind={jk} but empty expect (declare the specific observed target)") + if jk == "liveness": + issues.append(f"{nm}: liveness is tier1 — replace with the app-authored effect you can observe") + if int(r.get("depth", 0) or 0) < 0: + issues.append(f"{nm}: negative depth") + if issues: + print(f"[rb_lint] {len(issues)} issue(s):") + for i in issues: + print(" - " + i) + else: + print("[rb_lint] no issues") + return issues + + +# Non-portable source patterns: pass on the reference (testgen) but break on the +# recreation (eval, app at a different path). Each is a hard portability defect on macOS. +_BAD_SOURCE_PATTERNS = [ + (r"\.pipeline_refapp|/pipeline_work/", + "names a pipeline-internal reference path (gone/locked at eval) — attach via the ax fixture / rb_connect()"), + (r"/workspace/output/recreation|/var/tmp/pipeline_results", + "names an eval-only / pipeline path — a test must not know where the app is installed"), + (r"defaults['\"\s,]+write", + "seeds app state via `defaults write` — the recreation may use a different bundle id / defaults; drive state via the GUI"), + (r"open\s+-a\s+[\"']?[A-Z]", + "launches the app by a hardcoded name via `open -a` — use the ax fixture (host launches the app)"), + (r"subprocess\.(?:Popen|run|call)\([^)]*[\"'][^\"']*/(?:Applications|Users|usr|bin|var)/", + "spawns the app by an absolute path — attach to the launched instance via the ax fixture / rb_connect()"), + (r"AXUIElementCreateApplication\(", + "creates an AX app handle directly (usually a hardcoded pid/path) — use the ax fixture so the SAME test drives reference AND recreation"), +] + + +def rb_lint_sources(testgen_dir: str) -> list: + """Scan authored test/helper .py for NON-PORTABLE patterns (pipeline paths, defaults + seeding, absolute-path spawn, direct AX app creation) — so the suite drives the + recreation, not just the reference. REPORT-ONLY. Skips the kit/runner/helper libs.""" + _SKIP = ("rb_testgen_kit.py", "run_ax_tests.py", "ax_test_runner.py", + "ax_helpers.py", "verifier_helpers.py", "conftest.py", "verifier_template.py", + "verifier_lint.py", "lint.py", "prune_failing_tests.py", "vlm_judge.py") + py = [p for p in (glob.glob(os.path.join(testgen_dir, "*.py")) + + glob.glob(os.path.join(testgen_dir, "tests", "*.py"))) + if os.path.basename(p) not in _SKIP] + issues = [] + for p in py: + base = os.path.basename(p) + try: + src = open(p, errors="replace").read() + except Exception: + continue + for pat, why in _BAD_SOURCE_PATTERNS: + if re.search(pat, src): + issues.append(f"{base}: {why}") + if issues: + print(f"[rb_lint_sources] {len(issues)} portability issue(s):") + for i in issues: + print(" - " + i) + else: + print("[rb_lint_sources] no portability issues") + return issues + + +# ── MEASURED DEPTH cross-check (report-only): does the SOURCE back the DECLARED depth? ── +# macOS tests are pytest: declaration is a `@pytest.mark.rb(depth=, jump_kind=)` decorator +# on a Test* class method. A method with declared depth>=1 or jump_kind="reach" must call a +# depth-family member (rb_enter*/rb_reach* OR a whitelisted nav helper) directly, in a +# file-local helper it calls, or in an imported helper — else it is FAKE depth. +def _ast_call_name(node) -> str: + f = node.func + if isinstance(f, ast.Attribute): + return f.attr + if isinstance(f, ast.Name): + return f.id + return "" + + +def _is_fwd(cn: str) -> bool: + return bool(DEPTH_FWD_RE.match(cn)) or cn in FWD_WHITELIST + + +def _depth_calls(fn_node, local_funcs, budget: int = 2, seen=None): + """(n_fwd, n_reach): depth-family forward calls in fn_node, descending up to `budget` + levels into file-local functions it calls. Cycle-guarded. A LOWER BOUND on surfaces.""" + seen = seen if seen is not None else set() + n_fwd = n_reach = 0 + for node in ast.walk(fn_node): + if not isinstance(node, ast.Call): + continue + cn = _ast_call_name(node) + if _is_fwd(cn): + n_fwd += 1 + if cn.startswith("rb_reach"): + n_reach += 1 + elif budget > 0 and cn in local_funcs and cn not in seen: + seen.add(cn) + f, r = _depth_calls(local_funcs[cn], local_funcs, budget - 1, seen) + n_fwd += f + n_reach += r + return n_fwd, n_reach + + +def _rb_marker(fn_node): + """(depth, jump_kind) from a @pytest.mark.rb(...) decorator on a test method, else None.""" + for dec in getattr(fn_node, "decorator_list", []): + if not isinstance(dec, ast.Call): + continue + if _ast_call_name(dec) != "rb": + continue + depth, jk = 0, "none" + for kw in dec.keywords: + if kw.arg == "depth" and isinstance(kw.value, ast.Constant): + try: + depth = int(kw.value.value) + except Exception: + depth = 0 + elif kw.arg == "jump_kind" and isinstance(kw.value, ast.Constant): + jk = str(kw.value.value) + return depth, jk + return None + + +def rb_audit_depth(testgen_dir: str, results_dir: str | None = None) -> list: + """MEASURE navigation depth from the test SOURCE (AST) and cross-check the DECLARED + depth/jump_kind in each @pytest.mark.rb(...) marker — so a test can't just TYPE depth=2. + REPORT-ONLY: flags a declared depth>=1 or jump_kind="reach" whose method (and the local + helpers it calls) has NO depth-family call (rb_enter*/rb_reach* or a whitelisted nav + helper). Fix = add the nav helper you used (or name it rb_enter_*/rb_reach_*), or lower + the declared depth. depth-only; jump verdicts are a later phase.""" + issues = [] + pys = sorted(glob.glob(os.path.join(testgen_dir, "test_ax_*.py")) + + glob.glob(os.path.join(testgen_dir, "tests", "test_ax_*.py"))) + for p in pys: + try: + src = open(p, errors="replace").read() + tree = ast.parse(src) + except Exception: + continue + mod = os.path.basename(p)[len("test_ax_"):-len(".py")] + local_funcs = {n.name: n for n in ast.walk(tree) + if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))} + for node in ast.walk(tree): + if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): + continue + if not node.name.startswith("test_"): + continue + marker = _rb_marker(node) + if marker is None: + continue + depth, jk = marker + if not (depth >= 1 or jk == "reach"): + continue + # A method is "backed" iff IT (or a file-local helper it calls) makes a + # depth-family call, OR it takes a navigating fixture (ax_with_reset opens a + # panel in its setup). We DELIBERATELY do NOT fall back to file-level backing + # — that would let a fake-depth method ride on another test's nav call. + params = {a.arg for a in node.args.args} + fixture_nav = bool(params & _NAV_FIXTURES) + n_fwd, n_reach = _depth_calls(node, local_funcs) + if n_fwd == 0 and not fixture_nav: + issues.append(f"{mod}:{node.name}: declared depth={depth}/jump_kind={jk} but NO " + f"backing rb_enter*/rb_reach*/nav-helper call (fake depth)") + elif jk == "reach" and n_reach == 0 and not fixture_nav: + issues.append(f"{mod}:{node.name}: jump_kind=reach but no rb_reach* proof call " + f"(use kit.rb_reach(before,after,...) to prove the surface jump)") + if issues: + print(f"[rb_audit_depth] {len(issues)} fake-depth issue(s) (REPORT-ONLY — add the " + f"rb_reach/rb_enter/nav-helper you navigated with, or lower the declared depth):") + for i in issues: + print(" - " + i) + else: + print("[rb_audit_depth] no fake-depth issues (declared depth/reach backed by nav calls)") + return issues + + +def _tier_calls(fn_node, local_funcs, budget: int = 2, seen=None): + """Set of verdict families {'flip','value','reach'} called in fn_node, descending up to + `budget` levels into file-local helpers it calls. Cycle-guarded. Mirrors _depth_calls — + self-named wrappers (rb_flip_*/rb_value_*/rb_reach_*) count by prefix.""" + seen = seen if seen is not None else set() + fams = set() + for node in ast.walk(fn_node): + if not isinstance(node, ast.Call): + continue + cn = _ast_call_name(node) + if TIER_FLIP_RE.match(cn): + fams.add("flip") + elif TIER_VALUE_RE.match(cn): + fams.add("value") + elif cn.startswith("rb_reach"): + fams.add("reach") + elif budget > 0 and cn in local_funcs and cn not in seen: + seen.add(cn) + fams |= _tier_calls(local_funcs[cn], local_funcs, budget - 1, seen) + return fams + + +def rb_audit_tier(testgen_dir: str, results_dir: str | None = None) -> list: + """MEASURE jump RIGOR from the test SOURCE (AST) and cross-check the DECLARED jump_kind in + each @pytest.mark.rb(...) marker — so a test can't just TYPE jump_kind="value". REPORT-ONLY + (NOT a finalize gate). A tier2/3 claim must be backed by its verdict call: transition->rb_flip*, + value->rb_value* (reach->rb_reach* is already covered by rb_audit_depth). Flags a declared + transition/value whose method (and the local helpers it calls) has NO such verdict call. + Fix = add rb_flip(before,after)/rb_value(observed,expected) and pass its result as the assert, + or drop to a weaker jump_kind you can prove. Pytest-marker form (mirrors rb_audit_depth), + NOT keliang's record() form.""" + issues = [] + pys = sorted(glob.glob(os.path.join(testgen_dir, "test_ax_*.py")) + + glob.glob(os.path.join(testgen_dir, "tests", "test_ax_*.py"))) + for p in pys: + try: + src = open(p, errors="replace").read() + tree = ast.parse(src) + except Exception: + continue + mod = os.path.basename(p)[len("test_ax_"):-len(".py")] + local_funcs = {n.name: n for n in ast.walk(tree) + if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))} + for node in ast.walk(tree): + if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): + continue + if not node.name.startswith("test_"): + continue + marker = _rb_marker(node) + if marker is None: + continue + _depth, jk = marker + fam = _JK_FAMILY.get(jk) + if fam is None or jk == "reach": # none/liveness need no verdict; reach->rb_audit_depth + continue + fams = _tier_calls(node, local_funcs) + if fam not in fams: + issues.append(f"{mod}:{node.name}: declared jump_kind={jk} (tier {tier_of(jk)}) but " + f"NO backing rb_{fam}* verdict call — unbacked tier") + if issues: + print(f"[rb_audit_tier] {len(issues)} unbacked-tier issue(s) (REPORT-ONLY — back a " + f"transition with rb_flip(before,after) and a value with rb_value(observed,expected), " + f"passing its result as the assertion; or drop to a jump_kind you can prove):") + for i in issues: + print(" - " + i) + else: + print("[rb_audit_tier] no unbacked-tier issues (transition/value backed by verdict calls)") + return issues + + +if __name__ == "__main__": + import sys + _fns = {"audit": rb_audit, "lint": rb_lint, "lint_sources": rb_lint_sources} + _fns2 = {"audit_depth": rb_audit_depth, "audit_tier": rb_audit_tier} + if sys.argv[1:2] and sys.argv[1] in _fns2 and len(sys.argv) >= 3: + _fns2[sys.argv[1]](sys.argv[2], sys.argv[3] if len(sys.argv) >= 4 else None) + elif len(sys.argv) >= 3 and sys.argv[1] in _fns: + _fns[sys.argv[1]](sys.argv[2]) + else: + print("usage: rb_testgen_kit.py {audit|lint|lint_sources <dir> | " + "{audit_depth|audit_tier} <testgen_dir> [results_dir]}") diff --git a/macos/sqlitebrowser-sqlitebrowser/tests/requirements.txt b/macos/sqlitebrowser-sqlitebrowser/tests/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..feef67ce2aadbaa26d12e6b01cff7b8ce89ecb5c --- /dev/null +++ b/macos/sqlitebrowser-sqlitebrowser/tests/requirements.txt @@ -0,0 +1,3 @@ +pytest +pytest-check +pyobjc diff --git a/macos/sqlitebrowser-sqlitebrowser/tests/test_ax_buttons.py b/macos/sqlitebrowser-sqlitebrowser/tests/test_ax_buttons.py new file mode 100644 index 0000000000000000000000000000000000000000..4d8f4a6f17382994d0946a1249d1a418c3bc57d4 --- /dev/null +++ b/macos/sqlitebrowser-sqlitebrowser/tests/test_ax_buttons.py @@ -0,0 +1,815 @@ +"""AX button-interaction tests for DB Browser for SQLite (Qt6). + +Every assertion below encodes an OBSERVED CONSEQUENCE recorded in recon.md +(`## BUTTONS` B-groups 1..5, `## STATE` ST8/ST9/ST10, `## COMPUTATION`, `## TEXT` T4/T5): +an AXEnabled flip, a new surface, or a changed value / label / counter. + +Safety contract honoured here: no press of New Database / Open Database / Open Project / +Save Project / Save Table As / New Data Browser / Save results / Open SQL file(s) / +Save SQL file / Attach Database / Write Changes / Revert Changes / Upload / Refresh / +Clone from Link / Import / Export / Print / Set as NULL / any dock Close or Float / +any window-chrome button. Dialogs are always closed with their OWN scoped `Cancel`. +""" + +import json +import os +import re +import subprocess +import time + +import pytest +import rb_testgen_kit as kit + +RESULTS_DIR = os.environ.get("RESULTS_DIR", os.path.dirname(os.path.abspath(__file__))) +COUNTER_RE = re.compile(r"^\s*\d+\s*-\s*\d+\s+of\s+\d+\s*$") + + +def screenshot_assert(test_name, description, results_dir): + 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) + + +def _esc(times=1): + for _ in range(times): + subprocess.run(["osascript", "-e", + 'tell application "System Events" to key code 53'], + capture_output=True) + time.sleep(0.3) + + +def _keystroke(text): + subprocess.run(["osascript", "-e", + 'tell application "System Events" to keystroke ' + json.dumps(text)], + capture_output=True) + + +def open_menu(ax, top): + mb = ax.find(role="menu_bar_item", name=top, max_results=1) + if not mb: + return None + ax.action(mb[0].id, "AXPress") + time.sleep(0.6) + m = ax.find(role="menu", root_id=mb[0].id, max_results=1, max_depth=1) + return m[0] if m else None + + +def rb_reach_menu_item(ax, top, item_name): + m = open_menu(ax, top) + if m is None: + return False + for it in ax.find(role="menu_item", root_id=m.id, max_results=80, max_depth=1): + if (it.name or "") == item_name: + ok = ax.action(it.id, "AXPress") + time.sleep(1.4) + return bool(ok) + _esc(2) + return False + + +def find_window(ax, title_substr): + for w in ax.find(role="window", max_results=10, max_depth=1): + if title_substr.lower() in (w.name or "").lower(): + return w + return None + + +def rb_enter_inmemory_db(ax): + """File > New In-Memory Database, then dismiss the auto-opened table dialog.""" + rb_reach_menu_item(ax, "File", "New In-Memory Database") + w = find_window(ax, "Edit table definition") + if w is not None: + c = ax.find(role="button", name="Cancel", root_id=w.id, max_results=2) + if c: + ax.action(c[0].id, "AXPress") + time.sleep(1.0) + return find_window(ax, "Edit table definition") is None + + +def switch_tab(ax, name): + r = ax.find(role="radio", name=name, max_results=1) + if not r: + return False + ok = ax.action(r[0].id, "AXPress") + time.sleep(1.0) + return bool(ok) + + +def find_button(ax, name, root_id=None): + for b in ax.find(role="button", max_results=90, root_id=root_id): + if (b.name or "") == name: + return b + return None + + +def enabled(ax, el): + return bool(ax.get(el.id, ["AXEnabled"]).get("AXEnabled")) + + +def btn_enabled(ax, name): + b = find_button(ax, name) + return None if b is None else enabled(ax, b) + + +def sql_editor(ax): + """The QScintilla SQL editor: the only settable text_area that is not the SQL log.""" + for t in ax.find(role="text_area", max_results=15): + if not ax.is_attribute_settable(t.id, "AXValue"): + continue + v = str(ax.get(t.id, ["AXValue"]).get("AXValue") or "") + if "PRAGMA" in v or "EXECUTING" in v: + continue + return t + return None + + +def run_sql(ax, sql): + """Type + execute SQL. set_value is IGNORED by QScintilla -> click + keystroke.""" + switch_tab(ax, "Execute SQL") + e = sql_editor(ax) + assert e is not None, "SQL editor not found" + ax.click_element_cg(e.id) + time.sleep(0.35) + subprocess.run(["osascript", "-e", + 'tell application "System Events" to keystroke "a" using command down'], + capture_output=True) + time.sleep(0.25) + _keystroke(sql) + time.sleep(0.5) + b = find_button(ax, "Execute SQL") + assert b is not None and enabled(ax, b), "Execute SQL button not enabled" + ax.action(b.id, "AXPress") + time.sleep(1.9) + + +def result_cells(ax): + cols, cells = [], [] + for t in ax.find(role="table", max_results=10): + if (t.name or "") == "search result": + continue + ch = (ax.tree(max_depth=3, root_id=t.id).get("children") or []) + c = [x.get("name") for x in ch if x.get("role") == "column"] + v = [x.get("name") for x in ch if x.get("role") == "label"] + if c or v: + cols, cells = c, v + return cols, cells + + +def record_counter(ax): + """Browse Data counter label, e.g. '1 - 3 of 3'. MUST use the regex — a plain + ' of ' test also matches 'Identification of the cell currently in the editor'.""" + for l in ax.find(role="label", max_results=350): + v = str(ax.get(l.id, ["AXValue"]).get("AXValue") or "") + if COUNTER_RE.match(v): + return v.strip() + return None + + +def label_value(ax, needle): + for l in ax.find(role="label", max_results=350): + v = str(ax.get(l.id, ["AXValue"]).get("AXValue") or "") + if needle in v: + return v + return None + + +# --------------------------------------------------------------------------- +# extra locators built on the skeleton (semantic: AXTitle/AXDescription + AXRole, +# scoped by named parent container — never by child index or tree path) +# --------------------------------------------------------------------------- + +SQL_SUBTAB_RE = re.compile(r"^SQL\s+\d+$") + + +def main_window(ax): + """The main app window, matched on its visible title (never by index).""" + for w in ax.find(role="window", max_results=10, max_depth=1): + if (w.name or "").startswith("DB Browser for SQLite"): + return w + return None + + +def reveal_main_window(ax): + """The app is a regular windowed app (recon REVEAL_STEPS): the main window is already + on screen at launch. Raise it so window-dependent checks + screenshots see it.""" + w = main_window(ax) + if w is not None: + try: + ax.action(w.id, "AXRaise") + time.sleep(0.3) + except Exception: + pass + return w + + +def find_text_field(ax, name, root_id=None, contains=False): + for t in ax.find(role="text_field", max_results=60, root_id=root_id): + n = t.name or "" + if (name in n) if contains else (n == name): + return t + return None + + +def find_checkbox(ax, name, root_id=None, contains=False): + for c in ax.find(role="checkbox", max_results=60, root_id=root_id): + n = c.name or "" + if (name in n) if contains else (n == name): + return c + return None + + +def dialog_ddl_preview(ax, win): + """The dialog's read-only SQL box: its text_area whose AXValue contains CREATE.""" + for t in ax.find(role="text_area", max_results=10, root_id=win.id): + v = str(ax.get(t.id, ["AXValue"]).get("AXValue") or "") + if "CREATE" in v: + return v + return None + + +def sql_log_pane(ax): + """(element, value) of the SQL Log dock text_area — it holds the PRAGMA trace.""" + for t in ax.find(role="text_area", max_results=15): + v = str(ax.get(t.id, ["AXValue"]).get("AXValue") or "") + if "PRAGMA" in v: + return t, v + return None, "" + + +def enabled_map(ax, names): + return {n: btn_enabled(ax, n) for n in names} + + +def prove_value(observed, expected): + """kit.rb_value proof that tolerates dict/str shapes for map-valued observations.""" + try: + if kit.rb_value(observed, expected): + return True + except Exception: + pass + return bool(kit.rb_value(json.dumps(observed, sort_keys=True, default=str), + json.dumps(expected, sort_keys=True, default=str))) + + +def close_dialog_with_cancel(ax, win): + c = ax.find(role="button", name="Cancel", root_id=win.id, max_results=2) + assert c, "dialog exposes no scoped Cancel button" + ax.action(c[0].id, "AXPress") + time.sleep(1.0) + + +# --------------------------------------------------------------------------- + + +class TestToolbarButtonStates: + """B-group 1 — DB toolbar / project toolbar / Database-Structure toolbar buttons.""" + + @pytest.mark.rb( + depth=0, jump_kind="value", + expect="Write Changes/Revert Changes/Undo/Save Project/Attach Database/Create Table/" + "Create Index/Modify Table all AXEnabled False on a fresh app while " + "New Database/Open Database/Open Project are True", + ) + def test_toolbar_disabled_state_without_database(self, ax): + w = reveal_main_window(ax) + assert w is not None, "no main window named 'DB Browser for SQLite' in the AX tree" + assert (w.name or "") == "DB Browser for SQLite", ( + "a fresh app must have NO database open (recon T2), got title %r" % (w.name,)) + + expected = { + "New Database": True, + "Open Database": True, + "Open Project": True, + "Write Changes": False, + "Revert Changes": False, + "Undo": False, + "Save Project": False, + "Attach Database": False, + "Create Table": False, + "Create Index": False, + "Modify Table": False, + } + observed = enabled_map(ax, list(expected)) + + missing = [n for n, v in observed.items() if v is None] + assert not missing, "toolbar buttons absent from the AX tree: %r" % (missing,) + assert observed == expected, ( + "fresh-app toolbar AXEnabled map mismatch:\n observed=%r\n expected=%r" + % (observed, expected)) + assert prove_value(observed, expected) + + screenshot_assert( + "buttons_toolbar_fresh_state", + "DB Browser for SQLite main window, no database open. Top toolbar row shows " + "New Database and Open Database (Open Database has a dropdown chevron) as active " + "icons, while Write Changes, Revert Changes, Undo, Open Project (active), " + "Save Project and Attach Database follow — Write Changes, Revert Changes, Undo, " + "Save Project and Attach Database are greyed out/disabled. Below the toolbar a " + "4-tab bar reads Database Structure (selected), Browse Data, Edit Pragmas, " + "Execute SQL, and above the empty schema tree the Create Table, Create Index and " + "Modify Table buttons are also greyed out. Right side shows the Edit Database Cell " + "dock with a Mode: dropdown reading Text and the Remote dock; bottom dock tab strip " + "reads SQL Log, Plot, DB Schema, Remote; status bar bottom-right reads UTF-8.", + RESULTS_DIR) + + @pytest.mark.rb( + depth=1, jump_kind="transition", + expect="button 'Create Table' AXEnabled False->True after File>New In-Memory Database", + ) + def test_create_table_button_enables_with_database(self, ax): + reveal_main_window(ax) + before = btn_enabled(ax, "Create Table") + assert before is False, "Create Table must start disabled with no DB, got %r" % (before,) + + assert rb_enter_inmemory_db(ax), "in-memory DB did not open (modal still present)" + + after = btn_enabled(ax, "Create Table") + assert after is True, "Create Table must become enabled once a DB exists, got %r" % (after,) + assert kit.rb_flip(before, after) + + w = main_window(ax) + assert w is not None and "In-Memory database" in (w.name or ""), ( + "main window title must gain '- In-Memory database', got %r" + % (None if w is None else w.name,)) + + @pytest.mark.rb( + depth=1, jump_kind="transition", + expect="'Create Index' and 'Attach Database' AXEnabled False->True after opening the " + "in-memory database", + ) + def test_create_index_and_attach_buttons_enable_with_database(self, ax): + reveal_main_window(ax) + before = (btn_enabled(ax, "Create Index"), btn_enabled(ax, "Attach Database")) + assert before == (False, False), ( + "Create Index / Attach Database must both start disabled, got %r" % (before,)) + + assert rb_enter_inmemory_db(ax), "in-memory DB did not open (modal still present)" + + after = (btn_enabled(ax, "Create Index"), btn_enabled(ax, "Attach Database")) + assert after == (True, True), ( + "Create Index / Attach Database must both be enabled with a DB, got %r" % (after,)) + assert kit.rb_flip(before, after) + + @pytest.mark.rb( + depth=1, jump_kind="transition", + expect="Write Changes / Revert Changes AXEnabled False->True after CREATE TABLE via " + "Execute SQL", + ) + def test_write_changes_button_enables_after_ddl(self, ax): + reveal_main_window(ax) + assert rb_enter_inmemory_db(ax), "in-memory DB did not open (modal still present)" + + before = (btn_enabled(ax, "Write Changes"), btn_enabled(ax, "Revert Changes")) + assert before == (False, False), ( + "a freshly created DB has no pending changes, so Write/Revert Changes must be " + "disabled, got %r" % (before,)) + + run_sql(ax, "CREATE TABLE t1(a INTEGER, b TEXT);") + + after = (btn_enabled(ax, "Write Changes"), btn_enabled(ax, "Revert Changes")) + assert after == (True, True), ( + "DDL opens a transaction, so Write/Revert Changes must be enabled, got %r" % (after,)) + assert kit.rb_flip(before, after) + # never pressed: committing / rolling back destabilises the shared session + + +class TestStructureToolbarDialogButtons: + """B-group 1 press effects + B-group 5 dialog buttons.""" + + @pytest.mark.rb( + depth=1, jump_kind="reach", + expect="window 'Edit table definition' opens with preview CREATE TABLE \"\" ( );", + ) + def test_create_table_button_opens_edit_table_definition_dialog(self, ax): + reveal_main_window(ax) + assert rb_enter_inmemory_db(ax), "in-memory DB did not open (modal still present)" + + before = kit.rb_showing(ax) + b = find_button(ax, "Create Table") + assert b is not None and enabled(ax, b), "Create Table button missing or disabled" + ax.action(b.id, "AXPress") + time.sleep(1.4) + after = kit.rb_showing(ax) + + assert kit.rb_reach(before, after, target="window|Edit table definition") + + w = find_window(ax, "Edit table definition") + assert w is not None, "no window titled 'Edit table definition' after the press" + + preview = dialog_ddl_preview(ax, w) + assert preview == 'CREATE TABLE "" (\n\n);', ( + "freshly opened dialog DDL preview mismatch: %r" % (preview,)) + + dialog_buttons = { + "Add": True, # a new field can always be appended + "Remove": False, # nothing to remove yet + "OK": False, # table has no name yet + "Cancel": True, + } + observed = {} + for name, _ in dialog_buttons.items(): + el = find_button(ax, name, root_id=w.id) + observed[name] = None if el is None else enabled(ax, el) + assert observed == dialog_buttons, ( + "Edit-table-definition button enabled map mismatch:\n observed=%r\n expected=%r" + % (observed, dialog_buttons)) + + screenshot_assert( + "buttons_create_table_dialog", + "A modal window titled 'Edit table definition' is open in front of the DB Browser " + "for SQLite main window. It shows a 'Table' name field (empty), an 'Advanced' " + "checkbox, an empty field grid whose column headers read Name, Type, NN, PK, AI, U, " + "Default, Check, Collation, Foreign Key, a column of Add / Remove / Move up / " + "Move down / Move to top / Move to bottom buttons (only Add is enabled), the tab row " + "Fields / Index Constraints / Foreign Keys / Check Constraints with Fields selected, " + "a read-only SQL box showing CREATE TABLE \"\" ( ); and OK (greyed out) plus Cancel " + "buttons at the bottom.", + RESULTS_DIR) + + close_dialog_with_cancel(ax, w) + assert find_window(ax, "Edit table definition") is None, ( + "the dialog's own Cancel button must close 'Edit table definition'") + + @pytest.mark.rb( + depth=1, jump_kind="reach", + expect="window 'Edit Index Schema' opens from the Create Index toolbar button", + ) + def test_create_index_button_opens_edit_index_schema_dialog(self, ax): + reveal_main_window(ax) + assert rb_enter_inmemory_db(ax), "in-memory DB did not open (modal still present)" + + before = kit.rb_showing(ax) + b = find_button(ax, "Create Index") + assert b is not None and enabled(ax, b), "Create Index button missing or disabled" + ax.action(b.id, "AXPress") + time.sleep(1.4) + after = kit.rb_showing(ax) + + assert kit.rb_reach(before, after, target="window|Edit Index Schema") + + w = find_window(ax, "Edit Index Schema") + assert w is not None, "no window titled 'Edit Index Schema' after the press" + + name_field = find_text_field(ax, "Name", root_id=w.id) + unique_box = find_checkbox(ax, "Unique", root_id=w.id) + partial = find_text_field(ax, "Partial", root_id=w.id, contains=True) + cancel = ax.find(role="button", name="Cancel", root_id=w.id, max_results=2) + ok_btn = find_button(ax, "OK", root_id=w.id) + + assert name_field is not None, "Edit Index Schema exposes no text_field 'Name'" + assert unique_box is not None, "Edit Index Schema exposes no checkbox 'Unique'" + assert partial is not None, ( + "Edit Index Schema exposes no partial-index-clause text_field") + assert cancel, "Edit Index Schema exposes no scoped Cancel button" + assert ok_btn is not None and enabled(ax, ok_btn) is False, ( + "OK must stay disabled while the index is unnamed") + + close_dialog_with_cancel(ax, w) + assert find_window(ax, "Edit Index Schema") is None, ( + "the dialog's own Cancel button must close 'Edit Index Schema'") + + @pytest.mark.rb( + depth=2, jump_kind="value", + expect='preview goes CREATE TABLE "people" ( ) -> adds "Field1" INTEGER -> ' + 'adds "Field2" INTEGER', + ) + def test_dialog_add_button_grows_create_table_preview(self, ax): + reveal_main_window(ax) + # surface 1: the in-memory DB (its auto-opened dialog is dismissed by the helper) + assert rb_enter_inmemory_db(ax), "in-memory DB did not open (modal still present)" + + # surface 2: re-open the table designer through the toolbar button + b = find_button(ax, "Create Table") + assert b is not None and enabled(ax, b), "Create Table button missing or disabled" + ax.action(b.id, "AXPress") + time.sleep(1.4) + w = find_window(ax, "Edit table definition") + assert w is not None, "'Edit table definition' did not re-open" + + table_field = find_text_field(ax, "Table", root_id=w.id) + assert table_field is not None, "dialog exposes no text_field 'Table'" + ax.set_value(table_field.id, "people") + time.sleep(0.5) + named = dialog_ddl_preview(ax, w) + assert named == 'CREATE TABLE "people" (\n\n);', ( + "preview after naming the table mismatch: %r" % (named,)) + + add = find_button(ax, "Add", root_id=w.id) + assert add is not None and enabled(ax, add), "dialog 'Add' button missing or disabled" + + ax.action(add.id, "AXPress") + time.sleep(0.6) + one_field = dialog_ddl_preview(ax, w) + assert one_field == 'CREATE TABLE "people" (\n\t"Field1"\tINTEGER\n);', ( + "preview after the first Add mismatch: %r" % (one_field,)) + + add = find_button(ax, "Add", root_id=w.id) or add + ax.action(add.id, "AXPress") + time.sleep(0.6) + two_fields = dialog_ddl_preview(ax, w) + expected = ('CREATE TABLE "people" (\n\t"Field1"\tINTEGER,' + '\n\t"Field2"\tINTEGER\n);') + assert two_fields == expected, ( + "preview after the second Add mismatch: %r" % (two_fields,)) + assert kit.rb_value(two_fields, expected) + + close_dialog_with_cancel(ax, w) + assert find_window(ax, "Edit table definition") is None, ( + "the dialog's own Cancel button must close 'Edit table definition'") + + +class TestExecuteSqlButtons: + """B-group 2 — Execute SQL tab toolbar buttons.""" + + @pytest.mark.rb( + depth=1, jump_kind="value", + expect="Execute SQL tab, no DB: New tab/Open SQL file(s)/Save SQL file/Find or replace/" + "Un/comment block/Stop execution True; Execute SQL/Execute line/Save results False", + ) + def test_execute_sql_buttons_enabled_map_without_database(self, ax): + reveal_main_window(ax) + assert switch_tab(ax, "Execute SQL"), "no radio named 'Execute SQL' in the main tab bar" + + expected = { + "New tab": True, + "Open SQL file(s)": True, + "Save SQL file": True, + "Find or replace": True, + "Un/comment block": True, + "Stop execution": True, + "Execute SQL": False, + "Execute line": False, + "Save results": False, + } + observed = enabled_map(ax, list(expected)) + + missing = [n for n, v in observed.items() if v is None] + assert not missing, "Execute-SQL toolbar buttons absent from the AX tree: %r" % (missing,) + assert observed == expected, ( + "Execute-SQL button AXEnabled map (no DB) mismatch:\n observed=%r\n expected=%r" + % (observed, expected)) + assert prove_value(observed, expected) + # no file-dialog button was pressed + + @pytest.mark.rb( + depth=1, jump_kind="reach", + expect="SQL sub-tab 'SQL 1' created (radio|SQL 1 appears)", + ) + def test_new_tab_button_creates_sql_sub_tab(self, ax): + reveal_main_window(ax) + assert switch_tab(ax, "Execute SQL"), "no radio named 'Execute SQL' in the main tab bar" + + pre = [r.name for r in ax.find(role="radio", max_results=40) + if SQL_SUBTAB_RE.match(r.name or "")] + assert pre == [], "no SQL sub-tab may exist before pressing New tab, found %r" % (pre,) + + before = kit.rb_showing(ax) + b = find_button(ax, "New tab") + assert b is not None and enabled(ax, b), "New tab button missing or disabled" + ax.action(b.id, "AXPress") + time.sleep(1.0) + after = kit.rb_showing(ax) + + assert kit.rb_reach(before, after, target="radio|SQL 1") + + post = [r.name for r in ax.find(role="radio", max_results=40) + if SQL_SUBTAB_RE.match(r.name or "")] + assert post == ["SQL 1"], "expected exactly one sub-tab 'SQL 1', found %r" % (post,) + + @pytest.mark.rb( + depth=1, jump_kind="value", + expect="Execute SQL button False->True, and running SELECT 7*6 AS answer; yields " + "column 'answer' cell '42'", + ) + def test_execute_sql_button_enables_with_database_and_computes(self, ax): + reveal_main_window(ax) + assert switch_tab(ax, "Execute SQL"), "no radio named 'Execute SQL' in the main tab bar" + + before = btn_enabled(ax, "Execute SQL") + assert before is False, ( + "Execute SQL must be disabled while no database is open, got %r" % (before,)) + + assert rb_enter_inmemory_db(ax), "in-memory DB did not open (modal still present)" + + after = btn_enabled(ax, "Execute SQL") + assert after is True, ( + "Execute SQL must become enabled once a database is open, got %r" % (after,)) + + run_sql(ax, "SELECT 7*6 AS answer;") + + cols, cells = result_cells(ax) + assert cols == ["answer"], "results grid columns mismatch: %r" % (cols,) + assert kit.rb_value(cells, "42") + assert "42" in [str(c) for c in cells], "results grid cells mismatch: %r" % (cells,) + + screenshot_assert( + "buttons_execute_sql_result", + "DB Browser for SQLite with the in-memory database open and the Execute SQL tab " + "active. The SQL editor holds the statement SELECT 7*6 AS answer; the Execute " + "toolbar (green play icon plus Execute line, Stop, open/save SQL, New tab, find and " + "comment icons) sits above it with Execute now enabled, the results grid below shows " + "a single column headed 'answer' containing the value 42, and the message pane reads " + "'Execution finished without errors. Result: 1 rows returned in ...'.", + RESULTS_DIR) + + +class TestBrowseDataButtons: + """B-group 3 — Browse Data tab buttons.""" + + def _load_nums(self, ax, rows_sql): + assert rb_enter_inmemory_db(ax), "in-memory DB did not open (modal still present)" + run_sql(ax, "CREATE TABLE nums(n INTEGER, label TEXT); " + "INSERT INTO nums VALUES" + rows_sql + ";") + assert switch_tab(ax, "Browse Data"), "no radio named 'Browse Data' in the main tab bar" + + @pytest.mark.rb( + depth=1, jump_kind="value", + expect="Browse Data counter '1 - 3 of 3' -> '1 - 4 of 4' after pressing New Record", + ) + def test_new_record_button_increments_record_counter(self, ax): + reveal_main_window(ax) + self._load_nums(ax, "(10,'ten'),(20,'twenty'),(30,'thirty')") + + before = record_counter(ax) + assert before == "1 - 3 of 3", "record counter before New Record: %r" % (before,) + + b = find_button(ax, "New Record") + assert b is not None and enabled(ax, b), "New Record button missing or disabled" + ax.action(b.id, "AXPress") + time.sleep(1.4) + + after = record_counter(ax) + assert kit.rb_value(after, "1 - 4 of 4") + assert after == "1 - 4 of 4", "record counter after New Record: %r" % (after,) + + screenshot_assert( + "buttons_new_record_counter", + "DB Browser for SQLite, Browse Data tab active on the in-memory database. A " + "'Table:' dropdown reads nums, the data grid has columns _rowid_, n, label with the " + "rows 10/ten, 20/twenty, 30/thirty plus a newly inserted empty row at the bottom, a " + "'Filter in any column' box sits under the headers, and the record navigation strip " + "(|< < > >| and Go to:) with the record counter now reads '1 - 4 of 4' after the New " + "Record button was pressed.", + RESULTS_DIR) + + @pytest.mark.rb( + depth=1, jump_kind="transition", + expect="Clear Filters False->True when a filter is set, and pressing it restores counter " + "'1 - 3 of 3' and empties the filter", + ) + def test_clear_filters_button_round_trip(self, ax): + reveal_main_window(ax) + self._load_nums(ax, "(10,'ten'),(20,'twenty'),(30,'thirty')") + + assert btn_enabled(ax, "Clear Filters") is False, ( + "Clear Filters must be disabled on a freshly loaded, unfiltered table") + c0 = record_counter(ax) + assert c0 == "1 - 3 of 3", "record counter before filtering: %r" % (c0,) + + f = find_text_field(ax, "Filter in any column") + assert f is not None, "no text_field 'Filter in any column' on the Browse Data tab" + ax.set_value(f.id, "twenty") + time.sleep(1.6) + + filtered_enabled = btn_enabled(ax, "Clear Filters") + c1 = record_counter(ax) + assert filtered_enabled is True, ( + "Clear Filters must become enabled once a filter is active, got %r" + % (filtered_enabled,)) + assert c1 == "1 - 1 of 1", "record counter while filtered on 'twenty': %r" % (c1,) + assert kit.rb_flip((False, c0), (filtered_enabled, c1)) + + screenshot_assert( + "buttons_clear_filters_filtered", + "DB Browser for SQLite, Browse Data tab on table nums with a filter applied: the " + "'Filter in any column' box contains the text twenty, the data grid (columns " + "_rowid_, n, label) shows only ONE visible row 20 / twenty, the record counter reads " + "'1 - 1 of 1', and the Clear Filters button in the toolbar strip is now enabled " + "(no longer greyed out).", + RESULTS_DIR) + + cf = find_button(ax, "Clear Filters") + assert cf is not None and enabled(ax, cf), "Clear Filters button missing or disabled" + ax.action(cf.id, "AXPress") + time.sleep(1.6) + + assert btn_enabled(ax, "Clear Filters") is False, ( + "Clear Filters must disable itself again once no filter remains") + f2 = find_text_field(ax, "Filter in any column") + assert f2 is not None, "the filter field disappeared after Clear Filters" + fv = str(ax.get(f2.id, ["AXValue"]).get("AXValue") or "") + assert fv == "", "filter field must be emptied by Clear Filters, got %r" % (fv,) + c2 = record_counter(ax) + assert c2 == "1 - 3 of 3", "record counter after Clear Filters: %r" % (c2,) + + @pytest.mark.rb( + depth=1, jump_kind="value", + expect="|< < > >| Go to: New Record Save Table As New Data Browser enabled and " + "Clear Filters/Clear Sorting disabled on a freshly loaded table", + ) + def test_browse_data_navigation_buttons_enabled_with_data(self, ax): + reveal_main_window(ax) + self._load_nums(ax, "(10,'ten'),(20,'twenty')") + + expected = { + "|<": True, + "<": True, + ">": True, + ">|": True, + "Go to:": True, + "New Record": True, + "Save Table As": True, + "New Data Browser": True, + "Clear Filters": False, + "Clear Sorting": False, + } + observed = enabled_map(ax, list(expected)) + + missing = [n for n, v in observed.items() if v is None] + assert not missing, "Browse-Data buttons absent from the AX tree: %r" % (missing,) + assert observed == expected, ( + "Browse-Data button AXEnabled map mismatch:\n observed=%r\n expected=%r" + % (observed, expected)) + assert prove_value(observed, expected) + + goto = find_text_field(ax, "Enter record number to browse") + assert goto is not None, "'Go to:' has no paired record-number text_field" + # Save Table As / New Data Browser were never pressed (they raise dialogs/windows) + + +class TestDockPanelButtons: + """B-group 4 — SQL Log / Plot / Remote / Edit-Database-Cell dock buttons.""" + + @pytest.mark.rb( + depth=1, jump_kind="transition", + expect="SQL Log dock text_area AXValue starts with PRAGMA foreign_keys = '1'; before " + "Clear and is '' after", + ) + def test_sql_log_clear_button_empties_the_log(self, ax): + reveal_main_window(ax) + assert rb_enter_inmemory_db(ax), "in-memory DB did not open (modal still present)" + assert switch_tab(ax, "SQL Log"), "no dock radio named 'SQL Log'" + + pane, before_value = sql_log_pane(ax) + assert pane is not None, "no SQL-log text_area holding the PRAGMA trace" + assert before_value.startswith("PRAGMA foreign_keys = '1';"), ( + "SQL log must record the connection PRAGMAs, got %r" % (before_value[:120],)) + + b = find_button(ax, "Clear") + assert b is not None and enabled(ax, b), "SQL Log dock 'Clear' button missing or disabled" + ax.action(b.id, "AXPress") + time.sleep(0.6) + + after_value = str(ax.get(pane.id, ["AXValue"]).get("AXValue") or "") + assert after_value == "", "Clear must empty the SQL log, got %r" % (after_value[:120],) + assert kit.rb_flip(before_value, after_value) + + @pytest.mark.rb( + depth=0, jump_kind="value", + expect="Load all data and redraw plot / Save current plot / Upload / Refresh / " + "Clone from Link / Import / Export / Set as NULL / Print / Apply all " + "AXEnabled False on a fresh app", + ) + def test_plot_and_cell_editor_buttons_disabled_without_database(self, ax): + w = reveal_main_window(ax) + assert w is not None, "no main window named 'DB Browser for SQLite' in the AX tree" + assert (w.name or "") == "DB Browser for SQLite", ( + "a fresh app must have NO database open (recon T2), got title %r" % (w.name,)) + + names = [ + "Load all data and redraw plot", # Plot dock + "Upload", "Refresh", "Clone from Link", # Remote dock + "Import", "Export", "Set as NULL", "Print", "Apply", # Edit Database Cell dock + "Open in external application", "Open in application", + ] + expected = {n: False for n in names} + observed = enabled_map(ax, names) + + missing = [n for n, v in observed.items() if v is None] + assert not missing, "dock buttons absent from the AX tree: %r" % (missing,) + assert observed == expected, ( + "dock buttons must all be disabled with no database:\n observed=%r" % (observed,)) + assert prove_value(observed, expected) + + # the plot-save button carries a literal HTML AXTitle -> substring match, never equality + plot_save = [b for b in ax.find(role="button", max_results=90) + if "Save current plot" in (b.name or "")] + assert plot_save, "no button whose AXTitle contains 'Save current plot'" + assert enabled(ax, plot_save[0]) is False, ( + "'Save current plot' must be disabled while there is nothing plotted") + # none of these buttons were pressed (network / file-dialog / print side effects) diff --git a/macos/sqlitebrowser-sqlitebrowser/tests/test_ax_computation.py b/macos/sqlitebrowser-sqlitebrowser/tests/test_ax_computation.py new file mode 100644 index 0000000000000000000000000000000000000000..52f49087c3652346486ae83a28433881491bb57a --- /dev/null +++ b/macos/sqlitebrowser-sqlitebrowser/tests/test_ax_computation.py @@ -0,0 +1,612 @@ +"""AX COMPUTATION tests — DB Browser for SQLite (Qt6). + +Four computation engines, all driven purely through the AX API + System Events +keystrokes, every expected value taken verbatim from what was OBSERVED on the +reference app (recon.md ## COMPUTATION): + + 1. Execute SQL type SQL -> press `Execute SQL` -> results grid + message pane + 2. DDL preview `Edit table definition` / `Edit Index Schema` live CREATE preview + 3. Browse Data record counter `N - M of T` + "Filter in any column" + 4. Database Structure tree object counts `Tables (N) / Indices (N) / ...` + +A fresh app has NO database open, so every engine test first opens the in-memory +database (`File > New In-Memory Database`) and dismisses the auto-opened +`Edit table definition` modal with that window's OWN scoped `Cancel`. + +Deliberate omissions (recon says these reads are unreliable / non-deterministic): + * the SQL editor's own AXValue is truncated by QScintilla -> never asserted + * the `in Nms` / `Took 0ms` timing digits in the message pane -> never asserted +Never pressed: Write/Revert Changes, New/Open Database, any Save…, dock Close, +Delete Table…, or any native file-dialog button. +""" + +import json +import os +import re +import subprocess +import time + +import pytest +import rb_testgen_kit as kit + +RESULTS_DIR = os.environ.get("RESULTS_DIR", os.path.dirname(os.path.abspath(__file__))) +COUNTER_RE = re.compile(r"^\s*\d+\s*-\s*\d+\s+of\s+\d+\s*$") + + +def screenshot_assert(test_name, description, results_dir): + 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) + + +def _esc(times=1): + for _ in range(times): + subprocess.run(["osascript", "-e", + 'tell application "System Events" to key code 53'], + capture_output=True) + time.sleep(0.3) + + +def _keystroke(text): + subprocess.run(["osascript", "-e", + 'tell application "System Events" to keystroke ' + json.dumps(text)], + capture_output=True) + + +def open_menu(ax, top): + mb = ax.find(role="menu_bar_item", name=top, max_results=1) + if not mb: + return None + ax.action(mb[0].id, "AXPress") + time.sleep(0.6) + m = ax.find(role="menu", root_id=mb[0].id, max_results=1, max_depth=1) + return m[0] if m else None + + +def rb_reach_menu_item(ax, top, item_name): + m = open_menu(ax, top) + if m is None: + return False + for it in ax.find(role="menu_item", root_id=m.id, max_results=80, max_depth=1): + if (it.name or "") == item_name: + ok = ax.action(it.id, "AXPress") + time.sleep(1.4) + return bool(ok) + _esc(2) + return False + + +def find_window(ax, title_substr): + for w in ax.find(role="window", max_results=10, max_depth=1): + if title_substr.lower() in (w.name or "").lower(): + return w + return None + + +def rb_enter_inmemory_db(ax): + """File > New In-Memory Database, then dismiss the auto-opened table dialog.""" + rb_reach_menu_item(ax, "File", "New In-Memory Database") + w = find_window(ax, "Edit table definition") + if w is not None: + c = ax.find(role="button", name="Cancel", root_id=w.id, max_results=2) + if c: + ax.action(c[0].id, "AXPress") + time.sleep(1.0) + return find_window(ax, "Edit table definition") is None + + +def switch_tab(ax, name): + r = ax.find(role="radio", name=name, max_results=1) + if not r: + return False + ok = ax.action(r[0].id, "AXPress") + time.sleep(1.0) + return bool(ok) + + +def find_button(ax, name, root_id=None): + for b in ax.find(role="button", max_results=90, root_id=root_id): + if (b.name or "") == name: + return b + return None + + +def enabled(ax, el): + return bool(ax.get(el.id, ["AXEnabled"]).get("AXEnabled")) + + +def sql_editor(ax): + """The QScintilla SQL editor: the only settable text_area that is not the SQL log.""" + for t in ax.find(role="text_area", max_results=15): + if not ax.is_attribute_settable(t.id, "AXValue"): + continue + v = str(ax.get(t.id, ["AXValue"]).get("AXValue") or "") + if "PRAGMA" in v or "EXECUTING" in v: + continue + return t + return None + + +def run_sql(ax, sql): + """Type + execute SQL. set_value is IGNORED by QScintilla -> click + keystroke.""" + switch_tab(ax, "Execute SQL") + e = sql_editor(ax) + assert e is not None, "SQL editor not found" + ax.click_element_cg(e.id) + time.sleep(0.35) + subprocess.run(["osascript", "-e", + 'tell application "System Events" to keystroke "a" using command down'], + capture_output=True) + time.sleep(0.25) + _keystroke(sql) + time.sleep(0.5) + b = find_button(ax, "Execute SQL") + assert b is not None and enabled(ax, b), "Execute SQL button not enabled" + ax.action(b.id, "AXPress") + time.sleep(1.9) + + +def result_cells(ax): + """(column headers, cell values) of the SQL results grid. Skips the 'search result' decoy.""" + cols, cells = [], [] + for t in ax.find(role="table", max_results=10): + if (t.name or "") == "search result": + continue + ch = (ax.tree(max_depth=3, root_id=t.id).get("children") or []) + c = [x.get("name") for x in ch if x.get("role") == "column"] + v = [x.get("name") for x in ch if x.get("role") == "label"] + if c or v: + cols, cells = c, v + return cols, cells + + +def exec_msg(ax): + for t in ax.find(role="text_area", max_results=15): + v = str(ax.get(t.id, ["AXValue"]).get("AXValue") or "") + if v.startswith("Execution finished"): + return v + return "" + + +def record_counter(ax): + """Browse Data counter, e.g. '1 - 3 of 3'. MUST use the regex — a plain ' of ' test + also matches 'Identification of the cell currently in the editor'.""" + for l in ax.find(role="label", max_results=350): + v = str(ax.get(l.id, ["AXValue"]).get("AXValue") or "") + if COUNTER_RE.match(v): + return v.strip() + return None + + +def dialog_preview(ax, window): + """The read-only DDL preview text_area inside a dialog (its AXValue contains CREATE).""" + for t in ax.find(role="text_area", root_id=window.id, max_results=8): + v = str(ax.get(t.id, ["AXValue"]).get("AXValue") or "") + if "CREATE" in v: + return v + return None + + +def structure_group_names(ax): + out = [] + for g in ax.find(role="group", max_results=250): + n = g.name or "" + if n.startswith(("Tables (", "Indices (", "Views (", "Triggers (")): + out.append(n) + return sorted(set(out)) + + +# ── extra locators / navigation (semantic: role + visible AXTitle only) ───────── + +def wait_ready(ax, timeout=6.0): + """Settle after the per-test relaunch: wait until the app exposes a window.""" + deadline = time.time() + timeout + while time.time() < deadline: + if ax.find(role="window", max_results=1, max_depth=1): + return True + time.sleep(0.4) + return False + + +def dialog_button(ax, window, name): + """A button scoped INSIDE a dialog window (never a global 'Cancel'/'Add' match).""" + if window is None: + return None + for b in ax.find(role="button", root_id=window.id, max_results=40): + if (b.name or "") == name: + return b + return None + + +def dialog_field(ax, window, name): + if window is None: + return None + for t in ax.find(role="text_field", root_id=window.id, max_results=25): + if (t.name or "") == name: + return t + return None + + +def dialog_checkbox(ax, window, name): + if window is None: + return None + for c in ax.find(role="checkbox", root_id=window.id, max_results=25): + n = c.name or "" + if n == name or name in n: + return c + return None + + +def rb_enter_create_table_dialog(ax): + """SURFACE: Database Structure tab -> AXPress `Create Table` -> window + 'Edit table definition' (the second time this modal is crossed in a test).""" + switch_tab(ax, "Database Structure") + b = find_button(ax, "Create Table") + assert b is not None, "toolbar button 'Create Table' not found" + assert enabled(ax, b), "'Create Table' is disabled — no database open" + ax.action(b.id, "AXPress") + time.sleep(1.3) + return find_window(ax, "Edit table definition") + + +def rb_enter_create_index_dialog(ax): + """SURFACE: Database Structure tab -> AXPress `Create Index` -> window + 'Edit Index Schema' (needs a database AND at least one table).""" + switch_tab(ax, "Database Structure") + b = find_button(ax, "Create Index") + assert b is not None, "toolbar button 'Create Index' not found" + assert enabled(ax, b), "'Create Index' is disabled — no database open" + ax.action(b.id, "AXPress") + time.sleep(1.3) + return find_window(ax, "Edit Index Schema") + + +def rb_back_cancel(ax, window): + """Close a dialog with its OWN scoped Cancel button.""" + b = dialog_button(ax, window, "Cancel") + if b is None: + return False + ok = ax.action(b.id, "AXPress") + time.sleep(0.8) + return bool(ok) + + +def group_named(ax, name): + for g in ax.find(role="group", max_results=250): + if (g.name or "") == name: + return g + return None + + +# ── Engine 1 — Execute SQL ───────────────────────────────────────────────────── + +class TestExecuteSQLComputation: + """SQL evaluated by the app: results grid columns/cells + message pane.""" + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="results column 'answer' with cell '42' for SELECT 7*6") + def test_sql_multiplication(self, ax): + wait_ready(ax) + assert rb_enter_inmemory_db(ax), "in-memory database did not open" + run_sql(ax, "SELECT 7*6 AS answer;") + cols, cells = result_cells(ax) + screenshot_assert( + "computation_test_sql_multiplication", + "DB Browser for SQLite with the Execute SQL tab active. The SQL editor holds " + "'SELECT 7*6 AS answer;' and the results grid below it shows one column headed " + "'answer' containing the value 42 (7*6). The message pane under the grid reads " + "'Execution finished without errors. Result: 1 rows returned ...'.", + RESULTS_DIR) + assert cols == ["answer"], f"columns={cols!r} cells={cells!r}" + assert kit.rb_value(cells, "42"), f"expected cell '42', got cells={cells!r}" + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="results column 'total' with cell '5' for SELECT 2+3") + def test_sql_addition(self, ax): + wait_ready(ax) + assert rb_enter_inmemory_db(ax), "in-memory database did not open" + run_sql(ax, "SELECT 2+3 AS total;") + cols, cells = result_cells(ax) + assert cols == ["total"], f"columns={cols!r} cells={cells!r}" + assert kit.rb_value(cells, "5"), f"expected cell '5', got cells={cells!r}" + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="columns ['d','m'] and cells ['2','2'] for 10/4 and 10%4") + def test_sql_integer_division_and_modulo(self, ax): + wait_ready(ax) + assert rb_enter_inmemory_db(ax), "in-memory database did not open" + run_sql(ax, "SELECT 10/4 AS d, 10%4 AS m;") + cols, cells = result_cells(ax) + assert cols == ["d", "m"], f"columns={cols!r} cells={cells!r}" + assert cells == ["2", "2"], f"cells={cells!r}" + assert kit.rb_value(cells, ["2", "2"]), f"cells={cells!r}" + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="results column 'u' with cell 'DB4S' for upper('db4s')") + def test_sql_string_upper(self, ax): + wait_ready(ax) + assert rb_enter_inmemory_db(ax), "in-memory database did not open" + run_sql(ax, "SELECT upper('db4s') AS u;") + cols, cells = result_cells(ax) + assert cols == ["u"], f"columns={cols!r} cells={cells!r}" + assert kit.rb_value(cells, "DB4S"), f"expected cell 'DB4S', got cells={cells!r}" + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="results column 'n' with cell '5' for length('hello')") + def test_sql_string_length(self, ax): + wait_ready(ax) + assert rb_enter_inmemory_db(ax), "in-memory database did not open" + run_sql(ax, "SELECT length('hello') AS n;") + cols, cells = result_cells(ax) + assert cols == ["n"], f"columns={cols!r} cells={cells!r}" + assert kit.rb_value(cells, "5"), f"expected cell '5', got cells={cells!r}" + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="count(*)=3 and sum(a)=6 over 3 inserted rows -> cells ['3','6']") + def test_sql_aggregate_count_and_sum(self, ax): + wait_ready(ax) + assert rb_enter_inmemory_db(ax), "in-memory database did not open" + run_sql(ax, "CREATE TABLE t1(a INTEGER, b TEXT); " + "INSERT INTO t1 VALUES(1,'x'),(2,'y'),(3,'z'); " + "SELECT count(*) AS c, sum(a) AS s FROM t1;") + cols, cells = result_cells(ax) + assert cols == ["c", "s"], f"columns={cols!r} cells={cells!r}" + assert cells == ["3", "6"], f"cells={cells!r}" + assert kit.rb_value(cells, ["3", "6"]), f"cells={cells!r}" + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="message pane: 'Execution finished without errors.' and " + "'query executed successfully' with '3 rows affected'") + def test_sql_dml_reports_rows_affected(self, ax): + wait_ready(ax) + assert rb_enter_inmemory_db(ax), "in-memory database did not open" + run_sql(ax, "CREATE TABLE nums(n INTEGER, label TEXT); " + "INSERT INTO nums VALUES(10,'ten'),(20,'twenty'),(30,'thirty');") + msg = exec_msg(ax) + assert msg.startswith("Execution finished without errors."), f"message={msg!r}" + assert kit.rb_value(msg, "query executed successfully"), f"message={msg!r}" + assert kit.rb_value(msg, "3 rows affected"), f"message={msg!r}" + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="message pane 'Execution finished with errors.' + " + "'no such table: no_such_table_xyz' and an EMPTY results grid") + def test_sql_error_reports_no_such_table(self, ax): + wait_ready(ax) + assert rb_enter_inmemory_db(ax), "in-memory database did not open" + run_sql(ax, "SELECT * FROM no_such_table_xyz;") + msg = exec_msg(ax) + cols, cells = result_cells(ax) + screenshot_assert( + "computation_test_sql_error_no_such_table", + "DB Browser for SQLite, Execute SQL tab active. The editor holds " + "'SELECT * FROM no_such_table_xyz;'. The results grid is EMPTY (no columns, no " + "rows) and the message pane reports the SQLite error: 'Execution finished with " + "errors. Result: no such table: no_such_table_xyz'.", + RESULTS_DIR) + assert msg.startswith("Execution finished with errors."), f"message={msg!r}" + assert kit.rb_value(msg, "no such table: no_such_table_xyz"), f"message={msg!r}" + assert cols == [], f"results grid should be empty, got columns={cols!r} cells={cells!r}" + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="button 'Execute SQL' AXEnabled False->True once the in-memory " + "database exists") + def test_sql_execute_button_disabled_until_database_open(self, ax): + wait_ready(ax) + assert switch_tab(ax, "Execute SQL"), "could not activate the Execute SQL tab" + b = find_button(ax, "Execute SQL") + assert b is not None, "button 'Execute SQL' not found on the Execute SQL tab" + before = enabled(ax, b) + assert rb_enter_inmemory_db(ax), "in-memory database did not open" + b2 = find_button(ax, "Execute SQL") + assert b2 is not None, "button 'Execute SQL' vanished after opening the database" + after = enabled(ax, b2) + assert before is False, f"with no database open the button should be disabled, got {before!r}" + assert after is True, f"with the in-memory database open it should be enabled, got {after!r}" + assert kit.rb_flip(before, after), f"no enabled flip: {before!r} -> {after!r}" + + +# ── Engine 2 — DDL preview generators (dialog surfaces) ─────────────────────── + +class TestDDLPreviewComputation: + """The dialogs generate a live CREATE statement from the form contents.""" + + @pytest.mark.rb(depth=2, jump_kind="value", + expect='preview CREATE TABLE "" ( ); -> CREATE TABLE "people" ( );') + def test_create_table_preview_reflects_table_name(self, ax): + wait_ready(ax) + assert rb_enter_inmemory_db(ax), "in-memory database did not open" + w = rb_enter_create_table_dialog(ax) + assert w is not None, "window 'Edit table definition' did not open" + before = dialog_preview(ax, w) + assert before == 'CREATE TABLE "" (\n\n);', f"initial preview={before!r}" + field = dialog_field(ax, w, "Table") + assert field is not None, "text_field 'Table' not found in the dialog" + ax.set_value(field.id, "people") + time.sleep(0.7) + after = dialog_preview(ax, w) + screenshot_assert( + "computation_test_create_table_preview", + "The modal window 'Edit table definition' is open in front of the DB Browser for " + "SQLite main window. Its 'Table' name box contains 'people', the field grid " + "(headers Name, Type, NN, PK, AI, U, Default, Check, Collation, Foreign Key) is " + "still empty, and the read-only SQL preview box below shows " + 'CREATE TABLE "people" ( ); Fields / Index Constraints / Foreign Keys / Check ' + "Constraints tabs and OK / Cancel buttons are visible.", + RESULTS_DIR) + rb_back_cancel(ax, w) + assert after == 'CREATE TABLE "people" (\n\n);', f"preview after naming={after!r}" + assert kit.rb_value(after, 'CREATE TABLE "people" (\n\n);'), f"preview={after!r}" + + @pytest.mark.rb(depth=2, jump_kind="value", + expect='two Add presses give CREATE TABLE "people" ( "Field1" INTEGER, ' + '"Field2" INTEGER );') + def test_create_table_preview_grows_with_add_field(self, ax): + wait_ready(ax) + assert rb_enter_inmemory_db(ax), "in-memory database did not open" + w = rb_enter_create_table_dialog(ax) + assert w is not None, "window 'Edit table definition' did not open" + field = dialog_field(ax, w, "Table") + assert field is not None, "text_field 'Table' not found in the dialog" + ax.set_value(field.id, "people") + time.sleep(0.7) + add = dialog_button(ax, w, "Add") + assert add is not None, "button 'Add' not found in the dialog" + ax.action(add.id, "AXPress") + time.sleep(0.8) + one = dialog_preview(ax, w) + ax.action(add.id, "AXPress") + time.sleep(0.8) + two = dialog_preview(ax, w) + rb_back_cancel(ax, w) + assert one == 'CREATE TABLE "people" (\n\t"Field1"\tINTEGER\n);', \ + f"preview after 1 Add={one!r}" + assert two == 'CREATE TABLE "people" (\n\t"Field1"\tINTEGER,\n\t"Field2"\tINTEGER\n);', \ + f"preview after 2 Adds={two!r}" + assert kit.rb_value(two, '"Field2"\tINTEGER'), f"preview={two!r}" + + @pytest.mark.rb(depth=2, jump_kind="value", + expect='CREATE INDEX "" ON "t1" ( ); -> named idx_a -> ' + 'CREATE UNIQUE INDEX "idx_a" ON "t1" ( );') + def test_create_index_preview_name_and_unique(self, ax): + wait_ready(ax) + assert rb_enter_inmemory_db(ax), "in-memory database did not open" + run_sql(ax, "CREATE TABLE t1(a INTEGER, b TEXT);") + w = rb_enter_create_index_dialog(ax) + assert w is not None, "window 'Edit Index Schema' did not open" + opened = dialog_preview(ax, w) + assert opened is not None, "no CREATE preview text_area in 'Edit Index Schema'" + assert 'ON "t1"' in opened, f"initial index preview={opened!r}" + name = dialog_field(ax, w, "Name") + assert name is not None, "text_field 'Name' not found in 'Edit Index Schema'" + ax.set_value(name.id, "idx_a") + time.sleep(0.7) + named = dialog_preview(ax, w) + uniq = dialog_checkbox(ax, w, "Unique") + assert uniq is not None, "checkbox 'Unique' not found in 'Edit Index Schema'" + ax.action(uniq.id, "AXPress") + time.sleep(0.7) + unique = dialog_preview(ax, w) + rb_back_cancel(ax, w) + assert named == 'CREATE INDEX "idx_a" ON "t1" (\n\n);', f"preview after naming={named!r}" + assert unique == 'CREATE UNIQUE INDEX "idx_a" ON "t1" (\n\n);', \ + f"preview after Unique={unique!r}" + assert kit.rb_value(unique, 'CREATE UNIQUE INDEX "idx_a" ON "t1" (\n\n);'), \ + f"preview={unique!r}" + + +# ── Engine 3 — Browse Data record counter + filter ──────────────────────────── + +class TestBrowseDataCounterComputation: + """The Browse Data tab computes 'first - last of total' and re-computes it + from the filter expression.""" + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="Browse Data record counter reads '0 - 0 of 0' with no database open") + def test_record_counter_zero_without_database(self, ax): + wait_ready(ax) + assert switch_tab(ax, "Browse Data"), "could not activate the Browse Data tab" + counter = record_counter(ax) + assert counter is not None, "no 'N - M of T' record counter label on the Browse Data tab" + assert kit.rb_value(counter, "0 - 0 of 0"), f"counter={counter!r}" + assert counter == "0 - 0 of 0", f"counter={counter!r}" + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="counter '1 - 3 of 3' and Table: combobox 'nums' after inserting 3 rows") + def test_record_counter_matches_inserted_rows(self, ax): + wait_ready(ax) + assert rb_enter_inmemory_db(ax), "in-memory database did not open" + run_sql(ax, "CREATE TABLE nums(n INTEGER, label TEXT); " + "INSERT INTO nums VALUES(10,'ten'),(20,'twenty'),(30,'thirty');") + assert switch_tab(ax, "Browse Data"), "could not activate the Browse Data tab" + counter = record_counter(ax) + combo = ax.find(role="combobox", name="nums", max_results=1) + screenshot_assert( + "computation_test_record_counter_three_rows", + "DB Browser for SQLite with the Browse Data tab active. The 'Table:' dropdown " + "shows 'nums', the data grid has the columns _rowid_, n, label with the three " + "rows 10/ten, 20/twenty, 30/thirty, a 'Filter in any column' box sits under the " + "headers, and the record counter reads '1 - 3 of 3'.", + RESULTS_DIR) + assert counter is not None, "no 'N - M of T' record counter label found" + assert kit.rb_value(counter, "1 - 3 of 3"), f"counter={counter!r}" + assert counter == "1 - 3 of 3", f"counter={counter!r}" + assert combo, "no combobox titled 'nums' (the browsed table) found" + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="filter 'twenty' -> counter '1 - 1 of 1' and grid cells " + "['20','twenty'] with columns ['_rowid_','n','label']") + def test_filter_narrows_grid_and_counter(self, ax): + wait_ready(ax) + assert rb_enter_inmemory_db(ax), "in-memory database did not open" + run_sql(ax, "CREATE TABLE nums(n INTEGER, label TEXT); " + "INSERT INTO nums VALUES(10,'ten'),(20,'twenty'),(30,'thirty');") + assert switch_tab(ax, "Browse Data"), "could not activate the Browse Data tab" + flt = ax.find(role="text_field", name="Filter in any column", max_results=1) + assert flt, "text_field 'Filter in any column' not found on the Browse Data tab" + ax.set_value(flt[0].id, "twenty") + time.sleep(1.7) + counter = record_counter(ax) + cols, cells = result_cells(ax) + screenshot_assert( + "computation_test_filter_narrows_grid", + "DB Browser for SQLite, Browse Data tab active on table 'nums'. The filter box " + "under the column headers contains 'twenty', so the grid shows only ONE row " + "(20 / twenty) out of three, the record counter reads '1 - 1 of 1', and the " + "'Clear Filters' toolbar button is now enabled.", + RESULTS_DIR) + assert counter == "1 - 1 of 1", f"counter={counter!r}" + assert cols == ["_rowid_", "n", "label"], f"columns={cols!r}" + assert cells == ["20", "twenty"], f"cells={cells!r}" + assert kit.rb_value(cells, ["20", "twenty"]), f"cells={cells!r}" + + +# ── Engine 4 — Database Structure object counts ─────────────────────────────── + +class TestStructureCountComputation: + """The structure tree counts schema objects: Tables (N) / Indices (N) / ...""" + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="Tables (0)->Tables (1) with a tree node named 'nums' after " + "CREATE TABLE") + def test_structure_tree_object_counts_reflect_created_table(self, ax): + wait_ready(ax) + assert rb_enter_inmemory_db(ax), "in-memory database did not open" + assert switch_tab(ax, "Database Structure"), "could not activate Database Structure" + before_names = structure_group_names(ax) + assert "Tables (0)" in before_names, f"before={before_names!r}" + assert "Indices (0)" in before_names, f"before={before_names!r}" + assert "Views (0)" in before_names, f"before={before_names!r}" + assert "Triggers (0)" in before_names, f"before={before_names!r}" + run_sql(ax, "CREATE TABLE nums(n INTEGER, label TEXT);") + # re-activating the tab is what refreshes the structure tree + assert switch_tab(ax, "Database Structure"), "could not re-activate Database Structure" + after_names = structure_group_names(ax) + nums_node = group_named(ax, "nums") + screenshot_assert( + "computation_test_structure_counts", + "DB Browser for SQLite with the Database Structure tab active. The schema tree " + "now lists 'Tables (1)' expanded/containing an entry named 'nums', alongside " + "'Indices (0)', 'Views (0)' and 'Triggers (0)'; the Create Table / Create Index / " + "Modify Table buttons sit above the tree.", + RESULTS_DIR) + assert kit.rb_value(after_names, "Tables (1)"), f"after={after_names!r}" + assert "Tables (1)" in after_names, f"after={after_names!r}" + assert "Tables (0)" not in after_names, f"after={after_names!r}" + assert nums_node is not None, "no tree node named 'nums' after CREATE TABLE nums" + assert kit.rb_flip(before_names, after_names), \ + f"object counts did not change: {before_names!r} -> {after_names!r}" diff --git a/macos/sqlitebrowser-sqlitebrowser/tests/test_ax_menus.py b/macos/sqlitebrowser-sqlitebrowser/tests/test_ax_menus.py new file mode 100644 index 0000000000000000000000000000000000000000..5d6e1506b0a87163538ab0a1b7557939bcb32ddd --- /dev/null +++ b/macos/sqlitebrowser-sqlitebrowser/tests/test_ax_menus.py @@ -0,0 +1,889 @@ +"""AX MENU tests for DB Browser for SQLite (Qt6) — generated from recon.md ## MENUS. + +Every fact asserted here was OBSERVED on the reference app and recorded in recon.md +(`## MENUS`, `## AX_TREE`, `## STRUCTURE`, `## TEXT`, `## VISUAL`). + +Locator contract: menus are ALWAYS scoped + menu_bar_item -> find(role="menu", root_id=mbi.id, max_depth=1) + -> find(role="menu_item", root_id=menu.id, max_depth=1) +because a global find(role="menu_item") returns ~200 Apple-menu items. + +Destructive items are NEVER pressed: Quit, Close Database, Delete Table..., Compact +Database..., Load Extension..., Enter Full Screen, any Window Layout item, any Help item, +New Database..., Open Database..., Open Project..., any Save..., any Import/Export leaf +(they raise native file panels that hang the test). +""" + +import json +import os +import subprocess +import time + +import pytest +import rb_testgen_kit as kit + +RESULTS_DIR = os.environ.get("RESULTS_DIR", os.path.dirname(os.path.abspath(__file__))) + + +def screenshot_assert(test_name, description, results_dir): + 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) + + +def _esc(times=1): + for _ in range(times): + subprocess.run(["osascript", "-e", + 'tell application "System Events" to key code 53'], + capture_output=True) + time.sleep(0.3) + + +def open_menu(ax, top): + """Open a top-level app menu; returns its `menu` element or None.""" + mb = ax.find(role="menu_bar_item", name=top, max_results=1) + if not mb: + return None + ax.action(mb[0].id, "AXPress") + time.sleep(0.6) + m = ax.find(role="menu", root_id=mb[0].id, max_results=1, max_depth=1) + return m[0] if m else None + + +def items_of(ax, menu): + return ax.find(role="menu_item", root_id=menu.id, max_results=80, max_depth=1) + + +def item_named(ax, menu, name): + for it in items_of(ax, menu): + if (it.name or "") == name: + return it + return None + + +def submenu_of(ax, item): + m = ax.find(role="menu", root_id=item.id, max_results=1, max_depth=1) + return m[0] if m else None + + +def item_attrs(ax, it): + return ax.get(it.id, ["AXEnabled", "AXMenuItemMarkChar", + "AXMenuItemCmdChar", "AXMenuItemCmdModifiers"]) + + +def rb_reach_menu_item(ax, top, item_name): + """Open `top` and AXPress the menu item named exactly `item_name`.""" + m = open_menu(ax, top) + if m is None: + return False + it = item_named(ax, m, item_name) + if it is None: + _esc(2) + return False + ok = ax.action(it.id, "AXPress") + time.sleep(1.4) + return bool(ok) + + +def find_window(ax, title_substr): + for w in ax.find(role="window", max_results=10, max_depth=1): + if title_substr.lower() in (w.name or "").lower(): + return w + return None + + +def untitled_dialog(ax): + """The Qt message-box window (AXTitle == '').""" + for w in ax.find(role="window", max_results=10, max_depth=1): + if (w.name or "") == "": + return w + return None + + +def close_dialog(ax, window, button_name="Cancel"): + if window is None: + return False + b = ax.find(role="button", name=button_name, root_id=window.id, max_results=2) + if b: + ax.action(b[0].id, "AXPress") + time.sleep(1.0) + return True + return False + + +def rb_enter_inmemory_db(ax): + """File > New In-Memory Database, then dismiss the auto-opened table dialog.""" + rb_reach_menu_item(ax, "File", "New In-Memory Database") + w = find_window(ax, "Edit table definition") + if w is not None: + close_dialog(ax, w, "Cancel") + return find_window(ax, "Edit table definition") is None + + +def pref_item(ax, menu): + """The app-menu Preferences/Settings item — AXTitle is UNSTABLE across runs.""" + for it in items_of(ax, menu): + n = (it.name or "").lower() + if "services" in n: + continue + if "prefer" in n or "etting" in n: + return it + return None + + +def result_cells(ax): + cols, cells = [], [] + for t in ax.find(role="table", max_results=10): + if (t.name or "") == "search result": + continue + ch = (ax.tree(max_depth=3, root_id=t.id).get("children") or []) + c = [x.get("name") for x in ch if x.get("role") == "column"] + v = [x.get("name") for x in ch if x.get("role") == "label"] + if c or v: + cols, cells = c, v + return cols, cells + + +# ── local additions (semantic locators, no framework internals) ────────────── + +APP_MENU = "DB Browser for SQLite" + +TOP_MENUS = [APP_MENU, "File", "Edit", "View", "Tools", "Help"] + +# recon ## MENUS — minimum app-authored named items per menu (macOS may ADD more) +MIN_NAMED = {APP_MENU: 6, "File": 18, "Edit": 4, "View": 13, "Tools": 7, "Help": 6} + +FILE_ITEMS = [ + "New Database...", "New In-Memory Database", "Open Database...", + "Open Database Read Only...", "Attach Database...", "Recent Files", + "Save Database As...", "Close Database", "Write Changes", "Revert Changes", + "Undo", "Import", "Export", "Open Project...", "Save Project", + "Save Project As...", "Close Project", "Save All", +] + +VIEW_TOGGLES = [ + "SQL Log", "Plot", "DB Schema", "Edit Database Cell", "Remote", + "DB Toolbar", "Extra DB Toolbar", "Project Toolbar", + "Database Structure", "Browse Data", "Edit Pragmas", "Execute SQL", +] + +TOOLS_ITEMS = [ + "Compact Database...", "Load Extension...", "Integrity Check", + "Quick Integrity Check", "Foreign-Key Check", "Optimize", "Show Row Counts", +] + +HELP_ITEMS = [ + "What's This?", "Website", "Wiki", "Bug Report...", + "Feature Request...", "Donate on Patreon...", +] + +FILE_IMPORT_ITEMS = ["Database from SQL file...", "Table from CSV file...", + "Table from CSV data in Clipboard..."] +FILE_EXPORT_ITEMS = ["Database to SQL file...", "Table(s) as CSV file...", + "Table to JSON..."] +FILE_RECENT_ITEMS = ["Automatically load the last opened DB file at startup", + "Clear List"] +WINDOW_LAYOUT_ITEMS = ["Reset Window Layout", "Simplify Window Layout", + "Dock Windows at Bottom", "Dock Windows at Left Side", + "Dock Windows at Top"] + +PREFS_TABS = ["General", "Database", "Data Browser", "SQL", "Extensions", "Remote"] + +TABLE_PREVIEW_FRESH = 'CREATE TABLE "" (\n\n);' +INTEGRITY_CONFIRM_TEXT = ( + "This action will open a new SQL tab for running:\n" + "PRAGMA integrity_check;\n" + "Press Help for opening the corresponding SQLite reference page." +) +ABOUT_DESCRIPTION = ("DB Browser for SQLite is an open source, freeware visual tool " + "used to create, design and edit SQLite") + + +def _norm(s): + """Compare menu labels SEMANTICALLY: the unicode ellipsis and '...' are the same + label; leading/trailing whitespace is irrelevant.""" + return str(s or "").replace("…", "...").strip() + + +def named_items(ax, menu): + """Normalised names of the menu's non-separator items (separators have name '').""" + return [_norm(it.name) for it in items_of(ax, menu) if _norm(it.name)] + + +def named_submenu_items(ax, item): + sub = submenu_of(ax, item) + if sub is None: + return None + return [_norm(i.name) for i in items_of(ax, sub) if _norm(i.name)] + + +def item_by_label(ax, menu, label): + """Locate a menu item by its VISIBLE label (ellipsis-tolerant).""" + want = _norm(label) + for it in items_of(ax, menu): + if _norm(it.name) == want: + return it + return None + + +def item_by_prefix(ax, menu, prefix): + p = _norm(prefix).lower() + for it in items_of(ax, menu): + if _norm(it.name).lower().startswith(p): + return it + return None + + +def enabled_map(ax, menu, labels): + """{label: bool AXEnabled} — value is None when the item is absent.""" + present = {} + for it in items_of(ax, menu): + n = _norm(it.name) + if n and n not in present: + present[n] = it + out = {} + for lb in labels: + it = present.get(_norm(lb)) + out[lb] = None if it is None else bool(item_attrs(ax, it).get("AXEnabled")) + return out + + +def shortcut_of(ax, menu, label): + """(AXMenuItemCmdChar, AXMenuItemCmdModifiers) of a menu item, or (None, None).""" + it = item_by_label(ax, menu, label) + if it is None: + return (None, None) + a = item_attrs(ax, it) + ch = a.get("AXMenuItemCmdChar") + md = a.get("AXMenuItemCmdModifiers") + ch = None if ch is None else str(ch) + try: + md = None if md is None else int(md) + except Exception: + md = None + return (ch, md) + + +def rb_enter_main_window(ax): + """Reveal the app's UI before any window-dependent check. The reference is a plain + windowed app (recon REVEAL_STEPS), but a recreation may need a reveal path — + ensure_ui_visible() tries them all.""" + try: + ax.ensure_ui_visible() + except Exception: + pass + return find_window(ax, "DB Browser for SQLite") + + +def main_window_title(ax): + for w in ax.find(role="window", max_results=10, max_depth=1): + n = str(w.name or "") + if n.startswith("DB Browser for SQLite"): + return n + return "" + + +def label_texts(ax, window, limit=30): + """AXValue (and AXTitle) of every label under a window — a recreation may carry the + text in either attribute.""" + out = [] + if window is None: + return out + for lb in ax.find(role="label", root_id=window.id, max_results=limit): + v = ax.get(lb.id, ["AXValue"]).get("AXValue") + if v is not None: + out.append(str(v)) + n = str(lb.name or "") + if n: + out.append(n) + return out + + +def button_names(ax, window, limit=15): + if window is None: + return [] + return [str(b.name or "") + for b in ax.find(role="button", root_id=window.id, max_results=limit)] + + +def text_area_containing(ax, window, needle): + if window is None: + return "" + for t in ax.find(role="text_area", root_id=window.id, max_results=8): + v = ax.get(t.id, ["AXValue"]).get("AXValue") + s = "" if v is None else str(v) + if needle in s: + return s + return "" + + +def combobox_options(ax, window): + opts = [] + if window is None: + return opts + for c in ax.find(role="combobox", root_id=window.id, max_results=6): + opts.append(str(c.name or "")) + for lb in ax.find(role="label", root_id=c.id, max_results=40): + opts.append(str(lb.name or "")) + return [o for o in opts if o] + + +def tabbar_group(ax, root_id, expected_radios): + """The tab bar is the `group` whose direct radio children are exactly + `expected_radios`; its AXTitle equals the SELECTED tab (recon ST1/ST5).""" + groups = ax.find(role="group", root_id=root_id, max_results=40) + for depth in (1, 2): + for g in groups: + kids = [_norm(k.name) for k in + ax.find(role="radio", root_id=g.id, max_results=12, max_depth=depth)] + if kids == [_norm(x) for x in expected_radios]: + return g + return None + + +def group_title(ax, group): + if group is None: + return None + return str(ax.get(group.id, ["AXTitle"]).get("AXTitle") or "") + + +def rb_reach_about_dialog(ax): + """app menu -> 'About DB Browser for SQLite' (window|About DB Browser for SQLite).""" + m = open_menu(ax, APP_MENU) + if m is None: + return False + it = item_by_prefix(ax, m, "About") + if it is None: + _esc(2) + return False + ok = ax.action(it.id, "AXPress") + time.sleep(1.5) + return bool(ok) + + +def rb_reach_preferences(ax): + """app menu -> Preferences…/Settings… (window|Preferences).""" + m = open_menu(ax, APP_MENU) + if m is None: + return False + it = pref_item(ax, m) + if it is None: + _esc(2) + return False + ok = ax.action(it.id, "AXPress") + time.sleep(1.6) + return bool(ok) + + +def rb_enter_table_t1(ax): + """Edit ▸ Create Table… -> name it t1, Add one field, OK. Returns True when the + dialog closed (table created). Needs a DB already open.""" + rb_reach_menu_item(ax, "Edit", "Create Table...") + dlg = find_window(ax, "Edit table definition") + if dlg is None: + return False + tf = ax.find(role="text_field", name="Table", root_id=dlg.id, max_results=3) + if not tf: + tf = ax.find(role="text_field", root_id=dlg.id, max_results=3) + if tf: + ax.set_value(tf[0].id, "t1") + time.sleep(0.6) + add = ax.find(role="button", name="Add", root_id=dlg.id, max_results=3) + if add: + ax.action(add[0].id, "AXPress") + time.sleep(0.6) + ok = ax.find(role="button", name="OK", root_id=dlg.id, max_results=3) + if ok and bool(ax.get(ok[0].id, ["AXEnabled"]).get("AXEnabled")): + ax.action(ok[0].id, "AXPress") + time.sleep(1.2) + if find_window(ax, "Edit table definition") is not None: + close_dialog(ax, find_window(ax, "Edit table definition"), "Cancel") + return False + return True + + +# ── A) structure of every menu in recon ## MENUS ───────────────────────────── + +class TestMenuStructure: + + @pytest.mark.rb(depth=1, jump_kind="none", + expect="menu bar exposes the 6 app menus; every menu has >=1 item " + "and File/View/app own submenus") + def test_menu_bar_top_level_menus_and_item_counts(self, ax_with_reset): + ax = ax_with_reset + tops = [_norm(m.name) for m in + ax.find(role="menu_bar_item", max_results=15, max_depth=3)] + totals, named_totals, submenus = {}, {}, {} + for top in TOP_MENUS: + menu = open_menu(ax, top) + if menu is None: + totals[top], named_totals[top], submenus[top] = 0, 0, 0 + continue + items = items_of(ax, menu) + totals[top] = len(items) + named_totals[top] = len([i for i in items if _norm(i.name)]) + submenus[top] = len([i for i in items if submenu_of(ax, i) is not None]) + _esc(2) + _esc(2) + + assert set(TOP_MENUS).issubset(set(tops)), \ + f"menu bar is missing app menus: got {tops}" + for top in TOP_MENUS: + assert totals[top] >= 1, f"menu {top!r} has no children at all" + assert named_totals[top] >= MIN_NAMED[top], ( + f"menu {top!r}: {named_totals[top]} named items, " + f"expected >= {MIN_NAMED[top]}") + # separators are menu_items with an empty name -> total >= named + assert all(totals[t] >= named_totals[t] for t in TOP_MENUS) + assert submenus["File"] >= 3, ( + f"File must own the Recent Files/Import/Export submenus, " + f"found {submenus['File']}") + assert submenus["View"] >= 1, "View must own the Window Layout submenu" + assert submenus[APP_MENU] >= 1, "app menu must own the Services submenu" + assert sum(named_totals.values()) >= 50, ( + f"total named menu items {sum(named_totals.values())} " + f"(recon: 62 across the 6 app menus)") + + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="all 12 View toggles carry AXMenuItemMarkChar '/' (checkmark) " + "on a fresh app, plus Window Layout + Enter Full Screen") + def test_view_menu_full_item_list_and_checkmarks(self, ax_with_reset): + ax = ax_with_reset + menu = open_menu(ax, "View") + assert menu is not None, "View menu did not open" + names = named_items(ax, menu) + marks = [] + for lb in VIEW_TOGGLES: + it = item_by_label(ax, menu, lb) + marks.append(None if it is None + else item_attrs(ax, it).get("AXMenuItemMarkChar")) + screenshot_assert( + "menus_view_menu_checkmarks", + "The View dropdown lists SQL Log, Plot, DB Schema, Edit Database Cell, " + "Remote, DB Toolbar, Extra DB Toolbar, Project Toolbar, Database Structure, " + "Browse Data, Edit Pragmas, Execute SQL — each with a checkmark — plus a " + "'Window Layout' submenu and 'Enter Full Screen'.", + RESULTS_DIR) + _esc(2) + + missing = [n for n in VIEW_TOGGLES if _norm(n) not in names] + assert not missing, f"View menu missing toggles {missing}; got {names}" + assert _norm("Window Layout") in names, f"View lacks Window Layout: {names}" + assert _norm("Enter Full Screen") in names, \ + f"View lacks Enter Full Screen: {names}" + marks = [None if m is None else str(m) for m in marks] + assert kit.rb_value(sorted({str(m) for m in marks}), ["✓"]), ( + f"every View toggle must be CHECKED on a fresh app, marks={marks}") + assert marks == ["✓"] * 12, f"marks={marks}" + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="all 7 Tools items exist and report AXEnabled False with no " + "database open") + def test_tools_menu_all_disabled_without_database(self, ax_with_reset): + ax = ax_with_reset + menu = open_menu(ax, "Tools") + assert menu is not None, "Tools menu did not open" + names = named_items(ax, menu) + state = enabled_map(ax, menu, TOOLS_ITEMS) + _esc(2) + + missing = [n for n in TOOLS_ITEMS if _norm(n) not in names] + assert not missing, f"Tools menu missing {missing}; got {names}" + vals = [state[n] for n in TOOLS_ITEMS] + assert kit.rb_value(sorted({str(v) for v in vals}), ["False"]), ( + f"with NO database every Tools item must be DISABLED, got " + f"{dict(zip(TOOLS_ITEMS, vals))}") + assert vals == [False] * 7, dict(zip(TOOLS_ITEMS, vals)) + + @pytest.mark.rb(depth=1, jump_kind="none", + expect="Help menu lists the 6 recorded items (never pressed — they " + "open a browser)") + def test_help_menu_items(self, ax_with_reset): + ax = ax_with_reset + menu = open_menu(ax, "Help") + assert menu is not None, "Help menu did not open" + names = named_items(ax, menu) + _esc(2) + + missing = [n for n in HELP_ITEMS if _norm(n) not in names] + assert not missing, f"Help menu missing {missing}; got {names}" + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="app menu: About item, Preferences/Settings with cmd ',', " + "Quit cmd 'Q', Hide cmd 'H' mods 0, Hide Others 'H' mods 2") + def test_app_menu_items_and_shortcuts(self, ax_with_reset): + ax = ax_with_reset + menu = open_menu(ax, APP_MENU) + assert menu is not None, "app menu did not open" + names = named_items(ax, menu) + about = item_by_prefix(ax, menu, "About DB Browser for SQLite") + about_actions = list(about.actions) if about is not None else [] + prefs = pref_item(ax, menu) + prefs_attrs = {} if prefs is None else item_attrs(ax, prefs) + prefs_actions = list(prefs.actions) if prefs is not None else [] + quit_sc = shortcut_of(ax, menu, "Quit DB Browser for SQLite") + hide_sc = shortcut_of(ax, menu, "Hide DB Browser for SQLite") + hide_others_sc = shortcut_of(ax, menu, "Hide Others") + _esc(2) + + assert about is not None, f"no 'About DB Browser for SQLite' item: {names}" + assert "AXPress" in about_actions, \ + f"About item has no action interface: {about_actions}" + assert prefs is not None, f"no Preferences/Settings item: {names}" + assert "AXPress" in prefs_actions, \ + f"Preferences item has no action interface: {prefs_actions}" + prefs_cmd = prefs_attrs.get("AXMenuItemCmdChar") + observed = [None if prefs_cmd is None else str(prefs_cmd), + quit_sc[0], hide_sc[0], hide_others_sc[0]] + assert kit.rb_value(observed, [",", "Q", "H", "H"]), ( + f"app-menu cmd chars {observed} != [',', 'Q', 'H', 'H']") + assert quit_sc[1] == 0, f"Quit modifiers {quit_sc[1]} (expected 0 = plain cmd)" + assert hide_sc[1] == 0, f"Hide modifiers {hide_sc[1]} (expected 0)" + assert hide_others_sc[1] == 2, \ + f"Hide Others modifiers {hide_others_sc[1]} (expected 2 = alt+cmd)" + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="New Database (N,0), Open Database (O,0), Open Database Read " + "Only (O,1), Close Project (W,1), Save All (S,1), Write " + "Changes cmd 'S'") + def test_file_menu_keyboard_shortcuts(self, ax_with_reset): + ax = ax_with_reset + menu = open_menu(ax, "File") + assert menu is not None, "File menu did not open" + pairs = [shortcut_of(ax, menu, lb) for lb in + ["New Database...", "Open Database...", "Open Database Read Only...", + "Close Project", "Save All"]] + write_changes = shortcut_of(ax, menu, "Write Changes") + _esc(2) + + expected = [("N", 0), ("O", 0), ("O", 1), ("W", 1), ("S", 1)] + assert kit.rb_value(pairs, expected), ( + f"File-menu shortcuts {pairs} != {expected}") + assert write_changes[0] == "S", \ + f"Write Changes cmd char {write_changes[0]!r} (expected 'S')" + + + + +# ── B) safe-item activation ────────────────────────────────────────────────── + +class TestMenuItemActivation: + + @pytest.mark.rb(depth=1, jump_kind="reach", + expect="modal window 'Edit table definition' appears with the " + "preview CREATE TABLE \"\" (\\n\\n);") + def test_new_inmemory_database_opens_table_dialog(self, ax_with_reset): + ax = ax_with_reset + rb_enter_main_window(ax) + before = kit.rb_showing(ax) + pressed = rb_reach_menu_item(ax, "File", "New In-Memory Database") + after = kit.rb_showing(ax) + assert pressed, "could not press File > New In-Memory Database" + dlg = find_window(ax, "Edit table definition") + preview = text_area_containing(ax, dlg, "CREATE") + screenshot_assert( + "menus_new_inmemory_table_dialog", + "A modal window titled 'Edit table definition' is in front of the main " + "window: a 'Table' name field, an 'Advanced' checkbox, a field grid headed " + "Name, Type, NN, PK, AI, U, Default, Check, Collation, Foreign Key, " + "Add/Remove/move buttons, a read-only SQL box showing CREATE TABLE \"\" ( ); " + "tabs Fields / Index Constraints / Foreign Keys / Check Constraints, and " + "OK / Cancel buttons.", + RESULTS_DIR) + closed = close_dialog(ax, dlg, "Cancel") + gone = find_window(ax, "Edit table definition") is None + _esc(2) + + assert kit.rb_reach(before, after, target="window|Edit table definition"), ( + "File > New In-Memory Database did not open the 'Edit table definition' " + "window") + assert dlg is not None + assert preview == TABLE_PREVIEW_FRESH, ( + f"fresh CREATE-TABLE preview {preview!r} != {TABLE_PREVIEW_FRESH!r}") + assert closed, "the dialog exposes no scoped Cancel button" + assert gone, "'Edit table definition' is still open after Cancel" + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="main window title 'DB Browser for SQLite' -> " + "'DB Browser for SQLite - In-Memory database'") + def test_new_inmemory_database_changes_window_title(self, ax_with_reset): + ax = ax_with_reset + rb_enter_main_window(ax) + before_title = main_window_title(ax) + opened = rb_enter_inmemory_db(ax) + after_title = main_window_title(ax) + _esc(2) + + assert before_title == "DB Browser for SQLite", ( + f"fresh main window title {before_title!r}") + assert opened, "the auto-opened 'Edit table definition' dialog did not close" + assert kit.rb_flip(before_title, after_title), ( + f"window title did not change: {before_title!r} -> {after_title!r}") + assert kit.rb_value(after_title, "In-Memory database"), ( + f"title after opening the in-memory DB = {after_title!r}") + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="Edit > Create Table.../Create Index... AXEnabled False->True " + "once a database is open; Modify/Delete Table stay False") + def test_edit_menu_items_enable_after_database_opened(self, ax_with_reset): + ax = ax_with_reset + rb_enter_main_window(ax) + edit_labels = ["Create Table...", "Create Index...", + "Modify Table...", "Delete Table..."] + menu = open_menu(ax, "Edit") + assert menu is not None, "Edit menu did not open" + names = named_items(ax, menu) + s0 = enabled_map(ax, menu, edit_labels) + _esc(2) + + rb_enter_inmemory_db(ax) + + menu2 = open_menu(ax, "Edit") + assert menu2 is not None, "Edit menu did not open with a database" + s1 = enabled_map(ax, menu2, edit_labels) + _esc(2) + + missing = [n for n in edit_labels if _norm(n) not in names] + assert not missing, f"Edit menu missing {missing}; got {names}" + before_pair = (s0["Create Table..."], s0["Create Index..."]) + after_pair = (s1["Create Table..."], s1["Create Index..."]) + assert kit.rb_flip(before_pair, after_pair), ( + f"Create Table/Create Index did not change enabled state: " + f"{before_pair} -> {after_pair}") + assert before_pair == (False, False), f"no DB: {before_pair}" + assert after_pair == (True, True), f"DB open: {after_pair}" + assert (s1["Modify Table..."], s1["Delete Table..."]) == (False, False), ( + f"Modify/Delete Table must stay disabled without a selected table, got " + f"{(s1['Modify Table...'], s1['Delete Table...'])}") + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="all 7 Tools items AXEnabled False->True after File > New " + "In-Memory Database") + def test_tools_menu_items_enable_after_database_opened(self, ax_with_reset): + ax = ax_with_reset + rb_enter_main_window(ax) + menu = open_menu(ax, "Tools") + assert menu is not None, "Tools menu did not open" + s0 = enabled_map(ax, menu, TOOLS_ITEMS) + _esc(2) + + rb_enter_inmemory_db(ax) + + menu2 = open_menu(ax, "Tools") + assert menu2 is not None, "Tools menu did not open with a database" + s1 = enabled_map(ax, menu2, TOOLS_ITEMS) + _esc(2) + + before_vals = [s0[n] for n in TOOLS_ITEMS] + after_vals = [s1[n] for n in TOOLS_ITEMS] + assert kit.rb_flip(before_vals, after_vals), ( + f"Tools items did not change enabled state: {before_vals} -> {after_vals}") + assert before_vals == [False] * 7, dict(zip(TOOLS_ITEMS, before_vals)) + assert after_vals == [True] * 7, dict(zip(TOOLS_ITEMS, after_vals)) + + +# ── depth >= 2 chains reached through the menus ────────────────────────────── + +class TestMenuDepthChains: + + @pytest.mark.rb(depth=2, jump_kind="reach", + expect="window 'Edit Index Schema' with the table list holding t1 " + "and the preview CREATE INDEX \"\" ON \"t1\" (...)") + def test_edit_create_index_opens_index_dialog(self, ax_with_reset): + ax = ax_with_reset + rb_enter_main_window(ax) + assert rb_enter_inmemory_db(ax), "could not open the in-memory database" + table_created = rb_enter_table_t1(ax) + + before = kit.rb_showing(ax) + pressed = rb_reach_menu_item(ax, "Edit", "Create Index...") + after = kit.rb_showing(ax) + assert pressed, "could not press Edit > Create Index..." + idx = find_window(ax, "Edit Index Schema") + options = combobox_options(ax, idx) + preview = text_area_containing(ax, idx, "CREATE") + close_dialog(ax, idx, "Cancel") + _esc(2) + + assert kit.rb_reach(before, after, target="window|Edit Index Schema"), ( + "Edit > Create Index... did not open the 'Edit Index Schema' window") + assert idx is not None + if table_created: + assert any("t1" == o or "t1" in o for o in options), ( + f"the index dialog's table list does not offer t1: {options}") + assert 'ON "t1"' in preview, ( + f"CREATE-INDEX preview {preview!r} does not target t1") + else: + assert "CREATE" in preview or preview == "", ( + f"unexpected index preview {preview!r}") + + @pytest.mark.rb(depth=2, jump_kind="reach", + expect="untitled confirm window with the exact text 'PRAGMA " + "integrity_check;' block and OK / Cancel / Help buttons") + def test_tools_integrity_check_confirmation_dialog(self, ax_with_reset): + ax = ax_with_reset + rb_enter_main_window(ax) + assert rb_enter_inmemory_db(ax), "could not open the in-memory database" + + before = kit.rb_showing(ax) + pressed = rb_reach_menu_item(ax, "Tools", "Integrity Check") + after = kit.rb_showing(ax) + assert pressed, "could not press Tools > Integrity Check" + dlg = untitled_dialog(ax) + btns = button_names(ax, dlg) + texts = label_texts(ax, dlg) + screenshot_assert( + "menus_integrity_check_confirm", + "A modal alert in front of the DB Browser for SQLite window with a warning " + "icon and the text 'This action will open a new SQL tab for running: PRAGMA " + "integrity_check; Press Help for opening the corresponding SQLite reference " + "page.' plus OK / Cancel / Help buttons.", + RESULTS_DIR) + close_dialog(ax, dlg, "Cancel") + _esc(2) + + assert kit.rb_reach(before, after, target="PRAGMA integrity_check"), ( + "Tools > Integrity Check did not raise the PRAGMA integrity_check confirm " + "dialog") + assert dlg is not None, "no untitled Qt message-box window appeared" + assert {"OK", "Cancel", "Help"}.issubset(set(btns)), \ + f"confirm dialog buttons {btns}" + assert any(t == INTEGRITY_CONFIRM_TEXT for t in texts), ( + f"confirm text not found verbatim; observed {texts}") + + @pytest.mark.rb(depth=3, jump_kind="value", + expect="pressing OK runs PRAGMA integrity_check; in a new SQL tab " + "'Integrity Check*' whose results column 'integrity_check' " + "holds the cell 'ok'") + def test_tools_integrity_check_runs_and_reports_ok(self, ax_with_reset): + ax = ax_with_reset + rb_enter_main_window(ax) + assert rb_enter_inmemory_db(ax), "could not open the in-memory database" + assert rb_reach_menu_item(ax, "Tools", "Integrity Check"), \ + "could not press Tools > Integrity Check" + dlg = untitled_dialog(ax) + assert dlg is not None, "no confirm dialog for Integrity Check" + ok = ax.find(role="button", name="OK", root_id=dlg.id, max_results=2) + assert ok, f"confirm dialog has no OK button: {button_names(ax, dlg)}" + ax.action(ok[0].id, "AXPress") + time.sleep(2.6) + + cols, cells = result_cells(ax) + radios = [str(r.name or "") for r in ax.find(role="radio", max_results=40)] + screenshot_assert( + "menus_integrity_check_result", + "The Execute SQL tab is active with TWO sub-tabs ('SQL 1' and 'Integrity " + "Check*'), the editor holds PRAGMA integrity_check; and a results grid whose " + "single column 'integrity_check' contains the value ok.", + RESULTS_DIR) + _esc(2) + + assert cols == ["integrity_check"], f"results columns {cols}" + assert kit.rb_value(cells, "ok"), f"results cells {cells} (expected 'ok')" + assert any(n.startswith("Integrity Check") for n in radios), ( + f"no 'Integrity Check*' SQL sub-tab was created: {radios}") + + +class TestAppMenuSurfaces: + + @pytest.mark.rb(depth=1, jump_kind="reach", + expect="window 'About DB Browser for SQLite' with the freeware " + "description sentence and a 'DB Browser for SQLite Version' " + "line") + def test_app_menu_about_dialog(self, ax_with_reset): + ax = ax_with_reset + rb_enter_main_window(ax) + before = kit.rb_showing(ax) + pressed = rb_reach_about_dialog(ax) + after = kit.rb_showing(ax) + assert pressed, "could not press the app menu's About item" + about = find_window(ax, "About DB Browser for SQLite") + texts = label_texts(ax, about) + btns = button_names(ax, about) + screenshot_assert( + "menus_about_dialog", + "A small window titled 'About DB Browser for SQLite' showing the app logo " + "image, a version line beginning 'DB Browser for SQLite Version', the " + "sentence 'DB Browser for SQLite is an open source, freeware visual tool " + "used to create, design and edit SQLite', and a Close button.", + RESULTS_DIR) + closed = close_dialog(ax, about, "Close") + _esc(2) + + assert kit.rb_reach(before, after, + target="window|About DB Browser for SQLite"), ( + "the About item did not open the About window") + assert about is not None + assert any(ABOUT_DESCRIPTION in t for t in texts), ( + f"About description sentence missing; observed {texts}") + # NEVER assert the version NUMBER — it is build specific. + assert any("DB Browser for SQLite Version" in t for t in texts), ( + f"About window has no version line; observed {texts}") + assert "Close" in btns, f"About window buttons {btns}" + assert closed, "the About window exposes no scoped Close button" + + @pytest.mark.rb(depth=2, jump_kind="reach", + expect="Preferences > Database tab: 'Prefetch block size' appears " + "and 'Max Recent Files' (General tab) disappears; tab-bar " + "group AXTitle 'General' -> 'Database'") + def test_preferences_window_tab_navigation(self, ax_with_reset): + ax = ax_with_reset + rb_enter_main_window(ax) + opened = rb_reach_preferences(ax) + prefs = find_window(ax, "Preferences") + assert opened and prefs is not None, \ + "app menu > Preferences.../Settings... did not open the Preferences window" + tabs = [_norm(r.name) for r in + ax.find(role="radio", root_id=prefs.id, max_results=20)] + bar = tabbar_group(ax, prefs.id, PREFS_TABS) + title_general = group_title(ax, bar) + screenshot_assert( + "menus_preferences_general", + "A separate 'Preferences' window with a tab strip General, Database, Data " + "Browser, SQL, Extensions, Remote (General selected), a Language dropdown " + "reading 'English (United States) [System Language]', Font size 13, Max " + "Recent Files 5, toolbar-style dropdowns, and Save / Cancel / Restore " + "Defaults buttons.", + RESULTS_DIR) + + db_tab = ax.find(role="radio", name="Database", root_id=prefs.id, max_results=2) + assert db_tab, f"Preferences has no 'Database' tab; radios {tabs}" + before = kit.rb_showing(ax) + ax.action(db_tab[0].id, "AXPress") + time.sleep(1.1) + after = kit.rb_showing(ax) + title_database = group_title(ax, bar) + + close_dialog(ax, prefs, "Cancel") + remaining = len(ax.find(role="window", max_results=10, max_depth=1)) + _esc(2) + + assert [t for t in tabs if t in PREFS_TABS][:6] == PREFS_TABS, \ + f"Preferences tab radios {tabs}" + assert title_general == "General", ( + f"Preferences opens on the General tab; tab-bar AXTitle {title_general!r}") + assert kit.rb_reach(before, after, target="Prefetch block size", + source="Max Recent Files"), ( + "pressing the Database tab did not swap the General page for the Database " + "page") + assert title_database == "Database", ( + f"tab-bar AXTitle after pressing Database = {title_database!r}") + assert remaining == 1, ( + f"{remaining} windows left after Preferences > Cancel (expected only the " + f"main window)") diff --git a/macos/sqlitebrowser-sqlitebrowser/tests/test_ax_states.py b/macos/sqlitebrowser-sqlitebrowser/tests/test_ax_states.py new file mode 100644 index 0000000000000000000000000000000000000000..1b56c774464f5c08ef5eb8774f08d6b9284ff410 --- /dev/null +++ b/macos/sqlitebrowser-sqlitebrowser/tests/test_ax_states.py @@ -0,0 +1,898 @@ +"""AX STATE verification suite — DB Browser for SQLite (Qt6). + +Sole owner of AXMenuItemMarkChar (CHECKED), AXEnabled flips, AXFocused and the +mode/selection indicators. + +KEY MECHANISM (recon ST1/ST2): Qt tab-bar radios expose AXValue == None and +AXSelected == None, so selection CANNOT be read from the radio. The tab-bar +`group`'s AXTitle equals the currently selected tab name; a tab bar is located by +its exact list of direct radio children (never by index / tree path). + +Every test declares depth + jump rigor via @pytest.mark.rb(...) and backs a +transition with kit.rb_flip / a value with kit.rb_value. +""" + +import json +import os +import subprocess +import time + +import pytest +import rb_testgen_kit as kit + +RESULTS_DIR = os.environ.get("RESULTS_DIR", os.path.dirname(os.path.abspath(__file__))) +MAIN_TABS = ["Database Structure", "Browse Data", "Edit Pragmas", "Execute SQL"] +DOCK_TABS = ["SQL Log", "Plot", "DB Schema", "Remote"] +REMOTE_TABS = ["DBHub.io", "Local", "Current Database"] +DIALOG_TABS = ["Fields", "Index Constraints", "Foreign Keys", "Check Constraints"] +PREFS_TABS = ["General", "Database", "Data Browser", "SQL", "Extensions", "Remote"] +PRAGMA_CHECKBOXES = ["Automatic Index", "Case Sensitive Like", "Checkpoint Full FSYNC", + "Foreign Keys", "Full FSYNC", "Ignore Check Constraints", + "Recursive Triggers", "Secure Delete"] +VIEW_TOGGLES = ["SQL Log", "Plot", "DB Schema", "Edit Database Cell", "Remote", + "DB Toolbar", "Extra DB Toolbar", "Project Toolbar", + "Database Structure", "Browse Data", "Edit Pragmas", "Execute SQL"] + + +def screenshot_assert(test_name, description, results_dir): + 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) + + +def _esc(times=1): + for _ in range(times): + subprocess.run(["osascript", "-e", + 'tell application "System Events" to key code 53'], + capture_output=True) + time.sleep(0.3) + + +def _key(code): + subprocess.run(["osascript", "-e", + 'tell application "System Events" to key code %d' % code], + capture_output=True) + time.sleep(0.35) + + +def open_menu(ax, top): + mb = ax.find(role="menu_bar_item", name=top, max_results=1) + if not mb: + return None + ax.action(mb[0].id, "AXPress") + time.sleep(0.6) + m = ax.find(role="menu", root_id=mb[0].id, max_results=1, max_depth=1) + return m[0] if m else None + + +def menu_item_map(ax, top, attrs=("AXEnabled", "AXMenuItemMarkChar")): + """Open `top`, read {name: {attr: value}} for its named items, then close the menu.""" + m = open_menu(ax, top) + out = {} + if m is not None: + for it in ax.find(role="menu_item", root_id=m.id, max_results=80, max_depth=1): + if it.name: + out[it.name] = ax.get(it.id, list(attrs)) + _esc(2) + return out + + +def rb_reach_menu_item(ax, top, item_name): + m = open_menu(ax, top) + if m is None: + return False + for it in ax.find(role="menu_item", root_id=m.id, max_results=80, max_depth=1): + if (it.name or "") == item_name: + ok = ax.action(it.id, "AXPress") + time.sleep(1.4) + return bool(ok) + _esc(2) + return False + + +def find_window(ax, title_substr): + for w in ax.find(role="window", max_results=10, max_depth=1): + if title_substr.lower() in (w.name or "").lower(): + return w + return None + + +def rb_enter_inmemory_db(ax): + """File > New In-Memory Database, then dismiss the auto-opened table dialog.""" + rb_reach_menu_item(ax, "File", "New In-Memory Database") + w = find_window(ax, "Edit table definition") + if w is not None: + c = ax.find(role="button", name="Cancel", root_id=w.id, max_results=2) + if c: + ax.action(c[0].id, "AXPress") + time.sleep(1.0) + return find_window(ax, "Edit table definition") is None + + +def switch_tab(ax, name, root_id=None): + r = ax.find(role="radio", name=name, max_results=1, root_id=root_id) + if not r: + return False + ok = ax.action(r[0].id, "AXPress") + time.sleep(1.0) + return bool(ok) + + +def tabbar(ax, kids, root_id=None): + """The tab-bar `group` whose direct radio children == kids. AXTitle == selected tab.""" + for g in ax.find(role="group", max_results=250, root_id=root_id): + ks = [k.name for k in ax.find(role="radio", root_id=g.id, max_results=10, max_depth=1)] + if ks == kids: + return g + return None + + +def selected_tab(ax, kids, root_id=None): + g = tabbar(ax, kids, root_id=root_id) + return None if g is None else g.name + + +def find_button(ax, name, root_id=None): + for b in ax.find(role="button", max_results=90, root_id=root_id): + if (b.name or "") == name: + return b + return None + + +def enabled(ax, el): + return bool(ax.get(el.id, ["AXEnabled"]).get("AXEnabled")) + + +def btn_enabled(ax, name): + b = find_button(ax, name) + return None if b is None else enabled(ax, b) + + +def checkbox_containing(ax, needle, root_id=None): + """Pragma checkbox AXTitles are literal HTML -> match by substring.""" + for c in ax.find(role="checkbox", max_results=60, root_id=root_id): + if needle in (c.name or ""): + return c + return None + + +def incrementor_containing(ax, needle, root_id=None): + for c in ax.find(role="incrementor", max_results=30, root_id=root_id): + if needle in (c.name or ""): + return c + return None + + +def cb_value(ax, el): + return ax.get(el.id, ["AXValue"]).get("AXValue") + + +def combo_named(ax, names, root_id=None): + for c in ax.find(role="combobox", max_results=30, root_id=root_id): + if (c.name or "") in names: + return c + return None + + +def combo_change(ax, combo, direction_code): + """Qt combobox: AXPress opens the popup, then arrow + Return commits. + direction_code: 125 = Down, 126 = Up.""" + ax.action(combo.id, "AXPress") + time.sleep(0.9) + _key(direction_code) + _key(36) + time.sleep(0.9) + + +def sql_editor(ax): + for t in ax.find(role="text_area", max_results=15): + if not ax.is_attribute_settable(t.id, "AXValue"): + continue + v = str(ax.get(t.id, ["AXValue"]).get("AXValue") or "") + if "PRAGMA" in v or "EXECUTING" in v: + continue + return t + return None + + +# ─────────────────────────── extra local helpers ─────────────────────────── +# All batched: ONE tree walk per role (12 separate full-tree walks blow the +# 30 s per-test budget on a ~325-node tree). + +PRAGMA_INCREMENTORS = ["Journal Size Limit", "Max Page Count", + "User Version", "WAL Auto Checkpoint"] +TOOLS_ITEMS = ["Compact Database...", "Load Extension...", "Integrity Check", + "Quick Integrity Check", "Foreign-Key Check", "Optimize", + "Show Row Counts"] +EDIT_DDL_ITEMS = ["Create Table...", "Create Index...", + "Modify Table...", "Delete Table..."] +# The app-menu Preferences item AXTitle is NOT stable ('Preferences...' vs +# 'Settings…') — always match by keyword (EN + ZH fallbacks). +PREF_KEYS = ("prefer", "etting", "偏好", "设置") + + +def _i(v): + """Normalize a checkbox AXValue (0/1, '0'/'1', bool) to an int.""" + if isinstance(v, bool): + return int(v) + try: + return int(v) + except (TypeError, ValueError): + return v + + +def _numstr(v): + """Normalize a spin-box AXValue to its plain string form ('1000', '-1').""" + if v is None: + return None + if isinstance(v, bool): + return str(int(v)) + if isinstance(v, float) and v.is_integer(): + return str(int(v)) + return str(v) + + +def buttons_by_name(ax, names, root_id=None): + """{name: element} for the wanted button AXTitles — one tree walk.""" + out = {} + for b in ax.find(role="button", max_results=120, root_id=root_id): + n = b.name or "" + if n in names and n not in out: + out[n] = b + return out + + +def button_names(ax, root_id=None): + return [b.name or "" for b in ax.find(role="button", max_results=120, root_id=root_id)] + + +def radio_names(ax, root_id=None): + return [r.name or "" for r in ax.find(role="radio", max_results=30, root_id=root_id)] + + +def combo_names(ax, root_id=None): + return [c.name or "" for c in ax.find(role="combobox", max_results=30, root_id=root_id)] + + +def label_texts(ax, root_id=None): + """Visible label text (AXValue and AXTitle both count — a recreation may use + either) for every `label` in the tree.""" + out = set() + for el in ax.find(role="label", max_results=150, root_id=root_id): + if el.value: + out.add(str(el.value)) + if el.name: + out.add(str(el.name)) + return out + + +def pragma_widgets(ax): + """({readable name: checkbox}, {readable name: incrementor}) — 2 tree walks. + Pragma AXTitles are literal HTML, so match by substring.""" + cbs = ax.find(role="checkbox", max_results=60) + incs = ax.find(role="incrementor", max_results=30) + cmap, imap = {}, {} + for n in PRAGMA_CHECKBOXES: + for c in cbs: + if n in (c.name or ""): + cmap[n] = c + break + for n in PRAGMA_INCREMENTORS: + for el in incs: + if n in (el.name or ""): + imap[n] = el + break + return cmap, imap + + +def pragma_enabled_list(ax): + """[AXEnabled] for the 8 pragma checkboxes then the 4 incrementors (None when + the widget is missing, so a gap FAILS instead of silently passing).""" + cmap, imap = pragma_widgets(ax) + out = [] + for n in PRAGMA_CHECKBOXES: + out.append(None if n not in cmap else enabled(ax, cmap[n])) + for n in PRAGMA_INCREMENTORS: + out.append(None if n not in imap else enabled(ax, imap[n])) + return out + + +def pragma_value_maps(ax): + cmap, imap = pragma_widgets(ax) + cvals = {n: (None if n not in cmap else _i(cb_value(ax, cmap[n]))) + for n in PRAGMA_CHECKBOXES} + ivals = {n: (None if n not in imap else _numstr(cb_value(ax, imap[n]))) + for n in PRAGMA_INCREMENTORS} + return cvals, ivals + + +def menu_enabled_map(item_map, names): + return {n: (bool(item_map[n].get("AXEnabled")) if n in item_map else None) + for n in names} + + +def mark_of(item_map, name): + return item_map.get(name, {}).get("AXMenuItemMarkChar") + + +def option_texts(ax, el): + """Visible option texts of a Qt combobox (its popup `list` holds one label per + option). Accepts AXTitle or AXValue so framework differences don't matter.""" + out = [] + for lb in ax.find(role="label", root_id=el.id, max_results=40): + t = lb.name or lb.value or "" + if t: + out.append(str(t)) + return out + + +def type_sql(ax, sql): + """QScintilla ignores set_value -> CG click + ⌘A + keystroke (recon COMPUTATION).""" + e = sql_editor(ax) + if e is None: + return False + ax.click_element_cg(e.id) + time.sleep(0.4) + subprocess.run(["osascript", "-e", + 'tell application "System Events" to keystroke "a" using command down'], + capture_output=True) + time.sleep(0.25) + subprocess.run(["osascript", "-e", + 'tell application "System Events" to keystroke ' + json.dumps(sql)], + capture_output=True) + time.sleep(0.5) + return True + + +def exec_sql(ax): + b = find_button(ax, "Execute SQL") + if b is None: + return False + ok = ax.action(b.id, "AXPress") + time.sleep(1.9) + return bool(ok) + + +def find_prefs_window(ax): + for w in ax.find(role="window", max_results=10, max_depth=1): + n = (w.name or "").lower() + if any(k in n for k in PREF_KEYS): + return w + return None + + +def rb_reach_preferences(ax): + """Open the Preferences/Settings surface by KEYWORD (recon: the menu item's + AXTitle is UNSTABLE — 'Preferences...' on one build, 'Settings…' on another). + Tries the app menu first, then the other menus, then the ⌘, hotkey.""" + w = find_prefs_window(ax) + if w is not None: + return w + tops = [t for t in ax.find(role="menu_bar_item", max_results=12, max_depth=3) + if (t.name or "") and (t.name or "").lower() != "apple"] + tops.sort(key=lambda t: 0 if any(k in (t.name or "").lower() + for k in ("sqlite", "browser", "db4s")) else 1) + for t in tops[:4]: + m = open_menu(ax, t.name) + if m is None: + continue + target = None + for it in ax.find(role="menu_item", root_id=m.id, max_results=80, max_depth=1): + nm = (it.name or "").lower() + if not nm or "service" in nm: + continue + if any(k in nm for k in PREF_KEYS): + target = it + break + if target is not None: + ax.action(target.id, "AXPress") + time.sleep(1.5) + w = find_prefs_window(ax) + if w is not None: + return w + _esc(2) + subprocess.run(["osascript", "-e", + 'tell application "System Events" to keystroke "," using command down'], + capture_output=True) + time.sleep(1.5) + return find_prefs_window(ax) + + +def close_scoped(ax, win, name="Cancel"): + """Close a dialog with ITS OWN scoped button (a global find(name='Cancel') + would also match the Edit-Pragmas / Preferences Cancel).""" + if win is None: + return False + b = ax.find(role="button", name=name, root_id=win.id, max_results=2) + if not b: + return False + ax.action(b[0].id, "AXPress") + time.sleep(0.8) + return True + + +def ext_widget_counts(ax, root_id): + """(n_checkboxes, n_buttons) whose visible label mentions "extension" — the + Extensions prefs page signature.""" + cbs = [c for c in ax.find(role="checkbox", max_results=60, root_id=root_id) + if "xtension" in (c.name or "").lower()] + bts = [b for b in ax.find(role="button", max_results=90, root_id=root_id) + if "xtension" in (b.name or "").lower()] + return len(cbs), len(bts) + + +# ══════════════════════════════ TAB-BAR SELECTION ══════════════════════════════ + +class TestTabBarSelectionState: + """ST1/ST2/ST3 — the mode/selection indicator is the tab-bar group's AXTitle.""" + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="main tab-bar group AXTitle 'Database Structure'->'Execute SQL'" + "->'Browse Data'->'Edit Pragmas'->back to 'Database Structure'") + def test_main_tab_bar_selection_indicator_walks_all_four(self, ax): + fresh = selected_tab(ax, MAIN_TABS) + assert fresh == "Database Structure", ( + f"fresh main tab-bar AXTitle should be 'Database Structure', got {fresh!r}") + seq = [fresh] + for name in ["Execute SQL", "Browse Data", "Edit Pragmas", "Database Structure"]: + assert switch_tab(ax, name), f"could not AXPress main tab radio {name!r}" + now = selected_tab(ax, MAIN_TABS) + assert now == name, ( + f"after pressing radio {name!r} the tab-bar AXTitle should be {name!r}, " + f"got {now!r}") + seq.append(now) + assert seq == ["Database Structure", "Execute SQL", "Browse Data", + "Edit Pragmas", "Database Structure"], seq + assert kit.rb_flip(seq[:-1], seq[1:]), ( + "the selection indicator never changed across the 4 main tabs") + screenshot_assert( + "states_test_main_tab_bar_selection", + "DB Browser for SQLite main window with the 4-tab bar Database Structure / " + "Browse Data / Edit Pragmas / Execute SQL. The walk ended back on " + "Database Structure, so that tab is the highlighted/selected one and the " + "left pane shows the empty object tree with Create Table, Create Index and " + "Modify Table buttons above it (all greyed out, no database open).", + RESULTS_DIR) + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="tab radios report AXValue None and AXSelected None; selection is " + "only readable from the tab-bar group AXTitle") + def test_main_tab_radios_expose_no_selection_attribute(self, ax): + g = tabbar(ax, MAIN_TABS) + assert g is not None, "main tab bar (radios == MAIN_TABS) not found" + radios = ax.find(role="radio", root_id=g.id, max_results=10, max_depth=1) + assert [r.name for r in radios] == MAIN_TABS, [r.name for r in radios] + for r in radios: + attrs = ax.get(r.id, ["AXValue", "AXSelected"]) + assert attrs.get("AXValue") is None, ( + f"radio {r.name!r} AXValue should be None, got {attrs.get('AXValue')!r}") + assert attrs.get("AXSelected") is None, ( + f"radio {r.name!r} AXSelected should be None, " + f"got {attrs.get('AXSelected')!r}") + assert kit.rb_value(selected_tab(ax, MAIN_TABS), "Database Structure") + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="dock tab-bar group AXTitle 'Remote'->'DB Schema'->'Plot'->'SQL Log'") + def test_dock_tab_bar_selection_indicator(self, ax): + fresh = selected_tab(ax, DOCK_TABS) + assert fresh == "Remote", ( + f"fresh dock tab-bar AXTitle should be 'Remote', got {fresh!r}") + seq = [fresh] + for name in ["DB Schema", "Plot", "SQL Log"]: + assert switch_tab(ax, name), f"could not AXPress dock tab radio {name!r}" + now = selected_tab(ax, DOCK_TABS) + assert now == name, ( + f"after pressing dock radio {name!r} the tab-bar AXTitle should be " + f"{name!r}, got {now!r}") + seq.append(now) + assert seq == ["Remote", "DB Schema", "Plot", "SQL Log"], seq + assert kit.rb_flip(seq[:-1], seq[1:]), "the dock selection indicator never changed" + screenshot_assert( + "states_test_dock_tab_selection", + "The bottom-right dock of DB Browser for SQLite. Its tab strip reads " + "SQL Log / Plot / DB Schema / Remote and SQL Log is now the highlighted " + "(selected) tab, so the dock body shows the SQL log text pane with the " + "'Show SQL submitted by' dropdown (Application) and a Clear button — the " + "Remote panel is no longer displayed.", + RESULTS_DIR) + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="Remote panel sub tab-bar AXTitle 'DBHub.io'->'Local'" + "->'Current Database'") + def test_remote_sub_tab_bar_selection_indicator(self, ax): + g = tabbar(ax, REMOTE_TABS) + assert g is not None, "Remote sub tab bar (radios == REMOTE_TABS) not found" + fresh = g.name + assert fresh == "DBHub.io", ( + f"fresh Remote sub tab-bar AXTitle should be 'DBHub.io', got {fresh!r}") + seq = [fresh] + for name in ["Local", "Current Database"]: + bar = tabbar(ax, REMOTE_TABS) + assert bar is not None, "Remote sub tab bar vanished" + assert switch_tab(ax, name, root_id=bar.id), ( + f"could not AXPress Remote sub-tab radio {name!r}") + now = selected_tab(ax, REMOTE_TABS) + assert now == name, ( + f"after pressing Remote sub-tab {name!r} the sub tab-bar AXTitle should " + f"be {name!r}, got {now!r}") + seq.append(now) + assert seq == ["DBHub.io", "Local", "Current Database"], seq + assert kit.rb_flip(seq[:-1], seq[1:]), "the Remote sub-tab indicator never changed" + + +# ═════════════════════════ VIEW MENU CHECK STATE (ST6) ═════════════════════════ + +class TestViewMenuCheckState: + """AXMenuItemMarkChar on the 12 View toggles + two SAFE round trips.""" + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="all 12 View toggles have AXMenuItemMarkChar '✓' on a fresh app") + def test_view_menu_all_twelve_toggles_checked_by_default(self, ax_with_reset): + ax = ax_with_reset + items = menu_item_map(ax, "View") + assert items, "View menu exposed no named menu items" + marks = [] + for name in VIEW_TOGGLES: + assert name in items, f"View menu item {name!r} missing (got {sorted(items)})" + mark = mark_of(items, name) + assert mark == "✓", ( + f"View toggle {name!r} should carry AXMenuItemMarkChar '✓' on a " + f"fresh app, got {mark!r}") + marks.append(mark) + assert len(marks) == 12 + assert kit.rb_value(sorted(set(marks)), "✓") + open_menu(ax, "View") + screenshot_assert( + "states_test_view_menu_checkmarks", + "The View menu of DB Browser for SQLite is open in the macOS menu bar. It " + "lists SQL Log, Plot, DB Schema, Edit Database Cell, Remote, DB Toolbar, " + "Extra DB Toolbar, Project Toolbar, Database Structure, Browse Data, " + "Edit Pragmas and Execute SQL — every one of those 12 entries shows a " + "checkmark on its left — plus a 'Window Layout' submenu and " + "'Enter Full Screen' with no checkmark.", + RESULTS_DIR) + _esc(2) + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="View▸SQL Log mark '✓'->None and the dock's Clear button / " + "'Show SQL submitted by' label / source combobox / 'SQL Log' radio " + "disappear, then all return") + def test_view_sql_log_toggle_round_trip(self, ax_with_reset): + ax = ax_with_reset + mark_before = mark_of(menu_item_map(ax, "View"), "SQL Log") + assert mark_before == "✓", ( + f"View▸SQL Log should start CHECKED, got {mark_before!r}") + assert find_button(ax, "Clear") is not None, "SQL Log dock 'Clear' button missing" + before = kit.rb_showing(ax) + + assert rb_reach_menu_item(ax, "View", "SQL Log"), "could not press View▸SQL Log" + after = kit.rb_showing(ax) + mark_off = mark_of(menu_item_map(ax, "View"), "SQL Log") + assert mark_off is None, ( + f"View▸SQL Log mark should be None once the dock is hidden, got {mark_off!r}") + assert find_button(ax, "Clear") is None, "SQL Log dock 'Clear' button still present" + assert combo_named(ax, ("Application",)) is None, ( + "SQL log source combobox 'Application' still present") + assert "SQL Log" not in radio_names(ax), "dock tab radio 'SQL Log' still present" + assert "Show SQL submitted by" not in label_texts(ax), ( + "label 'Show SQL submitted by' still present") + assert kit.rb_flip(mark_before, mark_off), "the SQL Log checkmark never flipped" + assert len(after) < len(before), ( + "hiding the SQL Log dock should REMOVE nodes from the AX tree " + f"(before={len(before)} after={len(after)})") + + assert rb_reach_menu_item(ax, "View", "SQL Log"), "could not re-press View▸SQL Log" + mark_back = mark_of(menu_item_map(ax, "View"), "SQL Log") + assert mark_back == "✓", ( + f"View▸SQL Log mark should return to '✓', got {mark_back!r}") + assert find_button(ax, "Clear") is not None, "'Clear' button did not come back" + assert combo_named(ax, ("Application",)) is not None, ( + "SQL log source combobox did not come back") + assert "SQL Log" in radio_names(ax), "dock tab radio 'SQL Log' did not come back" + assert "Show SQL submitted by" in label_texts(ax), ( + "label 'Show SQL submitted by' did not come back") + _esc(2) + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="View▸Plot mark '✓'->None->'✓' and the 'Line type:' / " + "'Point shape:' labels disappear and return") + def test_view_plot_toggle_round_trip(self, ax_with_reset): + ax = ax_with_reset + mark_before = mark_of(menu_item_map(ax, "View"), "Plot") + assert mark_before == "✓", ( + f"View▸Plot should start CHECKED, got {mark_before!r}") + texts = label_texts(ax) + assert "Line type:" in texts and "Point shape:" in texts, ( + "the Plot dock's 'Line type:' / 'Point shape:' labels are missing on a fresh app") + + assert rb_reach_menu_item(ax, "View", "Plot"), "could not press View▸Plot" + mark_off = mark_of(menu_item_map(ax, "View"), "Plot") + assert mark_off is None, ( + f"View▸Plot mark should be None once the dock is hidden, got {mark_off!r}") + gone = label_texts(ax) + assert "Line type:" not in gone, "'Line type:' label still present" + assert "Point shape:" not in gone, "'Point shape:' label still present" + assert "Plot" not in radio_names(ax), "dock tab radio 'Plot' still present" + assert kit.rb_flip(mark_before, mark_off), "the Plot checkmark never flipped" + + assert rb_reach_menu_item(ax, "View", "Plot"), "could not re-press View▸Plot" + mark_back = mark_of(menu_item_map(ax, "View"), "Plot") + assert mark_back == "✓", ( + f"View▸Plot mark should return to '✓', got {mark_back!r}") + back = label_texts(ax) + assert "Line type:" in back and "Point shape:" in back, ( + "the Plot dock labels did not come back") + _esc(2) + + +# ═══════════════════════════ PRAGMA STATE (ST7/ST8) ═══════════════════════════ + +class TestPragmaState: + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="all 8 pragma checkboxes AXValue 0 / AXEnabled False and the 4 " + "incrementors AXValue '0' / disabled with no database open") + def test_pragma_widgets_disabled_without_database(self, ax): + assert switch_tab(ax, "Edit Pragmas"), "could not activate the Edit Pragmas tab" + assert selected_tab(ax, MAIN_TABS) == "Edit Pragmas" + cvals, ivals = pragma_value_maps(ax) + assert cvals == {n: 0 for n in PRAGMA_CHECKBOXES}, cvals + assert ivals == {n: "0" for n in PRAGMA_INCREMENTORS}, ivals + en = pragma_enabled_list(ax) + assert len(en) == 12 and all(v is False for v in en), ( + f"every pragma widget must be DISABLED with no database open, got {en}") + observed = (tuple(sorted(cvals.items())), tuple(sorted(ivals.items())), tuple(en)) + expected = (tuple(sorted({n: 0 for n in PRAGMA_CHECKBOXES}.items())), + tuple(sorted({n: "0" for n in PRAGMA_INCREMENTORS}.items())), + tuple([False] * 12)) + assert kit.rb_value(observed, expected) + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="pragma checkboxes+incrementors AXEnabled False->True after " + "File▸New In-Memory Database") + def test_pragma_widgets_enable_with_database(self, ax_with_reset): + ax = ax_with_reset + assert switch_tab(ax, "Edit Pragmas"), "could not activate the Edit Pragmas tab" + before = pragma_enabled_list(ax) + assert len(before) == 12 and all(v is False for v in before), before + + assert rb_enter_inmemory_db(ax), "in-memory database was not opened cleanly" + assert switch_tab(ax, "Database Structure") + assert switch_tab(ax, "Edit Pragmas"), "could not re-activate the Edit Pragmas tab" + after = pragma_enabled_list(ax) + assert len(after) == 12 and all(v is True for v in after), ( + f"every pragma widget must be ENABLED once a database is open, got {after}") + assert kit.rb_flip(before, after), "the pragma ENABLED state never flipped" + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="Foreign Keys=1, Automatic Index=1, other 6 pragma checkboxes=0, " + "WAL Auto Checkpoint='1000', Journal Size Limit='-1', " + "Max Page Count='0', User Version='0'") + def test_pragma_values_load_for_inmemory_database(self, ax_with_reset): + ax = ax_with_reset + # ORDERING MATTERS: open the DB while ANOTHER tab is active, then activate + # Edit Pragmas — the pragma values only load on tab activation. + assert rb_enter_inmemory_db(ax), "in-memory database was not opened cleanly" + assert switch_tab(ax, "Edit Pragmas"), "could not activate the Edit Pragmas tab" + cvals, ivals = pragma_value_maps(ax) + expected_cb = {n: 0 for n in PRAGMA_CHECKBOXES} + expected_cb["Foreign Keys"] = 1 + expected_cb["Automatic Index"] = 1 + expected_inc = {"WAL Auto Checkpoint": "1000", "Journal Size Limit": "-1", + "Max Page Count": "0", "User Version": "0"} + assert cvals == expected_cb, f"pragma checkbox values {cvals} != {expected_cb}" + assert ivals == expected_inc, f"pragma spin values {ivals} != {expected_inc}" + assert kit.rb_value((tuple(sorted(cvals.items())), tuple(sorted(ivals.items()))), + (tuple(sorted(expected_cb.items())), + tuple(sorted(expected_inc.items())))) + screenshot_assert( + "states_test_pragma_values_inmemory", + "The Edit Pragmas tab of DB Browser for SQLite with the in-memory database " + "open. The pragma form lists Auto Vacuum, Automatic Index, Case Sensitive " + "Like, Checkpoint Full FSYNC, Foreign Keys, Full FSYNC, Ignore Check " + "Constraints, Journal Mode, Journal Size Limit, Locking Mode, Max Page " + "Count, Page Size, Recursive Triggers, Secure Delete, Synchronous, Temp " + "Store, User Version and WAL Auto Checkpoint. Exactly two checkboxes are " + "ticked — Foreign Keys and Automatic Index — every other pragma checkbox is " + "unticked, and the WAL Auto Checkpoint spin box reads 1000 while Journal " + "Size Limit reads -1. Save and Cancel buttons sit at the bottom.", + RESULTS_DIR) + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="Foreign Keys checkbox AXValue 1->0->1") + def test_pragma_foreign_keys_checkbox_toggle_round_trip(self, ax_with_reset): + ax = ax_with_reset + assert rb_enter_inmemory_db(ax), "in-memory database was not opened cleanly" + assert switch_tab(ax, "Edit Pragmas"), "could not activate the Edit Pragmas tab" + cb = checkbox_containing(ax, "Foreign Keys") + assert cb is not None, "pragma checkbox 'Foreign Keys' not found" + assert enabled(ax, cb), "pragma checkbox 'Foreign Keys' should be ENABLED with a DB" + v0 = _i(cb_value(ax, cb)) + assert v0 == 1, f"Foreign Keys should start CHECKED (1) for a new DB, got {v0!r}" + assert ax.action(cb.id, "AXPress"), "AXPress on the Foreign Keys checkbox failed" + time.sleep(0.5) + v1 = _i(cb_value(ax, cb)) + assert v1 == 0, f"Foreign Keys should be UNCHECKED (0) after one press, got {v1!r}" + assert kit.rb_flip(v0, v1), "the Foreign Keys checkbox value never flipped" + assert ax.action(cb.id, "AXPress"), "second AXPress on Foreign Keys failed" + time.sleep(0.5) + v2 = _i(cb_value(ax, cb)) + assert v2 == 1, f"Foreign Keys should be CHECKED (1) again, got {v2!r}" + + +# ═════════════════════════ ENABLED FLIPS (ST8/ST9/ST10) ════════════════════════ + +class TestEnabledFlips: + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="Write Changes / Revert Changes AXEnabled False->True after a " + "CREATE TABLE executed in the Execute SQL tab") + def test_write_changes_enabled_flip_after_ddl(self, ax_with_reset): + ax = ax_with_reset + assert rb_enter_inmemory_db(ax), "in-memory database was not opened cleanly" + wanted = ("Write Changes", "Revert Changes") + bm = buttons_by_name(ax, wanted) + assert set(bm) == set(wanted), f"toolbar buttons missing: {sorted(bm)}" + before = (enabled(ax, bm["Write Changes"]), enabled(ax, bm["Revert Changes"])) + assert before == (False, False), ( + f"Write/Revert Changes must be DISABLED before any DDL, got {before}") + + assert switch_tab(ax, "Execute SQL"), "could not activate the Execute SQL tab" + assert type_sql(ax, "CREATE TABLE t1(a INTEGER, b TEXT);"), "SQL editor not found" + assert exec_sql(ax), "could not press the 'Execute SQL' button" + + bm2 = buttons_by_name(ax, wanted) + assert set(bm2) == set(wanted), f"toolbar buttons missing after DDL: {sorted(bm2)}" + after = (enabled(ax, bm2["Write Changes"]), enabled(ax, bm2["Revert Changes"])) + assert after == (True, True), ( + f"Write/Revert Changes must be ENABLED after a CREATE TABLE, got {after}") + assert kit.rb_flip(before, after), "the pending-changes ENABLED state never flipped" + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="Tools items and Edit▸Create Table.../Create Index... AXEnabled " + "False->True after opening the in-memory database") + def test_tools_and_edit_menu_enabled_flip_with_database(self, ax_with_reset): + ax = ax_with_reset + tools_before = menu_enabled_map(menu_item_map(ax, "Tools"), TOOLS_ITEMS) + edit_before = menu_enabled_map(menu_item_map(ax, "Edit"), EDIT_DDL_ITEMS) + assert tools_before == {n: False for n in TOOLS_ITEMS}, tools_before + assert edit_before == {n: False for n in EDIT_DDL_ITEMS}, edit_before + + assert rb_enter_inmemory_db(ax), "in-memory database was not opened cleanly" + + tools_after = menu_enabled_map(menu_item_map(ax, "Tools"), TOOLS_ITEMS) + edit_after = menu_enabled_map(menu_item_map(ax, "Edit"), EDIT_DDL_ITEMS) + assert tools_after == {n: True for n in TOOLS_ITEMS}, ( + f"every Tools item must be ENABLED with a database open, got {tools_after}") + assert edit_after == {"Create Table...": True, "Create Index...": True, + "Modify Table...": False, "Delete Table...": False}, edit_after + before = (tuple(sorted(tools_before.items())), tuple(sorted(edit_before.items()))) + after = (tuple(sorted(tools_after.items())), tuple(sorted(edit_after.items()))) + assert kit.rb_flip(before, after), "no menu-item ENABLED state flipped" + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="Clear Filters AXEnabled False->True when a filter is typed and " + "back to False after pressing it") + def test_clear_filters_enabled_round_trip(self, ax_with_reset): + ax = ax_with_reset + assert rb_enter_inmemory_db(ax), "in-memory database was not opened cleanly" + assert switch_tab(ax, "Execute SQL"), "could not activate the Execute SQL tab" + assert type_sql(ax, "CREATE TABLE nums(n INTEGER, label TEXT); " + "INSERT INTO nums VALUES(10,'ten'),(20,'twenty'),(30,'thirty');") + assert exec_sql(ax), "could not press the 'Execute SQL' button" + assert switch_tab(ax, "Browse Data"), "could not activate the Browse Data tab" + + btn = find_button(ax, "Clear Filters") + assert btn is not None, "button 'Clear Filters' not found on the Browse Data tab" + before = enabled(ax, btn) + assert before is False, "'Clear Filters' must be DISABLED with no filter typed" + + flt = ax.find(role="text_field", name="Filter in any column", max_results=1) + assert flt, "text_field 'Filter in any column' not found" + assert ax.set_value(flt[0].id, "twenty"), "could not set the filter text" + time.sleep(1.7) + after = enabled(ax, find_button(ax, "Clear Filters")) + assert after is True, "'Clear Filters' must be ENABLED once a filter is typed" + assert kit.rb_flip(before, after), "the Clear Filters ENABLED state never flipped" + + btn2 = find_button(ax, "Clear Filters") + assert btn2 is not None + assert ax.action(btn2.id, "AXPress"), "AXPress on 'Clear Filters' failed" + time.sleep(1.7) + assert enabled(ax, find_button(ax, "Clear Filters")) is False, ( + "'Clear Filters' must be DISABLED again after clearing") + flt2 = ax.find(role="text_field", name="Filter in any column", max_results=1) + assert flt2, "the filter field disappeared" + assert (ax.get(flt2[0].id, ["AXValue"]).get("AXValue") or "") == "", ( + "the filter field should be emptied by 'Clear Filters'") + + +# ═══════════════════════ MODE COMBOBOX + FOCUS (ST13/ST11) ═══════════════════════ + +class TestModeAndFocusState: + + @pytest.mark.rb(depth=0, jump_kind="transition", + expect="SQL log source combobox AXTitle 'Application'->'User' via popup " + "+ Up + Return") + def test_sql_log_source_combobox_mode_flip(self, ax): + combo = combo_named(ax, ("Application",)) + assert combo is not None, "SQL log source combobox 'Application' not found" + assert enabled(ax, combo), "the SQL log source combobox should be ENABLED" + opts = option_texts(ax, combo) + assert opts == ["User", "Application", "Error Log"], ( + f"SQL log source options should be User/Application/Error Log, got {opts}") + before = ax.get(combo.id, ["AXTitle"]).get("AXTitle") + assert before == "Application", ( + f"the fresh SQL log source should be 'Application', got {before!r}") + combo_change(ax, combo, 126) + after = ax.get(combo.id, ["AXTitle"]).get("AXTitle") + assert after == "User", ( + f"after popup + Up + Return the source should read 'User', got {after!r}") + assert kit.rb_flip(before, after), "the SQL log source mode never changed" + + + +# ═════════════════════ DIALOG (ST4) + PREFERENCES (ST5) STATE ═════════════════════ + +class TestDialogAndPrefsState: + + + @pytest.mark.rb(depth=2, jump_kind="transition", + expect="Preferences tab-bar AXTitle 'General'->'Extensions' and the " + "Extensions-tab extension checkboxes/buttons appear") + def test_preferences_tab_bar_selection_indicator(self, ax_with_reset): + ax = ax_with_reset + prefs = rb_reach_preferences(ax) + assert prefs is not None, "the Preferences/Settings window did not open" + tab_before = selected_tab(ax, PREFS_TABS, root_id=prefs.id) + assert tab_before == "General", ( + f"the Preferences tab bar should open on 'General', got {tab_before!r}") + ext_before = ext_widget_counts(ax, prefs.id) + assert ext_before == (0, 0), ( + f"no extension checkbox/button should be showing on the General page, " + f"got {ext_before}") + + bar = tabbar(ax, PREFS_TABS, root_id=prefs.id) + assert bar is not None, "the Preferences tab bar was not found" + assert switch_tab(ax, "Extensions", root_id=bar.id), ( + "could not AXPress the Preferences 'Extensions' tab") + tab_after = selected_tab(ax, PREFS_TABS, root_id=prefs.id) + assert tab_after == "Extensions", ( + f"the Preferences tab-bar AXTitle should be 'Extensions', got {tab_after!r}") + ext_after = ext_widget_counts(ax, prefs.id) + assert ext_after[0] >= 2, ( + f"the Extensions page should expose at least 2 extension checkboxes " + f"(e.g. 'Disable Regular Expression extension', 'Allow loading extensions " + f"from SQL code'), got {ext_after[0]}") + assert ext_after[1] >= 2, ( + f"the Extensions page should expose add/remove extension buttons, " + f"got {ext_after[1]}") + assert kit.rb_flip((tab_before, ext_before), (tab_after, ext_after)), ( + "the Preferences tab selection never changed") + screenshot_assert( + "states_test_preferences_extensions_tab", + "A separate Preferences window of DB Browser for SQLite, in front of the " + "main window. Its tab strip reads General, Database, Data Browser, SQL, " + "Extensions, Remote and 'Extensions' is now the selected tab, so the page " + "shows the SQLite extension list with Add/Remove extension buttons and the " + "checkboxes for disabling the Regular Expression extension and allowing " + "extension loading from SQL code. Save, Cancel and Restore Defaults buttons " + "are at the bottom.", + RESULTS_DIR) + assert close_scoped(ax, prefs, "Cancel"), ( + "could not close the Preferences window with its own Cancel button") diff --git a/macos/sqlitebrowser-sqlitebrowser/tests/test_ax_structure.py b/macos/sqlitebrowser-sqlitebrowser/tests/test_ax_structure.py new file mode 100644 index 0000000000000000000000000000000000000000..583e835b59081e2f1f227873730ab6c4e6f9c393 --- /dev/null +++ b/macos/sqlitebrowser-sqlitebrowser/tests/test_ax_structure.py @@ -0,0 +1,729 @@ +"""AX STRUCTURE tests for `DB Browser for SQLite` (Qt6, net.sourceforge.sqlitebrowser). + +Every fact asserted here comes from the recon report's `## APP` / `## AX_TREE` / `## STRUCTURE` +sections (role census, tab-bar radio sets, toolbar button names, column headers, shape deltas). +Widgets are located by AXRole + visible AXTitle/AXValue (never by child index or tree path). + +Fresh-app starting state (per recon): main window on screen, NO DATABASE OPEN. +""" + +import json +import os +import re +import subprocess +import time + +import pytest +import rb_testgen_kit as kit + +RESULTS_DIR = os.environ.get("RESULTS_DIR", os.path.dirname(os.path.abspath(__file__))) +MAIN_TABS = ["Database Structure", "Browse Data", "Edit Pragmas", "Execute SQL"] +DOCK_TABS = ["SQL Log", "Plot", "DB Schema", "Remote"] +REMOTE_TABS = ["DBHub.io", "Local", "Current Database"] + + +def screenshot_assert(test_name, description, results_dir): + 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) + + +def _esc(times=1): + for _ in range(times): + subprocess.run(["osascript", "-e", + 'tell application "System Events" to key code 53'], + capture_output=True) + time.sleep(0.3) + + +def open_menu(ax, top): + """Open a top-level app menu; returns its `menu` element or None.""" + mb = ax.find(role="menu_bar_item", name=top, max_results=1) + if not mb: + return None + ax.action(mb[0].id, "AXPress") + time.sleep(0.6) + m = ax.find(role="menu", root_id=mb[0].id, max_results=1, max_depth=1) + return m[0] if m else None + + +def rb_reach_menu_item(ax, top, item_name): + """Open `top` and AXPress the menu item named exactly `item_name`.""" + m = open_menu(ax, top) + if m is None: + return False + for it in ax.find(role="menu_item", root_id=m.id, max_results=80, max_depth=1): + if (it.name or "") == item_name: + ok = ax.action(it.id, "AXPress") + time.sleep(1.4) + return bool(ok) + _esc(2) + return False + + +def find_window(ax, title_substr): + for w in ax.find(role="window", max_results=10, max_depth=1): + if title_substr.lower() in (w.name or "").lower(): + return w + return None + + +def rb_enter_inmemory_db(ax): + """File > New In-Memory Database, then dismiss the auto-opened table dialog.""" + rb_reach_menu_item(ax, "File", "New In-Memory Database") + w = find_window(ax, "Edit table definition") + if w is not None: + c = ax.find(role="button", name="Cancel", root_id=w.id, max_results=2) + if c: + ax.action(c[0].id, "AXPress") + time.sleep(1.0) + return find_window(ax, "Edit table definition") is None + + +def switch_tab(ax, name): + r = ax.find(role="radio", name=name, max_results=1) + if not r: + return False + ok = ax.action(r[0].id, "AXPress") + time.sleep(1.0) + return bool(ok) + + +def tabbar(ax, kids): + """The tab-bar `group` whose direct radio children == kids. Its AXTitle == selected tab.""" + for g in ax.find(role="group", max_results=250): + ks = [k.name for k in ax.find(role="radio", root_id=g.id, max_results=10, max_depth=1)] + if ks == kids: + return g + return None + + +def names(els): + return [e.name for e in els if e.name] + + +def find_button(ax, name): + for b in ax.find(role="button", max_results=80): + if (b.name or "") == name: + return b + return None + + +# --------------------------------------------------------------------------- # +# recon-derived expectations (## AX_TREE, ## STRUCTURE, ## TEXT, ## BUTTONS) +# --------------------------------------------------------------------------- # + +APP_MENU_TITLE = "DB Browser for SQLite" +MAIN_WINDOW_PREFIX = "db browser for sqlite" +TOP_MENUS = ["DB Browser for SQLite", "File", "Edit", "View", "Tools", "Help"] +STD_MENU_NAMES = {"apple", "file", "edit", "view", "tools", "help", "window"} + +TOOLBAR_BUTTONS = ["New Database", "Open Database", "Write Changes", "Revert Changes", + "Undo", "Open Project", "Save Project", "Attach Database"] +STRUCTURE_TOOLBAR_BUTTONS = ["Create Table", "Create Index", "Modify Table"] + +# ## TEXT T3 — column header sets that exist on a FRESH app (no DB) +STRUCTURE_COLUMNS = {"Name", "Object", "Type", "Schema", "Database"} +REMOTE_COLUMNS = {"Name", "Last modified", "Size", "Commit"} +PLOT_COLUMNS = {"Columns", "X", "Y1", "Y2", "Axis Type"} +TABLE_DIALOG_COLUMNS = {"Name", "Type", "NN", "PK", "AI", "U", + "Default", "Check", "Collation", "Foreign Key"} + +# ## AX_TREE / T1 — one signature label per dock panel (read via AXValue) +DOCK_LABEL_TEXTS = ["Mode:", "Show SQL submitted by", "Line type:", "Point shape:", "Identity"] + +# ## STRUCTURE S1 — Execute SQL tab page +EXEC_SQL_BUTTONS = {"Execute SQL", "Execute line", "Stop execution", "Open SQL file(s)", + "Save SQL file", "Save results", "New tab", "Find or replace", + "Un/comment block"} +# ## STRUCTURE S2 — Browse Data tab page +BROWSE_BUTTONS = {"New Record", "Save Table As", "New Data Browser", "Clear Filters", + "Clear Sorting", "Go to:"} +BROWSE_TEXT_FIELDS = ["Filter in any column", "Enter record number to browse"] +# ## STRUCTURE S3 / T6 — the 8 pragma checkboxes (AXTitle is literal HTML -> substring match) +PRAGMA_CHECKBOX_NAMES = ["Automatic Index", "Case Sensitive Like", "Checkpoint Full FSYNC", + "Foreign Keys", "Full FSYNC", "Ignore Check Constraints", + "Recursive Triggers", "Secure Delete"] +# ## STRUCTURE S6 / ST4 — Edit table definition dialog +TABLE_DIALOG_TABS = {"Fields", "Index Constraints", "Foreign Keys", "Check Constraints"} +TABLE_DIALOG_BUTTONS = {"Add", "Remove", "Move to top", "Move up", "Move down", + "Move to bottom", "OK", "Cancel"} +# ## STRUCTURE S7 / ST5 — Preferences window +PREFS_TABS = {"General", "Database", "Data Browser", "SQL", "Extensions", "Remote"} +PREFS_BUTTONS = {"Save", "Cancel", "Restore Defaults", "Import Settings", "Export Settings"} + +# role census on a fresh app (## AX_TREE "Role census") +MIN_ROLE_COUNTS = [("button", 30), ("radio", 11), ("combobox", 5), ("checkbox", 4), + ("label", 40), ("text_area", 2), ("split_group", 1), ("menubutton", 1)] +ABSENT_ROLES = {"tabgroup", "toolbar", "outline"} +SQL_SUBTAB_RE = re.compile(r"^\s*SQL\s*\d+\s*$") + + +# --------------------------------------------------------------------------- # +# small, framework-tolerant locator helpers (recon-only, no live exploration) +# --------------------------------------------------------------------------- # + +def rb_ensure_ui(ax, tries=3): + """Best-effort reveal of the app's window before any window-dependent check. + + Recon REVEAL_STEPS: this is a regular windowed app whose main window is already on + screen at launch, so this normally returns immediately. `ensure_ui_visible` is used + when the helper exposes it (menu-bar/LSUIElement style recreations). + """ + wins = [] + for _ in range(tries): + wins = ax.find(role="window", max_results=10, max_depth=1) + if wins: + return wins + fn = getattr(ax, "ensure_ui_visible", None) + if callable(fn): + try: + fn() + except Exception: + pass + time.sleep(0.7) + return wins + + +def role_els(ax, role, root_id=None, limit=200, max_depth=None): + kw = {"role": role, "max_results": limit} + if root_id is not None: + kw["root_id"] = root_id + if max_depth is not None: + kw["max_depth"] = max_depth + try: + return list(ax.find(**kw) or []) + except Exception: + return [] + + +def role_name_set(ax, role, root_id=None, limit=200, max_depth=None): + return {(e.name or "").strip() for e in role_els(ax, role, root_id, limit, max_depth)} + + +def _norm_text(s): + s = (s or "").replace("…", "...") + s = re.sub(r"\s+", " ", s).strip().lower() + return s.rstrip(":").strip() + + +def _norm_role(r): + r = (r or "").strip().lower() + if r.startswith("ax"): + r = r[2:] + return r.replace("_", "").replace(" ", "").replace("-", "") + + +def el_value(ax, el): + try: + got = ax.get(el.id, ["AXValue"]) or {} + except Exception: + return "" + v = got.get("AXValue") if hasattr(got, "get") else got + return "" if v is None else str(v) + + +def label_texts(ax, limit=200): + """Normalised visible text of every `label`: AXTitle AND AXValue (either may carry it).""" + out = set() + for lb in role_els(ax, "label", limit=limit): + n = _norm_text(lb.name) + if n: + out.add(n) + v = _norm_text(el_value(ax, lb)) + if v: + out.add(v) + return out + + +def walk_tree_nodes(node, depth=1): + """Yield (level, role, name); the root element is level 1 (== number of levels).""" + if not isinstance(node, dict): + return + yield depth, (node.get("role") or ""), (node.get("name") or "") + for ch in (node.get("children") or []): + yield from walk_tree_nodes(ch, depth + 1) + + +def all_tab_bars(ax): + """Every `group` that owns direct `radio` children -> {tuple(radio names): group}.""" + out = {} + for g in role_els(ax, "group", limit=250): + ks = tuple((k.name or "").strip() + for k in role_els(ax, "radio", root_id=g.id, limit=12, max_depth=1)) + ks = tuple(k for k in ks if k) + if ks: + out[ks] = g + return out + + +def find_tab_bar(ax, kids): + """Tab-bar group whose direct radio children are exactly `kids` (order-tolerant).""" + g = tabbar(ax, list(kids)) + if g is not None: + return g + want = set(kids) + for ks, grp in all_tab_bars(ax).items(): + if set(ks) == want: + return grp + return None + + +def rb_press_button(ax, name, root_id=None, settle=1.2): + """AXPress the `button` whose AXTitle is exactly `name` (optionally scoped).""" + for b in role_els(ax, "button", root_id=root_id, limit=150): + if (b.name or "").strip() == name: + ok = ax.action(b.id, "AXPress") + time.sleep(settle) + return bool(ok) + return False + + +def rb_open_app_menu(ax): + """Open the application menu (title == app name; falls back to the non-standard menu).""" + m = open_menu(ax, APP_MENU_TITLE) + if m is not None: + return m + for mbi in role_els(ax, "menu_bar_item", limit=20): + n = (mbi.name or "").strip() + if not n or n.lower() in STD_MENU_NAMES: + continue + ax.action(mbi.id, "AXPress") + time.sleep(0.6) + got = ax.find(role="menu", root_id=mbi.id, max_results=1, max_depth=1) + if got: + return got[0] + _esc(1) + return None + + +def rb_open_preferences(ax): + """app menu -> Preferences.../Settings... (recon: that AXTitle is NOT stable -> keyword).""" + menu = rb_open_app_menu(ax) + if menu is None: + return False + for it in ax.find(role="menu_item", root_id=menu.id, max_results=60, max_depth=1): + low = (it.name or "").lower() + if not low or "services" in low: + continue + if "prefer" in low or "etting" in low: + ok = ax.action(it.id, "AXPress") + time.sleep(1.8) + return bool(ok) + _esc(2) + return False + + +def close_window_via_cancel(ax, win): + if win is None: + _esc(2) + return + c = ax.find(role="button", name="Cancel", root_id=win.id, max_results=3) + hit = [b for b in (c or []) if (b.name or "").strip() == "Cancel"] or list(c or []) + if hit: + ax.action(hit[0].id, "AXPress") + time.sleep(0.9) + else: + _esc(2) + + +def missing(expected, found): + return sorted(set(expected) - set(found)) + + +# --------------------------------------------------------------------------- # +# A) EXISTENCE GATE (depth=0, jump_kind="none") +# --------------------------------------------------------------------------- # + +class TestStructureGate: + + @pytest.mark.rb(depth=0, jump_kind="none") + def test_gate_app_and_main_window(self, ax): + wins = rb_ensure_ui(ax) + root = ax.tree(max_depth=2) or {} + assert isinstance(root, dict) and root, "app is not reachable through the AX API" + assert _norm_role(root.get("role")) == "application", \ + f"AX root role is {root.get('role')!r}, expected an application element" + assert (root.get("children") or []), "application element exposes no AXChildren" + + assert len(wins) == 1, \ + f"expected exactly 1 top-level window on a fresh app, got {len(wins)}: {names(wins)}" + title = (wins[0].name or "").strip() + assert title.lower().startswith(MAIN_WINDOW_PREFIX), \ + f"main window AXTitle {title!r} does not start with 'DB Browser for SQLite'" + + screenshot_assert( + "structure_test_gate_app_and_main_window", + "Dark-themed application window titled 'DB Browser for SQLite'. Top toolbar row: New " + "Database, Open Database (with a dropdown chevron), Write Changes, Revert Changes, " + "Undo, Open Project, Save Project, Attach Database - the last six greyed out. Below " + "it a 4-tab bar: Database Structure (selected), Browse Data, Edit Pragmas, Execute " + "SQL. Left pane: an empty tree with Name / Type / Schema headers and Create Table, " + "Create Index, Modify Table buttons above it. Right side: an 'Edit Database Cell' " + "dock with a 'Mode:' dropdown showing Text, and a 'Remote' dock with an Identity " + "dropdown and DBHub.io / Local / Current Database tabs. Bottom-right dock tab strip: " + "SQL Log, Plot, DB Schema, Remote. Status bar bottom-right reads 'UTF-8'.", + RESULTS_DIR) + + @pytest.mark.rb(depth=0, jump_kind="none") + def test_gate_menu_bar_items(self, ax): + rb_ensure_ui(ax) + bars = role_els(ax, "menu_bar", limit=5) + assert bars, "no menu_bar element exposed by the application" + + found = role_name_set(ax, "menu_bar_item", root_id=bars[0].id, limit=30, max_depth=1) + if not any(n in found for n in TOP_MENUS): + found = role_name_set(ax, "menu_bar_item", limit=30) + assert not missing(TOP_MENUS, found), \ + f"menu bar is missing top-level menus {missing(TOP_MENUS, found)}; found {sorted(found)}" + + @pytest.mark.rb(depth=0, jump_kind="none") + def test_gate_three_tab_bars(self, ax): + rb_ensure_ui(ax) + bars = all_tab_bars(ax) + sets = [set(k) for k in bars.keys()] + for expected, label in ((MAIN_TABS, "main view tab bar"), + (DOCK_TABS, "bottom dock tab bar"), + (REMOTE_TABS, "Remote sub-tab bar")): + assert set(expected) in sets, \ + f"{label} not found: no group owns exactly the radios {expected}; " \ + f"radio groups present: {sorted(tuple(sorted(s)) for s in sets)}" + + main_bar = find_tab_bar(ax, MAIN_TABS) + assert main_bar is not None and (main_bar.name or "").strip() == "Database Structure", \ + f"fresh main tab bar should report AXTitle 'Database Structure', got " \ + f"{getattr(main_bar, 'name', None)!r}" + + screenshot_assert( + "structure_test_gate_three_tab_bars", + "The DB Browser for SQLite window shows three tab strips at once: the main 4-tab bar " + "with Database Structure selected followed by Browse Data, Edit Pragmas, Execute SQL; " + "the bottom-right dock tab strip SQL Log / Plot / DB Schema / Remote with Remote " + "highlighted; and inside the Remote dock panel a sub-tab strip DBHub.io / Local / " + "Current Database with DBHub.io selected above an empty remote file list.", + RESULTS_DIR) + + @pytest.mark.rb(depth=0, jump_kind="none") + def test_gate_toolbar_buttons(self, ax): + rb_ensure_ui(ax) + found = role_name_set(ax, "button", limit=150) + assert not missing(TOOLBAR_BUTTONS, found), \ + f"toolbar buttons missing: {missing(TOOLBAR_BUTTONS, found)}" + assert not missing(STRUCTURE_TOOLBAR_BUTTONS, found), \ + f"Database-Structure toolbar buttons missing: " \ + f"{missing(STRUCTURE_TOOLBAR_BUTTONS, found)}" + + @pytest.mark.rb(depth=0, jump_kind="none") + def test_gate_dock_panel_widgets(self, ax): + rb_ensure_ui(ax) + texts = label_texts(ax) + want = [_norm_text(t) for t in DOCK_LABEL_TEXTS] + gone = [orig for orig, n in zip(DOCK_LABEL_TEXTS, want) if n not in texts] + assert not gone, f"dock panel signature labels missing: {gone}" + + assert find_button(ax, "Clear") is not None, \ + "SQL Log dock button 'Clear' not found" + + enc = [lb for lb in role_els(ax, "label", limit=200) + if _norm_text(lb.name) == "database encoding"] + assert enc, "status bar label 'Database encoding' not found" + blob = f"{enc[0].name or ''} {el_value(ax, enc[0])}" + assert "utf-8" in blob.lower(), \ + f"status bar encoding label should report UTF-8, got {blob!r}" + + @pytest.mark.rb(depth=0, jump_kind="none") + def test_gate_table_column_headers(self, ax): + rb_ensure_ui(ax) + cols = role_name_set(ax, "column", limit=100) + for expected, label in ((STRUCTURE_COLUMNS, "Database Structure / DB Schema tree"), + (REMOTE_COLUMNS, "Remote file list"), + (PLOT_COLUMNS, "Plot column list")): + assert not missing(expected, cols), \ + f"{label} column headers missing {missing(expected, cols)}; " \ + f"columns present: {sorted(cols)}" + + + +# --------------------------------------------------------------------------- # +# B) SHAPE DELTAS (reach / transition, depth >= 1) +# --------------------------------------------------------------------------- # + +class TestStructureShapeDeltas: + + @pytest.mark.rb(depth=1, jump_kind="reach", + expect="Execute SQL tab page: 'Execute line' appears, 'Create Table' gone") + def test_shape_execute_sql_tab(self, ax): + rb_ensure_ui(ax) + before = kit.rb_showing(ax) + assert switch_tab(ax, "Execute SQL"), "could not AXPress the radio 'Execute SQL'" + after = kit.rb_showing(ax) + + assert kit.rb_reach(before, after, + target="button|Execute line", + source="button|Create Table"), \ + "switching to Execute SQL did not surface 'Execute line' while retiring 'Create Table'" + assert len(after) > len(before), \ + f"Execute SQL page should ADD widgets: {len(before)} -> {len(after)} keys" + + btns = role_name_set(ax, "button", limit=150) + assert not missing(EXEC_SQL_BUTTONS, btns), \ + f"Execute SQL toolbar buttons missing: {missing(EXEC_SQL_BUTTONS, btns)}" + checks = role_name_set(ax, "checkbox", limit=60) + assert "Find" in checks, f"Execute SQL 'Find' checkbox missing; checkboxes: {sorted(checks)}" + + screenshot_assert( + "structure_test_shape_execute_sql_tab", + "The Execute SQL tab is now the selected tab in the main 4-tab bar (Database " + "Structure, Browse Data, Edit Pragmas, Execute SQL). The pane shows the SQL editor " + "toolbar with a green triangular Execute SQL button and Execute line (both greyed out " + "because no database is open) plus Stop execution, Open SQL file(s), Save SQL file, " + "New tab, Find or replace and Un/comment block; below it an empty SQL text editor and " + "an empty results area. The Create Table / Create Index / Modify Table tree toolbar of " + "the Database Structure page is no longer visible.", + RESULTS_DIR) + + @pytest.mark.rb(depth=1, jump_kind="reach", + expect="Browse Data tab page: text_field 'Filter in any column' appears, " + "'Create Table' gone") + def test_shape_browse_data_tab(self, ax): + rb_ensure_ui(ax) + before = kit.rb_showing(ax) + assert switch_tab(ax, "Browse Data"), "could not AXPress the radio 'Browse Data'" + after = kit.rb_showing(ax) + + assert kit.rb_reach(before, after, + target="text_field|Filter in any column", + source="button|Create Table"), \ + "Browse Data page did not expose the 'Filter in any column' field / still shows " \ + "'Create Table'" + assert len(after) > len(before), \ + f"Browse Data page should ADD widgets: {len(before)} -> {len(after)} keys" + + fields = role_name_set(ax, "text_field", limit=60) + assert not missing(BROWSE_TEXT_FIELDS, fields), \ + f"Browse Data text fields missing: {missing(BROWSE_TEXT_FIELDS, fields)}; " \ + f"text fields: {sorted(fields)}" + btns = role_name_set(ax, "button", limit=150) + assert not missing(BROWSE_BUTTONS, btns), \ + f"Browse Data buttons missing: {missing(BROWSE_BUTTONS, btns)}" + + @pytest.mark.rb(depth=1, jump_kind="reach", + expect="Edit Pragmas tab page: 'Secure Delete' pragma control appears, " + "'Create Table' gone, >= 30 new widgets") + def test_shape_edit_pragmas_tab(self, ax): + rb_ensure_ui(ax) + before = kit.rb_showing(ax) + assert switch_tab(ax, "Edit Pragmas"), "could not AXPress the radio 'Edit Pragmas'" + after = kit.rb_showing(ax) + + assert kit.rb_reach(before, after, + target="Secure Delete", + source="button|Create Table"), \ + "Edit Pragmas page did not surface the 'Secure Delete' pragma control" + assert len(after) - len(before) >= 30, \ + f"Edit Pragmas page should add >= 30 widgets, got {len(after) - len(before)} " \ + f"({len(before)} -> {len(after)})" + + boxes = [(c.name or "") for c in role_els(ax, "checkbox", limit=80)] + pragma_boxes = [n for n in boxes if any(p in n for p in PRAGMA_CHECKBOX_NAMES)] + assert len(pragma_boxes) >= 8, \ + f"expected >= 8 pragma checkboxes (HTML AXTitles matched by substring), " \ + f"found {len(pragma_boxes)}" + + incs = role_els(ax, "incrementor", limit=40) + assert len(incs) >= 4, f"expected >= 4 pragma incrementors, found {len(incs)}" + + btns = role_name_set(ax, "button", limit=150) + assert not missing(["Save", "Cancel"], btns), \ + f"Edit Pragmas Save/Cancel buttons missing: {missing(['Save', 'Cancel'], btns)}" + + @pytest.mark.rb(depth=1, jump_kind="reach", + expect="dock tab Remote -> DB Schema: group|DB Schema appears, group|Remote " + "gone, dock tab bar AXTitle == 'DB Schema'") + def test_shape_dock_tab_db_schema(self, ax): + rb_ensure_ui(ax) + before = kit.rb_showing(ax) + assert switch_tab(ax, "DB Schema"), "could not AXPress the dock radio 'DB Schema'" + after = kit.rb_showing(ax) + + assert kit.rb_reach(before, after, + target="group|DB Schema", + source="group|Remote"), \ + "dock tab bar did not move from Remote to DB Schema" + + bar = find_tab_bar(ax, DOCK_TABS) + assert bar is not None, f"dock tab bar with radios {DOCK_TABS} disappeared" + assert (bar.name or "").strip() == "DB Schema", \ + f"dock tab bar AXTitle should be 'DB Schema', got {bar.name!r}" + + screenshot_assert( + "structure_test_shape_dock_tab_db_schema", + "The bottom-right dock of the DB Browser for SQLite window now shows a schema tree " + "with the column headers Name / Object / Type / Schema / Database instead of the " + "Remote panel, and 'DB Schema' is the highlighted tab in the SQL Log / Plot / DB " + "Schema / Remote tab strip.", + RESULTS_DIR) + + @pytest.mark.rb(depth=2, jump_kind="reach", + expect="dock tab bar walks Remote->DB Schema->Plot->SQL Log; group|SQL Log " + "appears, group|Plot gone") + def test_shape_dock_tab_plot_then_sql_log(self, ax): + rb_ensure_ui(ax) + assert switch_tab(ax, "DB Schema"), "could not AXPress the dock radio 'DB Schema'" + + before1 = kit.rb_showing(ax) + assert switch_tab(ax, "Plot"), "could not AXPress the dock radio 'Plot'" + after1 = kit.rb_showing(ax) + assert kit.rb_reach(before1, after1, + target="group|Plot", + source="group|DB Schema"), \ + "dock tab bar did not move from DB Schema to Plot" + + before2 = kit.rb_showing(ax) + assert switch_tab(ax, "SQL Log"), "could not AXPress the dock radio 'SQL Log'" + after2 = kit.rb_showing(ax) + assert kit.rb_reach(before2, after2, + target="group|SQL Log", + source="group|Plot"), \ + "dock tab bar did not move from Plot to SQL Log" + + bar = find_tab_bar(ax, DOCK_TABS) + assert bar is not None, f"dock tab bar with radios {DOCK_TABS} disappeared" + assert (bar.name or "").strip() == "SQL Log", \ + f"dock tab bar AXTitle should be 'SQL Log' after the walk, got {bar.name!r}" + + @pytest.mark.rb(depth=1, jump_kind="reach", + expect="File > New In-Memory Database: window|Edit table definition appears, " + "2 windows, main title gains '- In-Memory database'") + def test_shape_new_inmemory_db_opens_table_dialog(self, ax): + rb_ensure_ui(ax) + before = kit.rb_showing(ax) + try: + assert rb_reach_menu_item(ax, "File", "New In-Memory Database"), \ + "could not press the menu item File > New In-Memory Database" + after = kit.rb_showing(ax) + + assert kit.rb_reach(before, after, target="window|Edit table definition"), \ + "'New In-Memory Database' did not open the 'Edit table definition' window" + + wins = ax.find(role="window", max_results=10, max_depth=1) + assert len(wins) == 2, \ + f"expected 2 top-level windows (main + dialog), got {len(wins)}: {names(wins)}" + + mains = [w for w in wins + if (w.name or "").strip().lower().startswith(MAIN_WINDOW_PREFIX)] + assert mains, f"main window vanished; windows: {names(wins)}" + main_title = (mains[0].name or "").strip().lower() + assert "in-memory database" in main_title, \ + f"main window title should become 'DB Browser for SQLite - In-Memory database', " \ + f"got {mains[0].name!r}" + + dlg = find_window(ax, "Edit table definition") + assert dlg is not None, "no window titled 'Edit table definition'" + + fields = role_name_set(ax, "text_field", root_id=dlg.id, limit=40) + assert "Table" in fields, \ + f"dialog is missing the 'Table' name field; text fields: {sorted(fields)}" + boxes = role_name_set(ax, "checkbox", root_id=dlg.id, limit=40) + assert "Advanced" in boxes, \ + f"dialog is missing the 'Advanced' checkbox; checkboxes: {sorted(boxes)}" + + radios = role_name_set(ax, "radio", root_id=dlg.id, limit=20) + assert radios == TABLE_DIALOG_TABS, \ + f"dialog sub-tabs should be {sorted(TABLE_DIALOG_TABS)}, got {sorted(radios)}" + + btns = role_name_set(ax, "button", root_id=dlg.id, limit=60) + assert not missing(TABLE_DIALOG_BUTTONS, btns), \ + f"dialog buttons missing: {missing(TABLE_DIALOG_BUTTONS, btns)}" + + cols = role_name_set(ax, "column", root_id=dlg.id, limit=60) + assert not missing(TABLE_DIALOG_COLUMNS, cols), \ + f"dialog field-grid headers missing: {missing(TABLE_DIALOG_COLUMNS, cols)}; " \ + f"columns: {sorted(cols)}" + + screenshot_assert( + "structure_test_shape_new_inmemory_db_opens_table_dialog", + "A modal window titled 'Edit table definition' is open in front of the DB Browser " + "for SQLite window: it has a 'Table' name field, an 'Advanced' checkbox, a field " + "grid whose headers read Name, Type, NN, PK, AI, U, Default, Check, Collation, " + "Foreign Key, Add / Remove / move-up / move-down buttons, a read-only SQL box " + "showing CREATE TABLE \"\" ( ); , the sub-tabs Fields / Index Constraints / " + "Foreign Keys / Check Constraints, and OK / Cancel buttons. The main window title " + "behind it now reads 'DB Browser for SQLite - In-Memory database'.", + RESULTS_DIR) + finally: + close_window_via_cancel(ax, find_window(ax, "Edit table definition")) + + @pytest.mark.rb(depth=1, jump_kind="reach", + expect="SQL sub-tab 'SQL 1' created by the New tab button") + def test_shape_execute_sql_new_tab_creates_sql1(self, ax): + rb_ensure_ui(ax) + assert switch_tab(ax, "Execute SQL"), "could not AXPress the radio 'Execute SQL'" + + pre = [n for n in role_name_set(ax, "radio", limit=60) if SQL_SUBTAB_RE.match(n or "")] + assert not pre, f"a SQL sub-tab already exists before pressing 'New tab': {sorted(pre)}" + + before = kit.rb_showing(ax) + assert rb_press_button(ax, "New tab", settle=1.4), \ + "could not AXPress the Execute SQL button 'New tab'" + after = kit.rb_showing(ax) + + assert kit.rb_reach(before, after, target="radio|SQL 1"), \ + "'New tab' did not create the SQL sub-tab 'SQL 1'" + + bar = find_tab_bar(ax, ["SQL 1"]) + assert bar is not None, "no tab bar owning exactly the radio 'SQL 1' was created" + assert (bar.name or "").strip() == "SQL 1", \ + f"SQL sub-tab bar AXTitle should be 'SQL 1', got {bar.name!r}" + + @pytest.mark.rb(depth=1, jump_kind="reach", + expect="app menu Preferences.../Settings... opens window|Preferences with the " + "6 tab radios General..Remote as a new top-level surface") + def test_shape_preferences_window_is_new_surface(self, ax): + rb_ensure_ui(ax) + before = kit.rb_showing(ax) + win = None + try: + assert rb_open_preferences(ax), \ + "could not press Preferences.../Settings... in the application menu" + after = kit.rb_showing(ax) + + assert kit.rb_reach(before, after, target="window|Preferences"), \ + "no new 'Preferences' window appeared after the app-menu item was pressed" + + win = find_window(ax, "Preferences") or find_window(ax, "Settings") + assert win is not None, "no top-level window titled Preferences / Settings" + + radios = role_name_set(ax, "radio", root_id=win.id, limit=30) + assert radios == PREFS_TABS, \ + f"Preferences tab radios should be {sorted(PREFS_TABS)}, got {sorted(radios)}" + + btns = role_name_set(ax, "button", root_id=win.id, limit=80) + assert not missing(PREFS_BUTTONS, btns), \ + f"Preferences buttons missing: {missing(PREFS_BUTTONS, btns)}" + + screenshot_assert( + "structure_test_shape_preferences_window_is_new_surface", + "A separate 'Preferences' window is open with a tab strip reading General, " + "Database, Data Browser, SQL, Extensions, Remote (General selected). The General " + "page shows a Language dropdown reading 'English (United States) [System " + "Language]', Font size 13, Max Recent Files 5, several toolbar-style dropdowns, " + "and Save / Cancel / Restore Defaults buttons at the bottom.", + RESULTS_DIR) + finally: + close_window_via_cancel(ax, win or find_window(ax, "Preferences")) diff --git a/macos/sqlitebrowser-sqlitebrowser/tests/test_ax_text.py b/macos/sqlitebrowser-sqlitebrowser/tests/test_ax_text.py new file mode 100644 index 0000000000000000000000000000000000000000..5d329aef94f7c1b46d79a9d8e3d493958ca991a0 --- /dev/null +++ b/macos/sqlitebrowser-sqlitebrowser/tests/test_ax_text.py @@ -0,0 +1,739 @@ +"""AX TEXT-CONTENT lane — DB Browser for SQLite (Qt6). + +Every string asserted here is taken verbatim from recon.md `## TEXT` (T1..T6), with window titles +from T2, column-header texts from T3 and interaction->text deltas from T4/T5. + +Ground rules honoured by this module: + * Visible text of this app lives in `label` elements whose AXTitle is EMPTY and whose AXValue + carries the string -> always read via `ax.get(el.id, ["AXValue"])`. + * Column headers are `column`-role elements read via `el.name`. + * A fresh app has NO DATABASE open; the deterministic, dialog-free way to get one is + `File > New In-Memory Database` + dismissing the auto-opened "Edit table definition" modal + with that window's OWN scoped Cancel button (recon REVEAL_STEPS). + * Build-specific text is NEVER asserted: the About version number + ("... Version 3.13.99 (Aug 11 2026) ... Last commit hash ...") and the `in Nms` / `Took 0ms` + timing digits are forbidden. Only the stable prefixes/sentences are asserted. +""" + +import json +import os +import re +import subprocess +import time + +import pytest +import rb_testgen_kit as kit + +RESULTS_DIR = os.environ.get("RESULTS_DIR", os.path.dirname(os.path.abspath(__file__))) +COUNTER_RE = re.compile(r"^\s*\d+\s*-\s*\d+\s+of\s+\d+\s*$") + + +def screenshot_assert(test_name, description, results_dir): + 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) + + +def _esc(times=1): + for _ in range(times): + subprocess.run(["osascript", "-e", + 'tell application "System Events" to key code 53'], + capture_output=True) + time.sleep(0.3) + + +def _keystroke(text): + subprocess.run(["osascript", "-e", + 'tell application "System Events" to keystroke ' + json.dumps(text)], + capture_output=True) + + +def label_values(ax, root_id=None, limit=350): + """All non-empty AXValue strings of `label` elements.""" + out = [] + for l in ax.find(role="label", max_results=limit, root_id=root_id): + v = ax.get(l.id, ["AXValue"]).get("AXValue") + if isinstance(v, str) and v.strip(): + out.append(v) + return out + + +def label_with(ax, needle, root_id=None): + for v in label_values(ax, root_id=root_id): + if needle in v: + return v + return None + + +def column_names(ax, root_id=None): + return [c.name for c in ax.find(role="column", max_results=120, root_id=root_id) if c.name] + + +def open_menu(ax, top): + mb = ax.find(role="menu_bar_item", name=top, max_results=1) + if not mb: + return None + ax.action(mb[0].id, "AXPress") + time.sleep(0.6) + m = ax.find(role="menu", root_id=mb[0].id, max_results=1, max_depth=1) + return m[0] if m else None + + +def rb_reach_menu_item(ax, top, item_name): + m = open_menu(ax, top) + if m is None: + return False + for it in ax.find(role="menu_item", root_id=m.id, max_results=80, max_depth=1): + if (it.name or "") == item_name: + ok = ax.action(it.id, "AXPress") + time.sleep(1.4) + return bool(ok) + _esc(2) + return False + + +def find_window(ax, title_substr): + for w in ax.find(role="window", max_results=10, max_depth=1): + if title_substr.lower() in (w.name or "").lower(): + return w + return None + + +def main_window(ax): + wid = ax.get_main_window() + return None if wid is None else ax.get(wid, ["AXTitle"]).get("AXTitle") + + +def rb_enter_inmemory_db(ax): + """File > New In-Memory Database, then dismiss the auto-opened table dialog.""" + rb_reach_menu_item(ax, "File", "New In-Memory Database") + w = find_window(ax, "Edit table definition") + if w is not None: + c = ax.find(role="button", name="Cancel", root_id=w.id, max_results=2) + if c: + ax.action(c[0].id, "AXPress") + time.sleep(1.0) + return find_window(ax, "Edit table definition") is None + + +def switch_tab(ax, name, root_id=None): + r = ax.find(role="radio", name=name, max_results=1, root_id=root_id) + if not r: + return False + ok = ax.action(r[0].id, "AXPress") + time.sleep(1.0) + return bool(ok) + + +def find_button(ax, name, root_id=None): + for b in ax.find(role="button", max_results=90, root_id=root_id): + if (b.name or "") == name: + return b + return None + + +def enabled(ax, el): + return bool(ax.get(el.id, ["AXEnabled"]).get("AXEnabled")) + + +def sql_editor(ax): + for t in ax.find(role="text_area", max_results=15): + if not ax.is_attribute_settable(t.id, "AXValue"): + continue + v = str(ax.get(t.id, ["AXValue"]).get("AXValue") or "") + if "PRAGMA" in v or "EXECUTING" in v: + continue + return t + return None + + +def run_sql(ax, sql): + switch_tab(ax, "Execute SQL") + e = sql_editor(ax) + assert e is not None, "SQL editor not found" + ax.click_element_cg(e.id) + time.sleep(0.35) + subprocess.run(["osascript", "-e", + 'tell application "System Events" to keystroke "a" using command down'], + capture_output=True) + time.sleep(0.25) + _keystroke(sql) + time.sleep(0.5) + b = find_button(ax, "Execute SQL") + assert b is not None and enabled(ax, b), "Execute SQL button not enabled" + ax.action(b.id, "AXPress") + time.sleep(1.9) + + +def result_cells(ax): + cols, cells = [], [] + for t in ax.find(role="table", max_results=10): + if (t.name or "") == "search result": + continue + ch = (ax.tree(max_depth=3, root_id=t.id).get("children") or []) + c = [x.get("name") for x in ch if x.get("role") == "column"] + v = [x.get("name") for x in ch if x.get("role") == "label"] + if c or v: + cols, cells = c, v + return cols, cells + + +def exec_msg(ax): + for t in ax.find(role="text_area", max_results=15): + v = str(ax.get(t.id, ["AXValue"]).get("AXValue") or "") + if v.startswith("Execution finished"): + return v + return "" + + +def record_counter(ax): + """MUST use the regex — a plain ' of ' test also matches + 'Identification of the cell currently in the editor'.""" + for l in ax.find(role="label", max_results=350): + v = str(ax.get(l.id, ["AXValue"]).get("AXValue") or "") + if COUNTER_RE.match(v): + return v.strip() + return None + + +def grid_cell_named(ax, name): + for t in ax.find(role="table", max_results=10): + if (t.name or "") == "search result": + continue + for c in ax.find(role="label", root_id=t.id, max_results=40, max_depth=1): + if (c.name or "") == name: + return c + return None + + +# -------------------------------------------------------------------------------------------- +# extra text-lane helpers (built on the primitives above) +# -------------------------------------------------------------------------------------------- + +def ensure_ui(ax): + """Reveal the app's UI before any window/text inspection. + + recon REVEAL_STEPS: this is a REGULAR windowed app — the main window is already on screen at + launch (no status item / LSUIElement path). So the only reveal needed is to raise it; a + recreation that hides the window behind another surface still reports truthfully because the + assertions below run against whatever `get_main_window()` yields. + """ + wid = ax.get_main_window() + if wid is not None: + try: + ax.action(wid, "AXRaise") + except Exception: + pass + time.sleep(0.2) + return wid + + +def label_strings(ax, root_id=None, limit=350): + """AXValue *and* AXTitle strings of `label` elements. + + The reference puts dialog prose in AXValue; a differently-built recreation may legitimately + expose the same visible text as the label's AXTitle, so dialog scans consider both. + """ + out = [] + for l in ax.find(role="label", max_results=limit, root_id=root_id): + v = ax.get(l.id, ["AXValue"]).get("AXValue") + if isinstance(v, str) and v.strip(): + out.append(v) + if l.name and l.name.strip(): + out.append(l.name) + return out + + +def text_area_values(ax, root_id=None): + out = [] + for t in ax.find(role="text_area", max_results=15, root_id=root_id): + v = ax.get(t.id, ["AXValue"]).get("AXValue") + out.append(v if isinstance(v, str) else "") + return out + + +def text_area_containing(ax, needle): + for v in text_area_values(ax): + if needle in v: + return v + return "" + + +def press_menu_item_startswith(ax, top, prefix): + """Same scoping discipline as rb_reach_menu_item, but matches on a title PREFIX. + + Needed for the app menu's About item (recon MENUS: 'About DB Browser for SQLite').""" + m = open_menu(ax, top) + if m is None: + return False + for it in ax.find(role="menu_item", root_id=m.id, max_results=80, max_depth=1): + if (it.name or "").startswith(prefix): + ok = ax.action(it.id, "AXPress") + time.sleep(1.4) + return bool(ok) + _esc(2) + return False + + +def dialog_containing_text(ax, needle): + """Locate a secondary surface by its VISIBLE TEXT (never by index/path). + + Returns (window_element, matching_text) or (None, None).""" + for w in ax.find(role="window", max_results=10, max_depth=1): + if (w.name or "").startswith("DB Browser for SQLite"): + continue # the main window (fresh or '... - In-Memory database') + for v in label_strings(ax, root_id=w.id, limit=80): + if needle in v: + return w, v + return None, None + + +def close_dialog(ax, win, button_name="Cancel"): + """Always dismiss with the dialog's OWN scoped button (recon: never a global Cancel).""" + if win is None: + return False + b = find_button(ax, button_name, root_id=win.id) + if b is None: + _esc(1) + return False + ok = ax.action(b.id, "AXPress") + time.sleep(1.0) + return bool(ok) + + +def table_grid(ax, want_col=None): + """result_cells() but able to prefer the grid that owns a given column header.""" + best = ([], []) + for t in ax.find(role="table", max_results=10): + if (t.name or "") == "search result": + continue # 1x5px decoy table (recon COMPUTATION) + ch = (ax.tree(max_depth=3, root_id=t.id).get("children") or []) + c = [x.get("name") for x in ch if x.get("role") == "column"] + v = [x.get("name") for x in ch if x.get("role") == "label"] + if want_col is not None and want_col in c: + return c, v + if c or v: + best = (c, v) + return best + + +# ---- exact texts from recon ## TEXT --------------------------------------------------------- + +T1_STATIC_LABELS = [ + "Mode:", + "Show SQL submitted by", + "Line type:", + "Point shape:", + "Identity", + "Identification of the cell currently in the editor", + "Type and size of data currently in table", +] + +STRUCTURE_HEADERS = ["Name", "Object", "Type", "Schema", "Database"] +REMOTE_HEADERS = ["Name", "Last modified", "Size", "Commit"] +PLOT_HEADERS = ["Columns", "X", "Y1", "Y2", "Axis Type"] +TABLE_DIALOG_HEADERS = ["Name", "Type", "NN", "PK", "AI", "U", + "Default", "Check", "Collation", "Foreign Key"] + +INTEGRITY_TEXT = ("This action will open a new SQL tab for running:\n" + "PRAGMA integrity_check;\n" + "Press Help for opening the corresponding SQLite reference page.") + +ABOUT_DESC = ("DB Browser for SQLite is an open source, freeware visual tool used to create, " + "design and edit SQLite") + +RESULTS_HELP = "Results of the last executed statements." + +SQL_LOG_HEAD = "PRAGMA foreign_keys = '1';" + +PRAGMA_DISPLAY_LABELS = [ + "Auto Vacuum", "Automatic Index", "Case Sensitive Like", "Checkpoint Full FSYNC", + "Foreign Keys", "Full FSYNC", "Ignore Check Constraints", "Journal Mode", + "Journal Size Limit", "Locking Mode", "Max Page Count", "Page Size", + "Recursive Triggers", "Secure Delete", "Synchronous", "Temp Store", + "User Version", "WAL Auto Checkpoint", +] + +MAKE_NUMS = ("CREATE TABLE nums(n INTEGER, label TEXT); " + "INSERT INTO nums VALUES(10,'ten'),(20,'twenty'),(30,'thirty');") + + +class TestStaticText: + """T1/T3 — text that must be readable on a freshly launched app (NO database).""" + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="labels 'Mode:', 'Show SQL submitted by', 'Line type:', " + "'Point shape:', 'Identity', 'Identification of the cell currently in " + "the editor', 'Type and size of data currently in table' all present " + "with those exact AXValues") + def test_static_label_texts_on_fresh_app(self, ax): + ensure_ui(ax) + values = label_values(ax) + + # every text-bearing label read must be non-empty by construction + assert values, "no `label` element on the fresh app exposes a non-empty AXValue" + assert all(v.strip() for v in values), "collected a blank label value" + + found = set(values) + missing = [s for s in T1_STATIC_LABELS if s not in found] + assert not missing, f"missing exact label AXValues {missing}; observed={sorted(found)}" + + # tolerant proof on the SQL-log dock caption (recon T1) + assert kit.rb_value(values, "Show SQL submitted by"), \ + f"'Show SQL submitted by' not among label values: {sorted(found)}" + + # character count must match the actual text length for each asserted label + for s in T1_STATIC_LABELS: + actual = [v for v in values if v == s][0] + assert len(actual) == len(s), f"length mismatch for {s!r}: {len(actual)} != {len(s)}" + + screenshot_assert( + "text_test_static_labels_fresh", + "Dark-themed window titled 'DB Browser for SQLite' on a fresh launch with no database. " + "The 'Edit Database Cell' dock on the right shows the caption 'Mode:' next to a " + "dropdown reading Text plus the two placeholder lines 'Identification of the cell " + "currently in the editor' and 'Type and size of data currently in table'. The SQL Log " + "dock shows 'Show SQL submitted by' with an 'Application' dropdown and a Clear button; " + "the Plot dock shows 'Line type:' and 'Point shape:'; the Remote dock shows 'Identity' " + "with a 'Select an identity to connect' dropdown and DBHub.io / Local / Current " + "Database tabs. Main tab bar reads Database Structure (selected), Browse Data, Edit " + "Pragmas, Execute SQL. Status bar bottom-right reads 'UTF-8'.", + RESULTS_DIR) + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="status-bar label named 'Database encoding' has AXValue 'UTF-8'") + def test_status_bar_database_encoding_utf8(self, ax): + ensure_ui(ax) + target = None + for l in ax.find(role="label", max_results=350): + if (l.name or "") == "Database encoding": + target = l + break + assert target is not None, "status-bar label named 'Database encoding' not found" + + value = ax.get(target.id, ["AXValue"]).get("AXValue") + assert isinstance(value, str) and value.strip(), \ + f"status bar text is empty: {value!r}" + assert value == "UTF-8", f"expected status bar 'UTF-8', got {value!r}" + assert kit.rb_value(value, "UTF-8"), f"rb_value rejected status bar text {value!r}" + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="column headers include the structure-tree set " + "{Name,Object,Type,Schema,Database}, the remote set " + "{Name,Last modified,Size,Commit} and the plot set " + "{Columns,X,Y1,Y2,Axis Type}") + def test_column_header_texts_on_fresh_app(self, ax): + ensure_ui(ax) + headers = column_names(ax) + assert headers, "no `column` element exposes a header name" + got = set(headers) + + assert set(STRUCTURE_HEADERS).issubset(got), \ + f"structure-tree headers missing {sorted(set(STRUCTURE_HEADERS) - got)}; got {sorted(got)}" + assert set(REMOTE_HEADERS).issubset(got), \ + f"remote-list headers missing {sorted(set(REMOTE_HEADERS) - got)}; got {sorted(got)}" + assert set(PLOT_HEADERS).issubset(got), \ + f"plot-list headers missing {sorted(set(PLOT_HEADERS) - got)}; got {sorted(got)}" + + assert kit.rb_value(headers, "Axis Type"), \ + f"'Axis Type' header not observed; got {sorted(got)}" + + +class TestWindowTitleText: + """T2 — window-title text, fresh and after the in-memory database is created.""" + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="window title 'DB Browser for SQLite' -> " + "'DB Browser for SQLite - In-Memory database'") + def test_main_window_title_fresh_and_after_opening_database(self, ax): + ensure_ui(ax) + before = main_window(ax) + assert before == "DB Browser for SQLite", \ + f"fresh main window title should be 'DB Browser for SQLite', got {before!r}" + assert "DB Browser for SQLite" in (before or ""), "frame title lacks the app name" + + assert rb_enter_inmemory_db(ax), "'Edit table definition' modal was not dismissed" + + after = main_window(ax) + assert after != before, f"window title did not change after creating a database: {after!r}" + assert after == "DB Browser for SQLite - In-Memory database", \ + f"expected '<document> - <app>' title format, got {after!r}" + assert kit.rb_value(after, "DB Browser for SQLite - In-Memory database"), \ + f"rb_value rejected the title {after!r}" + + +class TestPanelText: + """T5 — long prose owned by docks / panels (needs a database).""" + + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="SQL Log dock text_area AXValue starts with \"PRAGMA foreign_keys = " + "'1';\" and lists PRAGMA database_list and the sqlite_master query") + def test_sql_log_shows_startup_pragmas(self, ax): + ensure_ui(ax) + assert rb_enter_inmemory_db(ax), "could not create the in-memory database" + assert switch_tab(ax, "SQL Log"), "SQL Log dock tab radio not pressable" + + log = text_area_containing(ax, "PRAGMA") + assert log, f"no text_area holds the SQL log; panes={text_area_values(ax)!r}" + assert log.startswith(SQL_LOG_HEAD), \ + f"SQL log should start with {SQL_LOG_HEAD!r}, got {log[:80]!r}" + assert "PRAGMA database_list;" in log, f"SQL log lacks PRAGMA database_list: {log!r}" + assert 'SELECT type,name,sql,tbl_name FROM "main".sqlite_master;' in log, \ + f"SQL log lacks the sqlite_master query: {log!r}" + assert kit.rb_value(log, "PRAGMA database_list;"), f"rb_value rejected the log {log[:80]!r}" + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="Edit Database Cell shows 'No cell active.' and " + "'Type: NULL; Size: 0 bytes' once a database is open") + def test_cell_editor_status_labels_with_database(self, ax): + ensure_ui(ax) + before = label_values(ax) + assert "Identification of the cell currently in the editor" in before, \ + ("fresh cell-editor panel should carry the placeholder " + f"'Identification of the cell currently in the editor'; got {sorted(set(before))}") + + assert rb_enter_inmemory_db(ax), "could not create the in-memory database" + after = label_values(ax) + + assert "No cell active." in after, \ + f"cell editor should read 'No cell active.' with a DB open; got {sorted(set(after))}" + assert "Type: NULL; Size: 0 bytes" in after, \ + f"cell editor should read 'Type: NULL; Size: 0 bytes'; got {sorted(set(after))}" + assert set(after) != set(before), "no cell-editor text changed after opening the database" + assert kit.rb_value(after, "Type: NULL; Size: 0 bytes"), \ + "rb_value rejected the cell-editor type/size line" + + +class TestDialogText: + """Text that only exists on a surface this test opened (depth >= 1).""" + + + @pytest.mark.rb(depth=1, jump_kind="value", + expect='About window shows "DB Browser for SQLite is an open source, freeware ' + 'visual tool used to create, design and edit SQLite" and a label ' + 'containing "DB Browser for SQLite Version"') + def test_about_dialog_description_text(self, ax): + ensure_ui(ax) + assert press_menu_item_startswith(ax, "DB Browser for SQLite", "About"), \ + "app menu > About ... could not be pressed" + + win = find_window(ax, "About DB Browser for SQLite") + try: + assert win is not None, "no 'About DB Browser for SQLite' window appeared" + assert (win.name or "") == "About DB Browser for SQLite", \ + f"About window title should be 'About DB Browser for SQLite', got {win.name!r}" + + texts = label_strings(ax, root_id=win.id, limit=60) + assert any(ABOUT_DESC in t for t in texts), \ + f"About window lacks the description sentence; observed={texts!r}" + # version LINE only — the version NUMBER / commit hash are build-specific. + assert any("DB Browser for SQLite Version" in t for t in texts), \ + f"About window lacks a 'DB Browser for SQLite Version' line; observed={texts!r}" + assert kit.rb_value(texts, ABOUT_DESC), "rb_value rejected the About description" + + screenshot_assert( + "text_test_about_dialog", + "A small window titled 'About DB Browser for SQLite' showing the app logo image, a " + "version line beginning 'DB Browser for SQLite Version', the sentence 'DB Browser " + "for SQLite is an open source, freeware visual tool used to create, design and " + "edit SQLite', and a Close button.", + RESULTS_DIR) + finally: + close_dialog(ax, win, "Close") # the About window's own Close button + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="Edit table definition dialog exposes column headers Name,Type,NN,PK," + "AI,U,Default,Check,Collation,Foreign Key") + def test_dialog_column_header_texts(self, ax): + ensure_ui(ax) + # press the menu item directly so the auto-opened modal is still on screen to inspect + assert rb_reach_menu_item(ax, "File", "New In-Memory Database"), \ + "File > New In-Memory Database could not be pressed" + + dialog = find_window(ax, "Edit table definition") + try: + assert dialog is not None, "'Edit table definition' dialog did not appear" + headers = column_names(ax, root_id=dialog.id) + assert headers, "the dialog's field grid exposes no column header text" + got = set(headers) + assert set(TABLE_DIALOG_HEADERS).issubset(got), \ + (f"dialog headers missing {sorted(set(TABLE_DIALOG_HEADERS) - got)}; " + f"got {headers!r}") + assert kit.rb_value(headers, "Collation"), \ + f"'Collation' header not observed; got {headers!r}" + finally: + close_dialog(ax, dialog, "Cancel") # scoped Cancel, never a global one + + +class TestComputedText: + """T4/T5 — text PRODUCED by executing SQL (message pane + results grid).""" + + @pytest.mark.rb(depth=1, jump_kind="value", + expect='message pane starts "Execution finished without errors." and contains ' + '"1 rows returned" and "SELECT 2+3 AS total;"') + def test_sql_execution_message_text_success(self, ax): + ensure_ui(ax) + assert rb_enter_inmemory_db(ax), "could not create the in-memory database" + run_sql(ax, "SELECT 2+3 AS total;") + + msg = exec_msg(ax) + assert msg, f"message pane is empty; panes={text_area_values(ax)!r}" + assert msg.startswith("Execution finished without errors."), \ + f"unexpected message prefix: {msg!r}" + assert "1 rows returned" in msg, f"message lacks '1 rows returned': {msg!r}" + assert "At line 1:" in msg, f"message lacks 'At line 1:': {msg!r}" + assert "SELECT 2+3 AS total;" in msg, f"message does not echo the statement: {msg!r}" + assert kit.rb_value(msg, "Execution finished without errors."), \ + "rb_value rejected the success message" + + cols, cells = result_cells(ax) + assert "total" in cols, f"results grid header should read 'total'; got {cols!r}" + assert kit.rb_value(cells, "5"), f"results grid should show '5'; got {cells!r}" + + screenshot_assert( + "text_test_sql_message_success", + "Execute SQL tab active in the 'DB Browser for SQLite - In-Memory database' window. " + "The SQL editor holds the statement SELECT 2+3 AS total; a results grid below shows a " + "single column headed 'total' containing the value 5, and the message pane reads " + "'Execution finished without errors.' followed by 'Result: 1 rows returned in ...' and " + "'At line 1: SELECT 2+3 AS total;'.", + RESULTS_DIR) + + @pytest.mark.rb(depth=1, jump_kind="value", + expect='message pane starts "Execution finished with errors." and contains ' + '"no such table: no_such_table_xyz"') + def test_sql_execution_message_text_error(self, ax): + ensure_ui(ax) + assert rb_enter_inmemory_db(ax), "could not create the in-memory database" + run_sql(ax, "SELECT * FROM no_such_table_xyz;") + + msg = exec_msg(ax) + assert msg, f"message pane is empty; panes={text_area_values(ax)!r}" + assert msg.startswith("Execution finished with errors."), \ + f"unexpected message prefix: {msg!r}" + assert "no such table: no_such_table_xyz" in msg, \ + f"message lacks the sqlite error text: {msg!r}" + assert kit.rb_value(msg, "no such table: no_such_table_xyz"), \ + "rb_value rejected the error message" + + cols, _cells = result_cells(ax) + assert cols == [], f"results grid should stay empty on error; got columns {cols!r}" + + +class TestGridText: + """T3/T4 — Browse Data grid text, record counter, and the cell-editor identification line.""" + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="grid columns ['_rowid_','n','label'], cell texts include " + "'ten'/'twenty'/'thirty' and counter '1 - 3 of 3'") + def test_browse_data_grid_text_and_counter(self, ax): + ensure_ui(ax) + assert rb_enter_inmemory_db(ax), "could not create the in-memory database" + run_sql(ax, MAKE_NUMS) + assert switch_tab(ax, "Browse Data"), "Browse Data tab radio not pressable" + + cols, cells = table_grid(ax, want_col="_rowid_") + assert cols == ["_rowid_", "n", "label"], \ + f"expected columns ['_rowid_','n','label']; got {cols!r}" + for want in ["ten", "twenty", "thirty", "10", "20", "30"]: + assert want in cells, f"grid cell text {want!r} missing; cells={cells!r}" + assert kit.rb_value(cells, "twenty"), f"rb_value rejected the cells {cells!r}" + + counter = record_counter(ax) + assert counter == "1 - 3 of 3", f"record counter should read '1 - 3 of 3'; got {counter!r}" + + screenshot_assert( + "text_test_browse_data_grid", + "Browse Data tab active with a 'Table:' dropdown reading nums. The data grid shows " + "columns _rowid_, n and label with the rows 10/ten, 20/twenty and 30/thirty, a 'Filter " + "in any column' box under the headers, and the record counter reading '1 - 3 of 3'.", + RESULTS_DIR) + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="clicking grid cell 'twenty' changes the cell-editor labels to " + "'Editing row=2, column=2' and 'Type: Text / Numeric; Size: 6 " + "character(s)' with the editor holding 'twenty'") + def test_cell_click_updates_editor_identification_text(self, ax): + ensure_ui(ax) + assert rb_enter_inmemory_db(ax), "could not create the in-memory database" + run_sql(ax, MAKE_NUMS) + assert switch_tab(ax, "Browse Data"), "Browse Data tab radio not pressable" + + before_vals = label_values(ax) + before = next((v for v in before_vals if "Editing row=" in v), None) + + cell = grid_cell_named(ax, "twenty") + assert cell is not None, "grid cell with the text 'twenty' not found" + ax.click_element_cg(cell.id) + time.sleep(1.2) + + after_vals = label_values(ax) + ident = next((v for v in after_vals if "Editing row=" in v), None) + assert ident is not None, \ + f"no cell-editor identification label after the click; labels={sorted(set(after_vals))}" + assert "Editing row=2" in ident, f"identification text should name row 2; got {ident!r}" + assert "column=" in ident, f"identification text should name a column; got {ident!r}" + if before is not None: + assert ident != before, f"identification text did not change from {before!r}" + + type_line = next((v for v in after_vals if v.startswith("Type: ")), None) + assert type_line is not None, \ + f"no 'Type: ...' size line after the click; labels={sorted(set(after_vals))}" + assert "character(s)" in type_line, \ + f"type/size line should report character(s) for a text cell; got {type_line!r}" + + editor_value = next((v for v in text_area_values(ax) if v == "twenty"), None) + assert editor_value == "twenty", \ + f"cell editor should hold exactly 'twenty'; panes={text_area_values(ax)!r}" + assert kit.rb_value(editor_value, "twenty"), "rb_value rejected the cell editor text" + + +class TestPragmaText: + """T6 — pragma display labels (plain `label`s that end with the object-replacement glyph).""" + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="Edit Pragmas tab shows the 18 pragma display labels (Auto Vacuum, " + "Automatic Index, ..., WAL Auto Checkpoint)") + def test_pragma_display_labels_present(self, ax): + ensure_ui(ax) + assert switch_tab(ax, "Edit Pragmas"), "Edit Pragmas tab radio not pressable" + + values = label_values(ax) + assert values, "Edit Pragmas page exposes no label text" + + found, missing = [], [] + for name in PRAGMA_DISPLAY_LABELS: + # recon T6: the value carries a trailing 'what's this' glyph -> startswith, never == + hit = next((v for v in values if v.startswith(name)), None) + (found if hit is not None else missing).append(name) + assert not missing, f"pragma display labels missing {missing}; got {sorted(set(values))}" + + found_count = len(found) + assert found_count == 18, f"expected 18 pragma labels, found {found_count}" + assert kit.rb_value(found_count, 18), f"rb_value rejected the pragma label count {found_count}" + + screenshot_assert( + "text_test_pragma_labels", + "Edit Pragmas tab active, showing a form of SQLite pragma controls whose visible " + "labels read Auto Vacuum, Automatic Index, Case Sensitive Like, Checkpoint Full FSYNC, " + "Foreign Keys, Full FSYNC, Ignore Check Constraints, Journal Mode, Journal Size Limit, " + "Locking Mode, Max Page Count, Page Size, Recursive Triggers, Secure Delete, " + "Synchronous, Temp Store, User Version and WAL Auto Checkpoint, with Save and Cancel " + "buttons at the bottom of the page.", + RESULTS_DIR) diff --git a/macos/sqlitebrowser-sqlitebrowser/tests/testcase_counts.json b/macos/sqlitebrowser-sqlitebrowser/tests/testcase_counts.json new file mode 100644 index 0000000000000000000000000000000000000000..8e1ff662b616dc150e516d6515f2ad69dfdebe22 --- /dev/null +++ b/macos/sqlitebrowser-sqlitebrowser/tests/testcase_counts.json @@ -0,0 +1,50 @@ +{ + "ax_total": 89, + "vlm_total": 27, + "ax_by_lane": { + "test_ax_buttons.py": 15, + "test_ax_computation.py": 16, + "test_ax_menus.py": 15, + "test_ax_states.py": 16, + "test_ax_structure.py": 14, + "test_ax_text.py": 13 + }, + "vlm_by_dir": { + "buttons": 4, + "computation": 5, + "menus": 7, + "states": 4, + "structure": 4, + "text": 3 + }, + "vlm_names": [ + "buttons_clear_filters_filtered.png", + "buttons_execute_sql_result.png", + "buttons_new_record_counter.png", + "buttons_toolbar_fresh_state.png", + "computation_test_create_table_preview.png", + "computation_test_filter_narrows_grid.png", + "computation_test_sql_error_no_such_table.png", + "computation_test_sql_multiplication.png", + "computation_test_structure_counts.png", + "menus_about_dialog.png", + "menus_file_menu.png", + "menus_integrity_check_confirm.png", + "menus_integrity_check_result.png", + "menus_new_inmemory_table_dialog.png", + "menus_preferences_general.png", + "menus_view_menu_checkmarks.png", + "states_test_dock_tab_selection.png", + "states_test_main_tab_bar_selection.png", + "states_test_preferences_extensions_tab.png", + "states_test_view_menu_checkmarks.png", + "structure_test_gate_app_and_main_window.png", + "structure_test_gate_three_tab_bars.png", + "structure_test_shape_execute_sql_tab.png", + "structure_test_shape_preferences_window_is_new_surface.png", + "text_test_about_dialog.png", + "text_test_browse_data_grid.png", + "text_test_sql_message_success.png" + ], + "frozen_at": "stage2_finalize" +} \ No newline at end of file diff --git a/macos/sqlitebrowser-sqlitebrowser/tests/verifier_helpers.py b/macos/sqlitebrowser-sqlitebrowser/tests/verifier_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..ce369cdae8db3a7427890d1636f8f5a3201dbef1 --- /dev/null +++ b/macos/sqlitebrowser-sqlitebrowser/tests/verifier_helpers.py @@ -0,0 +1,753 @@ +""" +verifier_helpers.py — High-level AX testing patterns for macOS app verification. + +v6 core library. Encodes all robust testing patterns as reusable functions +so verifier agents call high-level APIs instead of building from scratch. + +Depends on: ax_helpers.py (AXHelper class) +""" + +import datetime +import os +import re +import signal +import subprocess +import time +from collections import Counter + +# --------------------------------------------------------------------------- +# Key codes (macOS virtual key codes) +# --------------------------------------------------------------------------- +KC_LEFT_ARROW = 123 +KC_RIGHT_ARROW = 124 +KC_UP_ARROW = 126 +KC_DOWN_ARROW = 125 +KC_SPACE = 49 +KC_RETURN = 36 +KC_TAB = 48 +KC_ESCAPE = 53 +KC_Q = 12 +KC_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)" + ) diff --git a/macos/sqlitebrowser-sqlitebrowser/vlm_assertions.json b/macos/sqlitebrowser-sqlitebrowser/vlm_assertions.json new file mode 100644 index 0000000000000000000000000000000000000000..12f8b7fd2fc5dc91727b81a3edf4600348c2a940 --- /dev/null +++ b/macos/sqlitebrowser-sqlitebrowser/vlm_assertions.json @@ -0,0 +1,374 @@ +{ + "schema_version": 2, + "instance_id": "macos/sqlitebrowser-sqlitebrowser", + "grading": { + "mode": "deferred", + "model": null, + "scored_separately": true + }, + "totals": { + "assertions": 27, + "with_verdict": 0, + "calibrated": 0, + "usable": null, + "scored_records": 0, + "unbacked_records": 0 + }, + "assertions": [ + { + "id": "buttons_toolbar_fresh_state.png", + "screenshot": "buttons_toolbar_fresh_state.png", + "assertion": "DB Browser for SQLite main window, no database open. Top toolbar row shows New Database and Open Database (Open Database has a dropdown chevron) as active icons, while Write Changes, Revert Changes, Undo, Open Project (active), Save Project and Attach Database follow — Write Changes, Revert Changes, Undo, Save Project and Attach Database are greyed out/disabled. Below the toolbar a 4-tab bar reads Database Structure (selected), Browse Data, Edit Pragmas, Execute SQL, and above the empty schema tree the Create Table, Create Index and Modify Table buttons are also greyed out. Right side shows the Edit Database Cell dock with a Mode: dropdown reading Text and the Remote dock; bottom dock tab strip reads SQL Log, Plot, DB Schema, Remote; status bar bottom-right reads UTF-8.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "buttons_toolbar_fresh_state.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "buttons_execute_sql_result.png", + "screenshot": "buttons_execute_sql_result.png", + "assertion": "DB Browser for SQLite with the in-memory database open and the Execute SQL tab active. The SQL editor holds the statement SELECT 7*6 AS answer; the Execute toolbar (green play icon plus Execute line, Stop, open/save SQL, New tab, find and comment icons) sits above it with Execute now enabled, the results grid below shows a single column headed 'answer' containing the value 42, and the message pane reads 'Execution finished without errors. Result: 1 rows returned in ...'.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "buttons_execute_sql_result.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "buttons_new_record_counter.png", + "screenshot": "buttons_new_record_counter.png", + "assertion": "DB Browser for SQLite, Browse Data tab active on the in-memory database. A 'Table:' dropdown reads nums, the data grid has columns _rowid_, n, label with the rows 10/ten, 20/twenty, 30/thirty plus a newly inserted empty row at the bottom, a 'Filter in any column' box sits under the headers, and the record navigation strip (|< < > >| and Go to:) with the record counter now reads '1 - 4 of 4' after the New Record button was pressed.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "buttons_new_record_counter.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "buttons_clear_filters_filtered.png", + "screenshot": "buttons_clear_filters_filtered.png", + "assertion": "DB Browser for SQLite, Browse Data tab on table nums with a filter applied: the 'Filter in any column' box contains the text twenty, the data grid (columns _rowid_, n, label) shows only ONE visible row 20 / twenty, the record counter reads '1 - 1 of 1', and the Clear Filters button in the toolbar strip is now enabled (no longer greyed out).", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "buttons_clear_filters_filtered.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "computation_test_sql_multiplication.png", + "screenshot": "computation_test_sql_multiplication.png", + "assertion": "DB Browser for SQLite with the Execute SQL tab active. The SQL editor holds 'SELECT 7*6 AS answer;' and the results grid below it shows one column headed 'answer' containing the value 42 (7*6). The message pane under the grid reads 'Execution finished without errors. Result: 1 rows returned ...'.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "computation_test_sql_multiplication.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "computation_test_sql_error_no_such_table.png", + "screenshot": "computation_test_sql_error_no_such_table.png", + "assertion": "DB Browser for SQLite, Execute SQL tab active. The editor holds 'SELECT * FROM no_such_table_xyz;'. The results grid is EMPTY (no columns, no rows) and the message pane reports the SQLite error: 'Execution finished with errors. Result: no such table: no_such_table_xyz'.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "computation_test_sql_error_no_such_table.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "computation_test_create_table_preview.png", + "screenshot": "computation_test_create_table_preview.png", + "assertion": "The modal window 'Edit table definition' is open in front of the DB Browser for SQLite main window. Its 'Table' name box contains 'people', the field grid (headers Name, Type, NN, PK, AI, U, Default, Check, Collation, Foreign Key) is still empty, and the read-only SQL preview box below shows CREATE TABLE \"people\" ( ); Fields / Index Constraints / Foreign Keys / Check Constraints tabs and OK / Cancel buttons are visible.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "computation_test_create_table_preview.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "computation_test_structure_counts.png", + "screenshot": "computation_test_structure_counts.png", + "assertion": "DB Browser for SQLite with the Database Structure tab active. The schema tree now lists 'Tables (1)' expanded/containing an entry named 'nums', alongside 'Indices (0)', 'Views (0)' and 'Triggers (0)'; the Create Table / Create Index / Modify Table buttons sit above the tree.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "computation_test_structure_counts.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "computation_test_filter_narrows_grid.png", + "screenshot": "computation_test_filter_narrows_grid.png", + "assertion": "DB Browser for SQLite, Browse Data tab active on table 'nums'. The filter box under the column headers contains 'twenty', so the grid shows only ONE row (20 / twenty) out of three, the record counter reads '1 - 1 of 1', and the 'Clear Filters' toolbar button is now enabled.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "computation_test_filter_narrows_grid.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "menus_file_menu.png", + "screenshot": "menus_file_menu.png", + "assertion": "The macOS menu bar shows 'DB Browser for SQLite File Edit View Tools Help' and the File menu is dropped down listing New Database..., New In-Memory Database, Open Database..., Open Database Read Only..., Attach Database..., Recent Files, Save Database As..., Close Database, Write Changes, Revert Changes, Undo, Import, Export, Open Project..., Save Project, Save Project As..., Close Project, Save All — most of them greyed out because no database is open.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "menus_file_menu.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "menus_view_menu_checkmarks.png", + "screenshot": "menus_view_menu_checkmarks.png", + "assertion": "The View dropdown lists SQL Log, Plot, DB Schema, Edit Database Cell, Remote, DB Toolbar, Extra DB Toolbar, Project Toolbar, Database Structure, Browse Data, Edit Pragmas, Execute SQL — each with a checkmark — plus a 'Window Layout' submenu and 'Enter Full Screen'.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "menus_view_menu_checkmarks.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "menus_new_inmemory_table_dialog.png", + "screenshot": "menus_new_inmemory_table_dialog.png", + "assertion": "A modal window titled 'Edit table definition' is in front of the main window: a 'Table' name field, an 'Advanced' checkbox, a field grid headed Name, Type, NN, PK, AI, U, Default, Check, Collation, Foreign Key, Add/Remove/move buttons, a read-only SQL box showing CREATE TABLE \"\" ( ); tabs Fields / Index Constraints / Foreign Keys / Check Constraints, and OK / Cancel buttons.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "menus_new_inmemory_table_dialog.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "menus_integrity_check_confirm.png", + "screenshot": "menus_integrity_check_confirm.png", + "assertion": "A modal alert in front of the DB Browser for SQLite window with a warning icon and the text 'This action will open a new SQL tab for running: PRAGMA integrity_check; Press Help for opening the corresponding SQLite reference page.' plus OK / Cancel / Help buttons.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "menus_integrity_check_confirm.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "menus_integrity_check_result.png", + "screenshot": "menus_integrity_check_result.png", + "assertion": "The Execute SQL tab is active with TWO sub-tabs ('SQL 1' and 'Integrity Check*'), the editor holds PRAGMA integrity_check; and a results grid whose single column 'integrity_check' contains the value ok.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "menus_integrity_check_result.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "menus_about_dialog.png", + "screenshot": "menus_about_dialog.png", + "assertion": "A small window titled 'About DB Browser for SQLite' showing the app logo image, a version line beginning 'DB Browser for SQLite Version', the sentence 'DB Browser for SQLite is an open source, freeware visual tool used to create, design and edit SQLite', and a Close button.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "menus_about_dialog.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "menus_preferences_general.png", + "screenshot": "menus_preferences_general.png", + "assertion": "A separate 'Preferences' window with a tab strip General, Database, Data Browser, SQL, Extensions, Remote (General selected), a Language dropdown reading 'English (United States) [System Language]', Font size 13, Max Recent Files 5, toolbar-style dropdowns, and Save / Cancel / Restore Defaults buttons.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "menus_preferences_general.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "states_test_main_tab_bar_selection.png", + "screenshot": "states_test_main_tab_bar_selection.png", + "assertion": "DB Browser for SQLite main window with the 4-tab bar Database Structure / Browse Data / Edit Pragmas / Execute SQL. The walk ended back on Database Structure, so that tab is the highlighted/selected one and the left pane shows the empty object tree with Create Table, Create Index and Modify Table buttons above it (all greyed out, no database open).", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "states_test_main_tab_bar_selection.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "states_test_dock_tab_selection.png", + "screenshot": "states_test_dock_tab_selection.png", + "assertion": "The bottom-right dock of DB Browser for SQLite. Its tab strip reads SQL Log / Plot / DB Schema / Remote and SQL Log is now the highlighted (selected) tab, so the dock body shows the SQL log text pane with the 'Show SQL submitted by' dropdown (Application) and a Clear button — the Remote panel is no longer displayed.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "states_test_dock_tab_selection.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "states_test_view_menu_checkmarks.png", + "screenshot": "states_test_view_menu_checkmarks.png", + "assertion": "The View menu of DB Browser for SQLite is open in the macOS menu bar. It lists SQL Log, Plot, DB Schema, Edit Database Cell, Remote, DB Toolbar, Extra DB Toolbar, Project Toolbar, Database Structure, Browse Data, Edit Pragmas and Execute SQL — every one of those 12 entries shows a checkmark on its left — plus a 'Window Layout' submenu and 'Enter Full Screen' with no checkmark.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "states_test_view_menu_checkmarks.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "states_test_preferences_extensions_tab.png", + "screenshot": "states_test_preferences_extensions_tab.png", + "assertion": "A separate Preferences window of DB Browser for SQLite, in front of the main window. Its tab strip reads General, Database, Data Browser, SQL, Extensions, Remote and 'Extensions' is now the selected tab, so the page shows the SQLite extension list with Add/Remove extension buttons and the checkboxes for disabling the Regular Expression extension and allowing extension loading from SQL code. Save, Cancel and Restore Defaults buttons are at the bottom.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "states_test_preferences_extensions_tab.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "structure_test_shape_execute_sql_tab.png", + "screenshot": "structure_test_shape_execute_sql_tab.png", + "assertion": "The Execute SQL tab is now the selected tab in the main 4-tab bar (Database Structure, Browse Data, Edit Pragmas, Execute SQL). The pane shows the SQL editor toolbar with a green triangular Execute SQL button and Execute line (both greyed out because no database is open) plus Stop execution, Open SQL file(s), Save SQL file, New tab, Find or replace and Un/comment block; below it an empty SQL text editor and an empty results area. The Create Table / Create Index / Modify Table tree toolbar of the Database Structure page is no longer visible.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "structure_test_shape_execute_sql_tab.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "structure_test_shape_preferences_window_is_new_surface.png", + "screenshot": "structure_test_shape_preferences_window_is_new_surface.png", + "assertion": "A separate 'Preferences' window is open with a tab strip reading General, Database, Data Browser, SQL, Extensions, Remote (General selected). The General page shows a Language dropdown reading 'English (United States) [System Language]', Font size 13, Max Recent Files 5, several toolbar-style dropdowns, and Save / Cancel / Restore Defaults buttons at the bottom.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "structure_test_shape_preferences_window_is_new_surface.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "structure_test_gate_app_and_main_window.png", + "screenshot": "structure_test_gate_app_and_main_window.png", + "assertion": "Dark-themed application window titled 'DB Browser for SQLite'. Top toolbar row: New Database, Open Database (with a dropdown chevron), Write Changes, Revert Changes, Undo, Open Project, Save Project, Attach Database - the last six greyed out. Below it a 4-tab bar: Database Structure (selected), Browse Data, Edit Pragmas, Execute SQL. Left pane: an empty tree with Name / Type / Schema headers and Create Table, Create Index, Modify Table buttons above it. Right side: an 'Edit Database Cell' dock with a 'Mode:' dropdown showing Text, and a 'Remote' dock with an Identity dropdown and DBHub.io / Local / Current Database tabs. Bottom-right dock tab strip: SQL Log, Plot, DB Schema, Remote. Status bar bottom-right reads 'UTF-8'.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "structure_test_gate_app_and_main_window.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "structure_test_gate_three_tab_bars.png", + "screenshot": "structure_test_gate_three_tab_bars.png", + "assertion": "The DB Browser for SQLite window shows three tab strips at once: the main 4-tab bar with Database Structure selected followed by Browse Data, Edit Pragmas, Execute SQL; the bottom-right dock tab strip SQL Log / Plot / DB Schema / Remote with Remote highlighted; and inside the Remote dock panel a sub-tab strip DBHub.io / Local / Current Database with DBHub.io selected above an empty remote file list.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "structure_test_gate_three_tab_bars.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "text_test_about_dialog.png", + "screenshot": "text_test_about_dialog.png", + "assertion": "A small window titled 'About DB Browser for SQLite' showing the app logo image, a version line beginning 'DB Browser for SQLite Version', the sentence 'DB Browser for SQLite is an open source, freeware visual tool used to create, design and edit SQLite', and a Close button.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "text_test_about_dialog.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "text_test_sql_message_success.png", + "screenshot": "text_test_sql_message_success.png", + "assertion": "Execute SQL tab active in the 'DB Browser for SQLite - In-Memory database' window. The SQL editor holds the statement SELECT 2+3 AS total; a results grid below shows a single column headed 'total' containing the value 5, and the message pane reads 'Execution finished without errors.' followed by 'Result: 1 rows returned in ...' and 'At line 1: SELECT 2+3 AS total;'.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "text_test_sql_message_success.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "text_test_browse_data_grid.png", + "screenshot": "text_test_browse_data_grid.png", + "assertion": "Browse Data tab active with a 'Table:' dropdown reading nums. The data grid shows columns _rowid_, n and label with the rows 10/ten, 20/twenty and 30/thirty, a 'Filter in any column' box under the headers, and the record counter reading '1 - 3 of 3'.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "text_test_browse_data_grid.png", + "rigor": null, + "verdict": null, + "calibration": null + } + ], + "merged_from_files": 6, + "source_shapes": { + "dict_str": 27 + } +} \ No newline at end of file diff --git a/macos/stefansl-image-shrinker/LICENSE.md b/macos/stefansl-image-shrinker/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..b823bcc448f6fd5263abd6bda85d1e40afda9b33 --- /dev/null +++ b/macos/stefansl-image-shrinker/LICENSE.md @@ -0,0 +1,39 @@ +CC0 1.0 Universal +================== + +Statement of Purpose +--------------------- + +The laws of most jurisdictions throughout the world automatically confer exclusive Copyright and Related Rights (defined below) upon the creator and subsequent owner(s) (each and all, an "owner") of an original work of authorship and/or a database (each, a "Work"). + +Certain owners wish to permanently relinquish those rights to a Work for the purpose of contributing to a commons of creative, cultural and scientific works ("Commons") that the public can reliably and without fear of later claims of infringement build upon, modify, incorporate in other works, reuse and redistribute as freely as possible in any form whatsoever and for any purposes, including without limitation commercial purposes. These owners may contribute to the Commons to promote the ideal of a free culture and the further production of creative, cultural and scientific works, or to gain reputation or greater distribution for their Work in part through the use and efforts of others. + +For these and/or other purposes and motivations, and without any expectation of additional consideration or compensation, the person associating CC0 with a Work (the "Affirmer"), to the extent that he or she is an owner of Copyright and Related Rights in the Work, voluntarily elects to apply CC0 to the Work and publicly distribute the Work under its terms, with knowledge of his or her Copyright and Related Rights in the Work and the meaning and intended legal effect of CC0 on those rights. + +1. Copyright and Related Rights. +-------------------------------- +A Work made available under CC0 may be protected by copyright and related or neighboring rights ("Copyright and Related Rights"). Copyright and Related Rights include, but are not limited to, the following: + +i. the right to reproduce, adapt, distribute, perform, display, communicate, and translate a Work; +ii. moral rights retained by the original author(s) and/or performer(s); +iii. publicity and privacy rights pertaining to a person's image or likeness depicted in a Work; +iv. rights protecting against unfair competition in regards to a Work, subject to the limitations in paragraph 4(a), below; +v. rights protecting the extraction, dissemination, use and reuse of data in a Work; +vi. database rights (such as those arising under Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, and under any national implementation thereof, including any amended or successor version of such directive); and +vii. other similar, equivalent or corresponding rights throughout the world based on applicable law or treaty, and any national implementations thereof. + +2. Waiver. +----------- +To the greatest extent permitted by, but not in contravention of, applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and unconditionally waives, abandons, and surrenders all of Affirmer's Copyright and Related Rights and associated claims and causes of action, whether now known or unknown (including existing as well as future claims and causes of action), in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each member of the public at large and to the detriment of Affirmer's heirs and successors, fully intending that such Waiver shall not be subject to revocation, rescission, cancellation, termination, or any other legal or equitable action to disrupt the quiet enjoyment of the Work by the public as contemplated by Affirmer's express Statement of Purpose. + +3. Public License Fallback. +---------------------------- +Should any part of the Waiver for any reason be judged legally invalid or ineffective under applicable law, then the Waiver shall be preserved to the maximum extent permitted taking into account Affirmer's express Statement of Purpose. In addition, to the extent the Waiver is so judged Affirmer hereby grants to each affected person a royalty-free, non transferable, non sublicensable, non exclusive, irrevocable and unconditional license to exercise Affirmer's Copyright and Related Rights in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "License"). The License shall be deemed effective as of the date CC0 was applied by Affirmer to the Work. Should any part of the License for any reason be judged legally invalid or ineffective under applicable law, such partial invalidity or ineffectiveness shall not invalidate the remainder of the License, and in such case Affirmer hereby affirms that he or she will not (i) exercise any of his or her remaining Copyright and Related Rights in the Work or (ii) assert any associated claims and causes of action with respect to the Work, in either case contrary to Affirmer's express Statement of Purpose. + +4. Limitations and Disclaimers. +-------------------------------- + +a. No trademark or patent rights held by Affirmer are waived, abandoned, surrendered, licensed or otherwise affected by this document. +b. Affirmer offers the Work as-is and makes no representations or warranties of any kind concerning the Work, express, implied, statutory or otherwise, including without limitation warranties of title, merchantability, fitness for a particular purpose, non infringement, or the absence of latent or other defects, accuracy, or the present or absence of errors, whether or not discoverable, all to the greatest extent permissible under applicable law. +c. Affirmer disclaims responsibility for clearing rights of other persons that may apply to the Work or any use thereof, including without limitation any person's Copyright and Related Rights in the Work. Further, Affirmer disclaims responsibility for obtaining any necessary consents, permissions or other rights required for any use of the Work. +d. Affirmer understands and acknowledges that Creative Commons is not a party to this document and has no duty or obligation with respect to this CC0 or use of the Work. diff --git a/macos/stefansl-image-shrinker/instance.json b/macos/stefansl-image-shrinker/instance.json new file mode 100644 index 0000000000000000000000000000000000000000..430e738e72142eab38718dae30bfc20177fedc6d --- /dev/null +++ b/macos/stefansl-image-shrinker/instance.json @@ -0,0 +1,10 @@ +{ + "schema_version": 1, + "instance_id": "macos/stefansl-image-shrinker", + "platform": "macos", + "repo": "https://github.com/stefansl/image-shrinker", + "commit": "259f9a1e22e98b08a170c8ef55716e17e9855dca", + "patches": [], + "package": null, + "license": null +} \ No newline at end of file diff --git a/macos/stefansl-image-shrinker/reference/build.sh b/macos/stefansl-image-shrinker/reference/build.sh new file mode 100644 index 0000000000000000000000000000000000000000..f724151b02de9561ddf04403e3353998dd63dd27 --- /dev/null +++ b/macos/stefansl-image-shrinker/reference/build.sh @@ -0,0 +1,92 @@ +#!/usr/bin/env bash +# +# Standalone, reproducible build for "Image Shrinker" (Electron desktop app). +# MANUALLY FIXED (mingkang): the upstream repo has NO package-lock, so `npm install` +# drifts and a rebuilt app can throw a JS error. Fixes: +# * pin electron + electron-builder to exact versions (deterministic) +# * asarUnpack the native image binaries (mozjpeg/pngquant-bin/gifsicle) so +# execFile() can actually run them at runtime (they can't exec from inside asar) +# * remove the notarize afterSign hook (no Apple creds) +# All package.json edits are done in one idempotent node pass. +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd "$SCRIPT_DIR" + +APP_NAME="Image Shrinker" +APP_OUT="${APP_OUTPUT_DIR:-$SCRIPT_DIR}" + +echo "==> Building '$APP_NAME' in $SCRIPT_DIR" + +# 1. Node.js / npm (idempotent) +if ! command -v node >/dev/null 2>&1 || ! command -v npm >/dev/null 2>&1; then + echo "==> installing node via Homebrew"; brew install node +fi +echo "==> Using Node $(node --version) / npm $(npm --version)" + +# 2. Idempotent package.json fixes: drop afterSign, pin build tools, asarUnpack native bins. +echo "==> Patching package.json (pin versions, asarUnpack native binaries, drop notarize)" +node -e ' +const fs=require("fs"); const p=JSON.parse(fs.readFileSync("package.json","utf8")); +p.build=p.build||{}; +delete p.build.afterSign; +p.build.asar=true; +// electron-builder default npmRebuild=true re-runs each package install script +// at pack time — for mozjpeg that RE-DOWNLOADS (and wipes) the vendor binary we +// just placed. Disable it so our brew-provided cjpeg/pngquant/gifsicle survive. +p.build.npmRebuild=false; +const unpack="**/node_modules/{mozjpeg,pngquant-bin,gifsicle}/**"; +p.build.asarUnpack=Array.isArray(p.build.asarUnpack)?p.build.asarUnpack:(p.build.asarUnpack?[p.build.asarUnpack]:[]); +if(!p.build.asarUnpack.includes(unpack)) p.build.asarUnpack.push(unpack); +p.devDependencies=p.devDependencies||{}; +p.devDependencies.electron="10.4.7"; +p.devDependencies["electron-builder"]="22.14.13"; +// Electron 10 ships Node 12 (no fs/promises). Pin electron-* runtime deps to +// their Node-12-compatible versions so drift does not pull fs/promises users. +p.dependencies=p.dependencies||{}; +p.dependencies["electron-updater"]="4.3.1"; +p.dependencies["electron-log"]="4.2.2"; +p.dependencies["electron-settings"]="4.0.2"; +fs.writeFileSync("package.json", JSON.stringify(p,null,2)); +console.log(" asarUnpack:",p.build.asarUnpack.join(", ")); +' + +# 3. Install deps (pinned electron/electron-builder now exact) +echo "==> npm install" +npm install + +# 4. Provide native image binaries via Homebrew (the npm packages download them +# from a CDN that the build sandbox cannot reach → cjpeg/pngquant/gifsicle end +# up missing → "spawn ... ENOENT" at runtime). brew IS reachable here, so +# install the tools and drop them into the exact vendor/ paths the app spawns. +echo "==> Installing native image binaries via brew" +brew install mozjpeg pngquant gifsicle || true +CJPEG="$(brew --prefix mozjpeg 2>/dev/null)/bin/cjpeg"; [ -x "$CJPEG" ] || CJPEG="$(command -v cjpeg || true)" +PNGQ="$(command -v pngquant || true)"; [ -x "$PNGQ" ] || PNGQ="$(brew --prefix pngquant 2>/dev/null)/bin/pngquant" +GIFS="$(command -v gifsicle || true)"; [ -x "$GIFS" ] || GIFS="$(brew --prefix gifsicle 2>/dev/null)/bin/gifsicle" +place_bin() { # $1=dest relpath $2=src binary + local dest="node_modules/$1" src="$2" + if [ -n "$src" ] && [ -x "$src" ]; then + mkdir -p "$(dirname "$dest")"; cp -f "$src" "$dest"; chmod +x "$dest" + echo " placed $dest <- $src" + else + echo "ERROR: no usable binary for $dest (src='$src')" >&2; return 1 + fi +} +place_bin "mozjpeg/vendor/cjpeg" "$CJPEG" +place_bin "pngquant-bin/vendor/pngquant" "$PNGQ" +place_bin "gifsicle/vendor/gifsicle" "$GIFS" + +# 5. Build unpacked, unsigned .app +export CI=true +export CSC_IDENTITY_AUTO_DISCOVERY=false +export ELECTRON_BUILDER_CACHE="$SCRIPT_DIR/.cache-electron-builder" +echo "==> electron-builder (unpacked, unsigned, npmRebuild off)" +./node_modules/.bin/electron-builder build --mac --dir -c.mac.identity=null -c.npmRebuild=false + +# 6. Copy the finished .app to output +SRC_APP="$SCRIPT_DIR/dist/mac/$APP_NAME.app" +[ -d "$SRC_APP" ] || { echo "ERROR: electron-builder did not produce '$SRC_APP'" >&2; exit 1; } +mkdir -p "$APP_OUT"; DEST_APP="$APP_OUT/$APP_NAME.app" +if [ "$SRC_APP" != "$DEST_APP" ]; then rm -rf "$DEST_APP"; ditto "$SRC_APP" "$DEST_APP"; fi +echo "==> Build complete: $DEST_APP" diff --git a/macos/stefansl-image-shrinker/reference/launch.sh b/macos/stefansl-image-shrinker/reference/launch.sh new file mode 100644 index 0000000000000000000000000000000000000000..17f917a6b23b96ce75e13a398b4e00ef3e9af028 --- /dev/null +++ b/macos/stefansl-image-shrinker/reference/launch.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +APP_NAME="Image Shrinker" +candidates=() +[ -n "${APP_OUTPUT_DIR:-}" ] && candidates+=("$APP_OUTPUT_DIR/$APP_NAME.app") +candidates+=("$SCRIPT_DIR/$APP_NAME.app" "$SCRIPT_DIR/dist/mac/$APP_NAME.app") +APP="" +for c in "${candidates[@]}"; do [ -d "$c" ] && { APP="$c"; break; }; done +[ -n "$APP" ] || { echo "ERROR: could not find '$APP_NAME.app'." >&2; exit 1; } +BIN="$APP/Contents/MacOS/$APP_NAME" +[ -x "$BIN" ] || { echo "ERROR: app executable not found: $BIN" >&2; exit 1; } +echo "Launching: $APP" +exec "$BIN" --force-renderer-accessibility "$@" diff --git a/macos/stefansl-image-shrinker/tests/ax_helpers.py b/macos/stefansl-image-shrinker/tests/ax_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..2418d7b8c75891c2d08906848d6a36517cb98135 --- /dev/null +++ b/macos/stefansl-image-shrinker/tests/ax_helpers.py @@ -0,0 +1,849 @@ +import os +import re +import time +import warnings +import subprocess +from dataclasses import dataclass, field +from typing import Optional +from 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", +} + + +@dataclass +class 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 None diff --git a/macos/stefansl-image-shrinker/tests/conftest.py b/macos/stefansl-image-shrinker/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..21a9b7debd04c0633d77a60d8269102790a13e84 --- /dev/null +++ b/macos/stefansl-image-shrinker/tests/conftest.py @@ -0,0 +1,584 @@ +""" +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 json +import os +import signal +import subprocess +import tempfile +import 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.fixture +def app_process(app_path): + pid = _launch_app(app_path) + yield pid + _kill_pid(pid) + + +@pytest.fixture +def 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.fixture +def 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")) diff --git a/macos/stefansl-image-shrinker/tests/fixtures/sample.gif b/macos/stefansl-image-shrinker/tests/fixtures/sample.gif new file mode 100644 index 0000000000000000000000000000000000000000..d59d40ecf620695f8ec643afeec2ec0b3904b25c --- /dev/null +++ b/macos/stefansl-image-shrinker/tests/fixtures/sample.gif @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ace627b3033fac0f45dcb2d09ab4ea87c4096404b0a149af4f812ffa566e6ca1 +size 6390 diff --git a/macos/stefansl-image-shrinker/tests/fixtures/sample.jpg b/macos/stefansl-image-shrinker/tests/fixtures/sample.jpg new file mode 100644 index 0000000000000000000000000000000000000000..9c7b8159e7f6a84b946b226d3a6dfee8bd09beb1 --- /dev/null +++ b/macos/stefansl-image-shrinker/tests/fixtures/sample.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2b95b481d532f67c9607649111bdd81558c016a0cf0bbd8d8432328a081dca6f +size 2000 diff --git a/macos/stefansl-image-shrinker/tests/fixtures/sample.png b/macos/stefansl-image-shrinker/tests/fixtures/sample.png new file mode 100644 index 0000000000000000000000000000000000000000..4c9c16fdf1b5af65953d0d803bd5accb577cacc9 --- /dev/null +++ b/macos/stefansl-image-shrinker/tests/fixtures/sample.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d7ab764ee4580317cccfae20fe1602e73d51536752ba0fc2417262ad6dc287b6 +size 43388 diff --git a/macos/stefansl-image-shrinker/tests/fixtures/sample.svg b/macos/stefansl-image-shrinker/tests/fixtures/sample.svg new file mode 100644 index 0000000000000000000000000000000000000000..54d7f2e587039041494fa55900cdd0c035981fdf --- /dev/null +++ b/macos/stefansl-image-shrinker/tests/fixtures/sample.svg @@ -0,0 +1,13 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- a deliberately verbose svg so svgo has something to strip --> +<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200" viewBox="0 0 200 200" version="1.1"> + + <title>Sample + Sample shape used by the Image Shrinker verifier fixtures. + + + + + Shrink me + + diff --git a/macos/stefansl-image-shrinker/tests/imgshrink_helpers.py b/macos/stefansl-image-shrinker/tests/imgshrink_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..3a982c8ba13839d95d38fdf944f1021bf0ff3e02 --- /dev/null +++ b/macos/stefansl-image-shrinker/tests/imgshrink_helpers.py @@ -0,0 +1,780 @@ +"""Shared AX helpers for the Image Shrinker verifier suite. + +Portable by construction: everything is discovered from the RUNNING app through the +`ax` fixture (AXHelper) — no install paths, no bundle ids, no DOM ids hardcoded as the +only strategy. Every lookup is keyword/geometry based with layered fallbacks so the +SAME test drives the reference app and a recreation that names things differently. + +Vocabulary used by the suite +--------------------------- +main surface the app's main window: the drop zone ("Drag files here") + result list +settings pane the slide-in panel with the 6 preference toggles ("Settings" heading) +result line one entry of the result list: "You saved N%. …" + the output file path +""" +from __future__ import annotations + +import json +import math +import os +import re +import shutil +import subprocess +import tempfile +import time + +import ApplicationServices as _AS + +# ── settling times (Electron renderer needs a beat after every interaction) ── +CLICK_SETTLE = 0.35 +TOGGLE_SETTLE = 0.6 +NAV_SETTLE = 0.9 + +# Keyword sets — a recreation may word a label differently, so match on keywords. +KW_SAME_FOLDER = ["same folder", "same directory", "gleichen ordner", "同一"] +KW_NOTIFICATION = ["notification", "notif", "benachricht", "通知"] +KW_SUFFIX = [".min", "suffix", "后缀"] +KW_SUBFOLDER = ["subfolder", "minified", "sub folder", "unterordner", "子文件夹"] +KW_CLEARLIST = ["clear result", "clear list", "clearlist", "清空"] +KW_UPDATECHECK = ["update", "aktualis", "更新"] +SETTING_KEYWORDS = [KW_SAME_FOLDER, KW_NOTIFICATION, KW_SUFFIX, + KW_SUBFOLDER, KW_CLEARLIST, KW_UPDATECHECK] +# DOM ids the reference app uses (Chromium exposes them via AXDOMIdentifier). Used +# only as a *fallback* pairing strategy, never as the primary locator. +DOM_ORDER = ["folderswitch", "notification", "suffix", "subfolder", + "clearlist", "updatecheck"] +DOM_FOR_KW = {id(KW_SAME_FOLDER): "folderswitch", id(KW_NOTIFICATION): "notification", + id(KW_SUFFIX): "suffix", id(KW_SUBFOLDER): "subfolder", + id(KW_CLEARLIST): "clearlist", id(KW_UPDATECHECK): "updatecheck"} + +KW_SETTINGS_TRIGGER = ["setting", "preference", "prefs", "options", "config", + "gear", "more", "einstell", "设置"] +KW_DROPZONE = ["drag", "drop", "ziehen", "拖"] +SAVED_RE = re.compile(r"(\d+)\s*%") +MENU_KEY_ESCAPE = 53 +MENU_KEY_RETURN = 36 + + +# ──────────────────────────────────────────────────────────────────────────── +# AX plumbing +# ──────────────────────────────────────────────────────────────────────────── +def ensure_ax_ready(ax, timeout=15.0): + """Make the app's real content reachable through AX, then return True. + + Chromium/Electron apps expose an EMPTY window subtree until an assistive client + asks them to turn accessibility on (the app is otherwise only inspectable when it + was launched with --force-renderer-accessibility). Requesting + AXManualAccessibility / AXEnhancedUserInterface on the application element is the + documented AT handshake; it is a harmless no-op for a native app, which already + exposes its widgets. Poll until the window actually has content. + """ + def _content(): + return (len(ax.find(role="checkbox", max_results=1, max_depth=8)) + + len(ax.find(role="webarea", max_results=1, max_depth=6)) + + len(ax.find_text_elements(max_results=4))) + + if _content() >= 3: + return True + for attr in ("AXManualAccessibility", "AXEnhancedUserInterface"): + try: + _AS.AXUIElementSetAttributeValue(ax._app_ref, attr, True) + except Exception: + pass + deadline = time.time() + timeout + while time.time() < deadline: + if _content() >= 3: + return True + time.sleep(0.3) + return _content() > 0 + + +def _nums(v): + return [float(x) for x in re.findall(r"[-\d.]+", str(v))][-2:] if v is not None else [] + + +def frame(ax, el): + """[x, y, w, h] in screen points, or None.""" + d = ax.get(el.id, ["AXPosition", "AXSize"]) + p, s = _nums(d.get("AXPosition")), _nums(d.get("AXSize")) + return (p + s) if len(p) == 2 and len(s) == 2 else None + + +def windows(ax): + return ax.find(role="window", max_depth=1, max_results=10) + + +def main_window(ax): + """The app's main window element (largest / AXMain), or None.""" + wid = ax.get_main_window() + for w in windows(ax): + if w.id == wid: + return w + ws = windows(ax) + return ws[0] if ws else None + + +def window_frames(ax): + out = [] + for w in windows(ax): + f = frame(ax, w) + if f: + out.append(f) + return out + + +def is_visible(ax, el, wframes=None): + """True when the element has a real (non-collapsed) frame that sits on one of the + app's windows. The reference app keeps the whole settings pane in the tree at all + times and merely collapses it to a 1x1 box off the window edge, so PRESENCE alone + proves nothing — visibility must be measured.""" + f = frame(ax, el) + if not f or f[2] <= 1 or f[3] <= 1: + return False + if wframes is None: + wframes = window_frames(ax) + cx, cy = f[0] + f[2] / 2.0, f[1] + f[3] / 2.0 + for wx, wy, ww, wh in wframes: + if wx - 2 <= cx <= wx + ww + 2 and wy - 2 <= cy <= wy + wh + 2: + return True + return False + + +# "webarea" is the Electron web DOCUMENT container: its AX text is the document +# TITLE ("Image Shrinker"), not on-screen content, and it only started showing up +# once the launcher gained --force-renderer-accessibility. Counting it made every +# visible-text count one too high (home 3 vs 2, settings pane 11 vs 10), which is +# what failed the structure/text shape tests on the reference app itself. +_SKIP_ROLES = ("menu_item", "menu_bar_item", "menu", "menu_bar", "application", + "webarea", "web_area") + + +def visible_texts(ax, max_results=250): + """All on-screen text of the app (window titles excluded), as a list of strings.""" + wframes = window_frames(ax) + out = [] + for el in ax.find_text_elements(max_results=max_results): + if el.role in _SKIP_ROLES or el.role == "window": + continue + if is_visible(ax, el, wframes): + out.append(el.text) + return out + + +def visible_set(ax): + """{"role|text"} of everything currently on screen — the before/after snapshot a + reach test compares. Unlike kit.rb_showing this is VISIBILITY based, which is what + an in-window slide-in panel changes.""" + wframes = window_frames(ax) + out = set() + for el in ax.find_text_elements(max_results=250): + if el.role in _SKIP_ROLES: + continue + if is_visible(ax, el, wframes): + out.add(f"{el.role}|{el.text}") + for w in windows(ax): + out.add(f"window|{w.name or ''}") + return out + + +def rb_reach_appear(before, after, target, source=None): + """Surface-jump verdict on VISIBLE sets: `target` newly appeared (and `source`, if + given, went away). Same contract as kit.rb_reach but measured on visibility.""" + before, after = set(before or []), set(after or []) + t = str(target).lower() + appeared = any(t in k.lower() for k in (after - before)) + if source is None: + return appeared + s = str(source).lower() + return appeared and any(s in k.lower() for k in before) and not any( + s in k.lower() for k in after) + + +def rb_reach_gone(before, after, target): + """Left-the-surface verdict: `target` was visible before and is gone after.""" + before, after = set(before or []), set(after or []) + t = str(target).lower() + return any(t in k.lower() for k in before) and not any(t in k.lower() for k in after) + + +def find_visible_text(ax, keywords): + """First VISIBLE text element whose content matches any keyword (ci).""" + if isinstance(keywords, str): + keywords = [keywords] + wframes = window_frames(ax) + for el in ax.find_text_elements(max_results=250): + if el.role in _SKIP_ROLES: + continue + low = (el.text or "").lower() + if any(k.lower() in low for k in keywords) and is_visible(ax, el, wframes): + return el + return None + + +def text_is_visible(ax, keywords): + return find_visible_text(ax, keywords) is not None + + +def dom_id(ax, el): + return ax.get(el.id, ["AXDOMIdentifier"]).get("AXDOMIdentifier") or "" + + +def send_key(keycode, modifiers=None): + import Quartz + src = Quartz.CGEventSourceCreate(Quartz.kCGEventSourceStateHIDSystemState) + down = Quartz.CGEventCreateKeyboardEvent(src, keycode, True) + up = Quartz.CGEventCreateKeyboardEvent(src, keycode, False) + flags = 0 + for mod in (modifiers or []): + flags |= {"cmd": Quartz.kCGEventFlagMaskCommand, + "shift": Quartz.kCGEventFlagMaskShift, + "alt": Quartz.kCGEventFlagMaskAlternate, + "ctrl": Quartz.kCGEventFlagMaskControl}.get(mod, 0) + if flags: + Quartz.CGEventSetFlags(down, flags) + Quartz.CGEventSetFlags(up, flags) + Quartz.CGEventPost(Quartz.kCGHIDEventTap, down) + Quartz.CGEventPost(Quartz.kCGHIDEventTap, up) + time.sleep(0.25) + + +def click_at(x, y): + import Quartz + pt = Quartz.CGPointMake(x, y) + for kind in (Quartz.kCGEventLeftMouseDown, Quartz.kCGEventLeftMouseUp): + Quartz.CGEventPost(Quartz.kCGHIDEventTap, + Quartz.CGEventCreateMouseEvent(None, kind, pt, + Quartz.kCGMouseButtonLeft)) + time.sleep(0.05) + time.sleep(CLICK_SETTLE) + + +def focus_main_window(ax): + """Give the main window keyboard focus without touching any control: raise it and + click an empty area low in the window (the drop zone sits in the upper third and + would open a file chooser). Menu commands that talk to the focused window need + this.""" + w = main_window(ax) + if w is None: + return False + ax.action(w.id, "AXRaise") + f = frame(ax, w) + if f: + click_at(f[0] + f[2] * 0.5, f[1] + f[3] * 0.80) + return True + + +# ──────────────────────────────────────────────────────────────────────────── +# Settings pane +# ──────────────────────────────────────────────────────────────────────────── +def settings_open(ax): + """True when the settings pane is on screen: >=2 of its preference labels visible.""" + hits = 0 + for kws in SETTING_KEYWORDS: + if text_is_visible(ax, kws): + hits += 1 + if hits >= 2: + return True + return False + + +def settings_trigger(ax): + """The control that reveals the settings pane (the '⋯' glyph in the reference app), + found by DOM id / name / help keywords over everything pressable.""" + cands = [] + for el in ax.find_clickable(max_results=60): + if el.role in ("menu_item", "menu_bar_item"): + continue + blob = " ".join(str(x) for x in ( + dom_id(ax, el), el.name or "", + ax.get(el.id, ["AXHelp"]).get("AXHelp") or "", + ax.get(el.id, ["AXRoleDescription"]).get("AXRoleDescription") or "")) + low = blob.lower() + if "close" in low or "quit" in low: + continue + if any(k in low for k in KW_SETTINGS_TRIGGER): + cands.append(el) + return cands[0] if cands else None + + +def rb_enter_settings(ax): + """Open the settings pane from the main surface. Multi-strategy so a recreation + that wires it to a button, a menu item or ⌘, is still driven by the same test. + Returns True when the pane is on screen.""" + ensure_ax_ready(ax) + if settings_open(ax): + return True + + el = settings_trigger(ax) + if el is not None: + ax.action(el.id, "AXPress") + time.sleep(NAV_SETTLE) + if settings_open(ax): + return True + + # bottom-right glyph, clicked for real (an icon may expose no AX action) + w = main_window(ax) + f = frame(ax, w) if w else None + if f: + click_at(f[0] + f[2] - 24, f[1] + f[3] - 24) + time.sleep(NAV_SETTLE) + if settings_open(ax): + return True + + # ⌘, — the macOS standard "show settings" command + focus_main_window(ax) + send_key(43, ["cmd"]) # key code 43 == "," + time.sleep(NAV_SETTLE) + if settings_open(ax): + return True + + # app menu > Settings…/Preferences… + items = rb_enter_menu(ax, ["settings", "preference", "image", "shrink", "app"]) + for it in items: + if any(k in (it.name or "").lower() for k in ("setting", "preference")): + ax.action(it.id, "AXPress") + time.sleep(NAV_SETTLE) + break + dismiss_menus(ax) + dismiss_alerts(ax) + return settings_open(ax) + + +def rb_back_settings(ax): + """Leave the settings pane (Escape, then its close glyph). True when it is gone.""" + if not settings_open(ax): + return True + send_key(MENU_KEY_ESCAPE) + time.sleep(NAV_SETTLE) + if not settings_open(ax): + return True + for el in ax.find_clickable(max_results=60): + if "close" in (dom_id(ax, el) + " " + (el.name or "")).lower(): + ax.action(el.id, "AXPress") + time.sleep(NAV_SETTLE) + break + return not settings_open(ax) + + +def toggles(ax): + """Every preference toggle of the settings pane as (label_text, checkbox_element), + paired by row geometry (the row's label and its switch share a baseline).""" + boxes = ax.find(role="checkbox", max_results=30) + if not boxes: + boxes = ax.find(role="switch", max_results=30) + labels = [el for el in ax.find_text_elements(max_results=250) + if el.role not in _SKIP_ROLES and el.role != "window" and (el.text or "").strip()] + out = [] + for cb in boxes: + cf = frame(ax, cb) + if not cf: + continue + ccy = cf[1] + cf[3] / 2.0 + best, bestd = None, 1e9 + for lb in labels: + lf = frame(ax, lb) + if not lf: + continue + d = abs((lf[1] + lf[3] / 2.0) - ccy) + if d < bestd and lf[0] <= cf[0] + 4: + best, bestd = lb, d + out.append(((best.text if best is not None and bestd <= 40 else ""), cb)) + return out + + +def find_toggle(ax, keywords): + """The preference checkbox whose row label matches `keywords`. + Falls back to the reference DOM id, then to the documented row order.""" + pairs = toggles(ax) + for text, cb in pairs: + low = (text or "").lower() + if any(k.lower() in low for k in keywords): + return cb + want = DOM_FOR_KW.get(id(keywords)) + if want: + for _t, cb in pairs: + if dom_id(ax, cb) == want: + return cb + if want in DOM_ORDER and len(pairs) == len(DOM_ORDER): + return pairs[DOM_ORDER.index(want)][1] + return None + + +def toggle_value(ax, cb): + """0/1 for an AX checkbox (AXValue), else None.""" + if cb is None: + return None + v = ax.get(cb.id, ["AXValue"]).get("AXValue") + if isinstance(v, bool): + return int(v) + if isinstance(v, (int, float)): + return int(v) + if isinstance(v, str) and v.strip() in ("0", "1"): + return int(v.strip()) + return None + + +def press_toggle(ax, cb): + """AXPress a toggle and return its new value.""" + ax.action(cb.id, "AXPress") + time.sleep(TOGGLE_SETTLE) + return toggle_value(ax, cb) + + +def set_toggle(ax, cb, want): + """Drive a toggle to `want` (0/1). Returns the final value.""" + for _ in range(3): + cur = toggle_value(ax, cb) + if cur == want: + return cur + press_toggle(ax, cb) + return toggle_value(ax, cb) + + +# ──────────────────────────────────────────────────────────────────────────── +# Menus, dialogs, extra windows +# ──────────────────────────────────────────────────────────────────────────── +def menu_bar_items(ax): + return [m for m in ax.find(role="menu_bar_item", max_results=12, max_depth=3) + if (m.name or "") != "Apple"] + + +def menu_items(ax, mbi, max_results=40): + out, seen = [], set() + for menu in ax.find(role="menu", root_id=mbi.id, max_results=3): + for it in ax.find(role="menu_item", root_id=menu.id, max_results=max_results): + if it.id in seen: + continue + seen.add(it.id) + out.append(it) + return out + + +def rb_enter_menu(ax, name_keywords): + """Open the menu-bar menu whose title matches any keyword and return its items. + An Electron menu item only reacts to AXPress while its menu is open, so opening the + menu first is required, not cosmetic.""" + if isinstance(name_keywords, str): + name_keywords = [name_keywords] + for mbi in menu_bar_items(ax): + low = (mbi.name or "").lower() + if any(k.lower() in low for k in name_keywords): + ax.action(mbi.id, "AXPress") + time.sleep(0.7) + return menu_items(ax, mbi) + return [] + + +def find_menu_item(items, keywords): + for it in items: + low = (it.name or "").lower() + if any(k.lower() in low for k in keywords): + return it + return None + + +def press_menu_item(ax, item): + ok = ax.action(item.id, "AXPress") + time.sleep(NAV_SETTLE) + return ok + + +def dismiss_menus(ax): + send_key(MENU_KEY_ESCAPE) + time.sleep(0.2) + send_key(MENU_KEY_ESCAPE) + time.sleep(0.2) + + +def extra_windows(ax): + """App windows other than the main one (file chooser, About panel, alert).""" + mw = main_window(ax) + return [w for w in windows(ax) if mw is None or w.id != mw.id] + + +def dismiss_alerts(ax): + """Press OK/Cancel/Close on any modal alert of the app. Returns how many it closed.""" + n = 0 + for w in extra_windows(ax): + for b in ax.find(role="button", root_id=w.id, max_results=40): + if (b.name or "").strip().lower() in ("ok", "cancel", "close", "dismiss"): + ax.action(b.id, "AXPress") + time.sleep(CLICK_SETTLE) + n += 1 + break + return n + + +def dropzone(ax): + """The drop target that also opens the file chooser when activated.""" + for el in ax.find_clickable(max_results=60): + if el.role in ("menu_item", "menu_bar_item"): + continue + blob = (dom_id(ax, el) + " " + (el.name or "")).lower() + if any(k in blob for k in KW_DROPZONE): + return el + hint = find_visible_text(ax, KW_DROPZONE) + if hint is None: + return None + hf = frame(ax, hint) + best, bestd = None, 1e9 + for el in ax.find_clickable(max_results=60): + f = frame(ax, el) + if not f or f[2] < 40 or f[3] < 20: + continue + d = abs((f[1] + f[3] / 2.0) - (hf[1] + hf[3] / 2.0)) + if d < bestd: + best, bestd = el, d + return best if bestd < 120 else None + + +_RB_CHOOSER_TITLE_WORDS = ("open", "öffnen", "abrir", "打开", "选择", "choose", "select") + + +def _rb_looks_like_chooser(ax, w): + """True when this window IS the native file chooser, judged by semantics. + + Never by "it is not the main window": with the chooser open, AXMainWindow points AT + the chooser, so `extra_windows()` yields the app's own window instead (measured on a + fresh VM: windows were ['Open' 800x448, 'Image Shrinker' 340x550] and the app window + was returned). Judge by the visible title, or by carrying both Cancel and Open. + """ + names = {str(b.name or "").strip().lower() + for b in ax.find(role="button", root_id=w.id, max_results=60)} + # The buttons are the definition: the chooser's TITLE appears before its button + # subtree is built (measured: title 'Open' was already there while a button scan + # still returned []), so a title-only verdict hands the caller a half-built window. + if "cancel" in names and "open" in names: + return True + title = str(getattr(w, "name", "") or "").strip().lower() + return bool(names) and any(k in title for k in _RB_CHOOSER_TITLE_WORDS) + + +def rb_file_chooser_window(ax): + """The native file-chooser window if one is showing, else None.""" + for w in windows(ax): + f = frame(ax, w) + if f and f[2] > 200 and f[3] > 150 and _rb_looks_like_chooser(ax, w): + return w + return None + + +def rb_enter_file_dialog(ax): + """Activate the drop zone so the app's file chooser opens; return the new window + element (or None). The chooser is a separate window titled like "Open".""" + dz = dropzone(ax) + if dz is None: + return None + ax.action(dz.id, "AXPress") + deadline = time.time() + 12 + while time.time() < deadline: + w = rb_file_chooser_window(ax) + if w is not None: + return w + time.sleep(0.3) + return None + + +def rb_back_dialog(ax): + """Close any extra window (Cancel button, then Escape). True when only the main + window is left.""" + _targets = [w for w in windows(ax) if _rb_looks_like_chooser(ax, w)] or extra_windows(ax) + for w in _targets: + for b in ax.find(role="button", root_id=w.id, max_results=60): + if (b.name or "").strip().lower() in ("cancel", "ok", "close"): + ax.action(b.id, "AXPress") + time.sleep(CLICK_SETTLE) + break + if extra_windows(ax): + send_key(MENU_KEY_ESCAPE) + time.sleep(NAV_SETTLE) + return not extra_windows(ax) + + +# ──────────────────────────────────────────────────────────────────────────── +# The shrink pipeline +# ──────────────────────────────────────────────────────────────────────────── +def fixtures_dir(): + d = os.environ.get("FIXTURES_DIR", "") + if d and os.path.isdir(d): + return d + here = os.path.dirname(os.path.abspath(__file__)) + return os.path.join(here, "fixtures") + + +def workdir(name="shrink"): + """A fresh scratch directory — never the fixtures dir, which must stay pristine + (the app writes its output next to the file it shrinks).""" + return tempfile.mkdtemp(prefix=f"rb_{name}_") + + +def copy_fixture(basename, dest_dir, as_name=None): + src = os.path.join(fixtures_dir(), basename) + dst = os.path.join(dest_dir, as_name or basename) + shutil.copy(src, dst) + return dst + + +def app_bundle_id(ax): + from AppKit import NSRunningApplication + app = NSRunningApplication.runningApplicationWithProcessIdentifier_(int(ax._pid)) + return app.bundleIdentifier() if app is not None else None + + +def app_bundle_path(ax): + from AppKit import NSRunningApplication + app = NSRunningApplication.runningApplicationWithProcessIdentifier_(int(ax._pid)) + url = app.bundleURL() if app is not None else None + return url.path() if url is not None else None + + +def saved_texts(ax): + """Visible result-list headline texts, newest first (they are prepended).""" + return [t for t in visible_texts(ax) if "saved" in (t or "").lower()] + + +def result_lines(ax): + """The result list as [{"percent": int|None, "path": str}] newest first.""" + wframes = window_frames(ax) + rows = [] + for el in ax.find_text_elements(max_results=250): + if el.role in _SKIP_ROLES or el.role == "window": + continue + if not is_visible(ax, el, wframes): + continue + f = frame(ax, el) + rows.append((f[1], el.role, el.text)) + rows.sort() + out = [] + for i, (y, role, text) in enumerate(rows): + if "saved" in (text or "").lower(): + m = SAVED_RE.search(text) + path = "" + for _y2, _r2, t2 in rows[i + 1:i + 4]: + if t2 and t2.startswith("/"): + path = t2 + break + out.append({"percent": int(m.group(1)) if m else None, + "path": path, "text": text}) + return out + + +def shrink_file(ax, path, timeout=15.0): + """Hand `path` to the app the way the Finder / a double-click does (the app's own + open-file handler) and wait until a NEW result line shows up. + Returns the new result dict, or None on timeout.""" + n_before = len(saved_texts(ax)) + bid = app_bundle_id(ax) + if bid: + subprocess.run(["open", "-b", bid, path], capture_output=True, timeout=20) + else: + bundle = app_bundle_path(ax) + if not bundle: + return None + subprocess.run(["open", "-a", bundle, path], capture_output=True, timeout=20) + deadline = time.time() + timeout + while time.time() < deadline: + if len(saved_texts(ax)) > n_before: + time.sleep(0.4) + lines = result_lines(ax) + return lines[0] if lines else None + time.sleep(0.25) + return None + + +def expected_percent(size_before, size_after): + """The saving the app should report: JS Math.round(100 / before * (before - after)) + (half-up, unlike Python's banker's rounding).""" + if not size_before: + return None + return int(math.floor((100.0 / size_before) * (size_before - size_after) + 0.5)) + + +def wait_for(predicate, timeout=6.0, interval=0.25): + deadline = time.time() + timeout + while time.time() < deadline: + try: + v = predicate() + except Exception: + v = None + if v: + return v + time.sleep(interval) + return None + + +# ──────────────────────────────────────────────────────────────────────────── +# VLM screenshot assertions +# ──────────────────────────────────────────────────────────────────────────── +def results_dir(): + return os.environ.get("RESULTS_DIR") or os.path.join( + os.path.dirname(os.path.abspath(__file__)), "baseline_results") + + +def screenshot_assert(test_name, description, out_dir=None, ax=None): + """Capture the screen and record what a VLM judge should see in it. + + `ax` is accepted and deliberately IGNORED. test_ax_structure.py calls this helper + directly as `H.screenshot_assert(name, desc, RESULTS_DIR, ax=ax)`, which raised + TypeError on the reference app itself (the signature had no `ax`). The capture stays + full-screen on purpose: the frozen official_screenshots the VLM judge compares + against were taken that way, so cropping here would change what is being judged. + """ + base = out_dir or results_dir() + 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 + af = os.path.join(ss_dir, "assertions.json") + data = {} + if os.path.exists(af): + try: + with open(af) as f: + data = json.load(f) + except Exception: + data = {} + data[f"{test_name}.png"] = description + try: + with open(af, "w") as f: + json.dump(data, f, indent=2) + except Exception: + pass + + +def setting_rows(ax): + """The settings pane's six preference rows as (label_text, checkbox_element). + + The generated tests call `setting_rows`, but the module only ever defined `toggles`, + so every test using it died with AttributeError on the reference app itself. + + This is `toggles` with the row label resolved through the checkbox's + AXDOMIdentifier rather than by pure row geometry. The settings pane is an OVERLAY: + the home-surface texts underneath it keep real frames, and one of them shares a + baseline with the top row, so geometry alone mislabels it (observed: row 1 came back + as 'only SVG, JPG, GIF and PNG allowed' instead of 'Save shrinked files in same + folder'). Rows are returned in the pane's documented DOM order. + """ + _KW_FOR_DOM = {"folderswitch": KW_SAME_FOLDER, "notification": KW_NOTIFICATION, + "suffix": KW_SUFFIX, "subfolder": KW_SUBFOLDER, + "clearlist": KW_CLEARLIST, "updatecheck": KW_UPDATECHECK} + pairs = toggles(ax) + texts = [t for t in visible_texts(ax) if (t or "").strip()] + + def _label_for(cb, geom_label): + kws = _KW_FOR_DOM.get(dom_id(ax, cb)) + if kws: + for t in texts: + low = (t or "").lower() + if any(k.lower() in low for k in kws): + return t + return geom_label + + rows = [(_label_for(cb, lb), cb) for lb, cb in pairs] + order = {d: i for i, d in enumerate(DOM_ORDER)} + if all(dom_id(ax, cb) in order for _lb, cb in rows): + rows.sort(key=lambda r: order[dom_id(ax, r[1])]) + return rows diff --git a/macos/stefansl-image-shrinker/tests/rb_testgen_kit.py b/macos/stefansl-image-shrinker/tests/rb_testgen_kit.py new file mode 100644 index 0000000000000000000000000000000000000000..ccbbdd3c6136513161c133fbb4cefcfb0386d55c --- /dev/null +++ b/macos/stefansl-image-shrinker/tests/rb_testgen_kit.py @@ -0,0 +1,575 @@ +#!/usr/bin/env python3 +"""RB TestGen Kit (macOS/AX port of the Linux v7.5 kit) — a test's NAVIGATION +DEPTH and JUMP RIGOR are DECLARED (not inferred), uniformly recorded, and +self-auditable. + +DIFFERENCE FROM LINUX: macOS tests are **pytest** (methods on Test* classes taking +the `ax` fixture, plain asserts) — NOT standalone scripts calling R.record(). So the +DECLARATION is a pytest marker on the test method: + + import rb_testgen_kit as kit + + @pytest.mark.rb(depth=1, jump_kind="reach", expect="Preferences window visible") + def test_prefs_opens(self, ax_with_reset): + before = kit.rb_showing(ax_with_reset) + helpers.rb_reach_prefs(ax_with_reset) # a nav helper you name rb_reach_* / rb_enter_* + after = kit.rb_showing(ax_with_reset) + assert kit.rb_reach(before, after, target="Preferences", source="menu bar") + +conftest.py's pytest_runtest_makereport hook reads the marker + the test outcome and +writes {name, passed, depth, jump_kind, tier, expect} so the runner can fold it into +_results.json. The audits below then read those records (+ the test SOURCE). + +jump_kind (verbatim strings — the audit/stats key off them): + "none" no trigger; existence/structure only -> tier 0 + "liveness" only "did not crash / still alive" -> tier 1 (weak; avoid) + "reach" a real surface jump: the TARGET surface's element + APPEARED and the SOURCE surface's element DISAPPEARED -> tier 2 + "transition" a state flip (CHECKED/ENABLED/mode) before->after -> tier 2 + "value" a specific expected value/content was asserted -> tier 3 + +DEPTH is the number of surfaces crossed before the assertion (0 = home/first screen, +1 = one dialog/panel/submenu, 2+ = deeper). A flat-tree read of a deep element is +depth 0 — depth counts surfaces the test actually navigated through. + +REACH PROOF (so "reach" cannot be faked by reading a flat tree): + before = rb_showing(ax) + + 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('')" + python3 -c "import rb_testgen_kit as k; k.rb_lint('')" + python3 -c "import rb_testgen_kit as k; k.rb_lint_sources('')" + python3 -c "import rb_testgen_kit as k; k.rb_audit_depth('','')" +""" +from __future__ import annotations + +import ast +import glob +import json +import os +import re + +JUMP_KINDS = {"none": 0, "liveness": 1, "reach": 2, "transition": 2, "value": 3} + +# Double-axis quota TARGETS (fractions) — goals rb_audit REPORTS, NOT a hard gate. +QUOTAS = { + "existence_max": 0.30, # jump_kind=="none" share of ALL tests + "interactive_min": 0.60, # reach|transition|value share of ALL tests + "depth_ge1_min": 0.40, # depth>=1 share of INTERACTIVE tests + "depth_ge2_min": 0.10, # depth>=2 share of INTERACTIVE tests + "value_min": 0.25, # jump_kind=="value" share of INTERACTIVE tests +} + +# Depth family: a test "crosses a surface" iff it calls a member of the depth family. +# macOS accepts BOTH the naming convention rb_enter_*/rb_reach_* (write your own nav +# helper and NAME it so) AND the existing verifier_helpers/ax_helpers navigation +# functions (whitelist below) — so tests can reuse the mature reveal/navigate helpers. +DEPTH_FWD_RE = re.compile(r"^rb_(enter|reach)[a-z0-9_]*$") +DEPTH_BACK_RE = re.compile(r"^rb_back[a-z0-9_]*$") +# verifier_helpers / ax_helpers navigation functions that OPEN or move to a new surface. +FWD_WHITELIST = { + "ensure_ui_visible", "ensure_panel_open", "open_actions_menu", "open_menu", + "open_settings", "open_preferences", "open_dialog", "open_panel", "open_window", + "navigate_month", "navigate", "switch_tab", "switch_mode", "switch_page", + "select_tab", "reveal_window", "show_panel", "show_menu", +} +BACK_WHITELIST = { + "dismiss_menus", "dismiss_panel", "dismiss_any_dialog", "close_panel", + "close_window", "go_back", +} +# pytest fixtures that themselves navigate into a surface during setup (so a test taking +# one legitimately has depth>=1 without a nav call in its own body). `ax` does NOT navigate. +_NAV_FIXTURES = {"ax_with_reset", "open_panel"} +# MEASURED-TIER verdict families (ported from keliang): a tier2/3 jump_kind must be BACKED +# by its verdict function — transition->rb_flip*, value->rb_value*, reach->rb_reach* — whose +# bool result is the test's assertion. Self-named wrappers count by prefix. +TIER_FLIP_RE = re.compile(r"^rb_flip[a-z0-9_]*$") +TIER_VALUE_RE = re.compile(r"^rb_value[a-z0-9_]*$") +_JK_FAMILY = {"transition": "flip", "value": "value", "reach": "reach"} +# normalize plural (v73prep) / singular module names so a JSON module ("button") and a +# file stem ("buttons") join. +_MODULE_ALIAS = {"menus": "menu", "buttons": "button", "states": "state", + "structures": "structure", "texts": "text", + "computations": "computation", "workflows": "workflow"} + +_DEPTH = 0 # module-global surface counter for rb_enter/rb_back + + +def tier_of(jump_kind: str) -> int: + return JUMP_KINDS.get(jump_kind, 2) + + +def rb_reset_depth() -> None: + global _DEPTH + _DEPTH = 0 + + +def rb_enter(_surface: str = "") -> int: + """Call right after your test navigates into a new surface (dialog/panel/submenu).""" + global _DEPTH + _DEPTH += 1 + return _DEPTH + + +def rb_back() -> int: + global _DEPTH + _DEPTH = max(0, _DEPTH - 1) + return _DEPTH + + +def _walk_tree_nodes(node, out, seen): + """Yield 'role|name' for a macOS AXHelper.tree() dict node (+children).""" + if not isinstance(node, dict) or seen[0] >= 8000: + return + seen[0] += 1 + role = str(node.get("role") or "") + name = str(node.get("name") or node.get("value") or "") + if role or name: + out.add(f"{role}|{name}") + for c in (node.get("children") or []): + _walk_tree_nodes(c, out, seen) + + +def rb_showing(ax, max_depth: int = 12) -> set: + """Snapshot the currently-reachable AX subtree under the app as {"role|name"}. + macOS AX has no AT-SPI SHOWING/VISIBLE state, so we approximate "showing" by the + live AX tree (AXChildren) the app currently exposes — a new window/sheet/popover + adds its elements; a dismissed one removes them. Feed before+after a trigger to + rb_reach() so a 'reach' test proves a REAL surface change, not a flat-tree read. + Safe no-op (empty set) if `ax` cannot produce a tree.""" + out: set = set() + try: + tree = ax.tree(max_depth=max_depth) # AXHelper.tree() -> nested dict + except Exception: + return out + _walk_tree_nodes(tree, out, [0]) + return out + + +def rb_reach(before, after, target: str, source: str | None = None) -> bool: + """True-jump verdict: the TARGET surface's discriminating element newly APPEARED + AND (if given) the SOURCE surface's discriminating element DISAPPEARED. This is + what separates a real surface jump from reading an element that was always there.""" + before = set(before or []) + after = set(after or []) + t = target.lower() + appeared = any(t in k.lower() for k in (after - before)) + if source is None: + return appeared + s = source.lower() + src_before = any(s in k.lower() for k in before) + src_after = any(s in k.lower() for k in after) + return appeared and src_before and not src_after + + +def rb_flip(before, after, expect: str = "") -> bool: + """In-page STATE-FLIP verdict (tier2 `transition`): the observed state actually CHANGED + before->after (a CHECKED/ENABLED/mode/selection value read the two times). Pass its bool + as the test's assertion. Does NOT touch depth — an in-page flip is depth 0 unless you + navigated a surface to reach the control. You MAY write your own `rb_flip_()` 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_()` 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 | " + "{audit_depth|audit_tier} [results_dir]}") diff --git a/macos/stefansl-image-shrinker/tests/requirements.txt b/macos/stefansl-image-shrinker/tests/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..feef67ce2aadbaa26d12e6b01cff7b8ce89ecb5c --- /dev/null +++ b/macos/stefansl-image-shrinker/tests/requirements.txt @@ -0,0 +1,3 @@ +pytest +pytest-check +pyobjc diff --git a/macos/stefansl-image-shrinker/tests/test_ax_buttons.py b/macos/stefansl-image-shrinker/tests/test_ax_buttons.py new file mode 100644 index 0000000000000000000000000000000000000000..cbb632c5aa599fd98ae7be4a0f64b34c47237f12 --- /dev/null +++ b/macos/stefansl-image-shrinker/tests/test_ax_buttons.py @@ -0,0 +1,464 @@ +"""AX button/control tests for Image Shrinker — every test asserts the CONSEQUENCE. + +Facts this module is built on (all observed on the running reference app, see recon): + +* The app is **Electron**: the window's AX subtree is EMPTY until the Chromium a11y + handshake runs, so the FIRST statement of every test is ``H.ensure_ax_ready(ax)``. +* The app's own controls are NOT ``AXButton``s. The ``...`` open-settings glyph, the + ``x`` close-settings glyph and the drop zone are ``AXGroup``s that merely expose + ``AXPress``. They are located through the semantic helpers + (``H.settings_trigger`` / ``H.dropzone`` / ``H.rb_back_settings``) — never by + ``role == "button"``, never by a DOM-id literal, never by child index or tree path, + so the same test also drives a recreation built on a different framework. +* The settings pane never leaves the AX tree (it is collapsed to a 1x1 box when + closed), therefore PRESENCE proves nothing: every verdict is measured on + VISIBILITY (``H.visible_set`` / ``H.visible_texts`` / ``H.settings_open``) or on the + set of app windows. +* The only genuinely named button of the app is the save-path ``> Open`` button, which + exists only while "Save shrinked files in same folder" is switched OFF. + +Never pressed here: the three traffic lights (AXCloseButton / AXMinimizeButton / +AXFullScreenButton), the footer logo link, the result-line path link. +""" +import json +import os +import subprocess +import time + +import pytest + +import imgshrink_helpers as H +import rb_testgen_kit as kit + + +def screenshot_assert(test_name, description, results_dir, ax=None): + """Capture the screen (cropped to the app's windows when `ax` is given) and record + what a VLM judge should be able to see in the shot.""" + 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") + region = None + if ax is not None: + try: + frames = H.window_frames(ax) + if frames: + x0 = min(f[0] for f in frames) - 16 + y0 = min(f[1] for f in frames) - 16 + x1 = max(f[0] + f[2] for f in frames) + 16 + y1 = max(f[1] + f[3] for f in frames) + 16 + if x1 - x0 > 40 and y1 - y0 > 40: + region = "%d,%d,%d,%d" % (max(0, x0), max(0, y0), x1 - x0, y1 - y0) + except Exception: + region = None + try: + cmd = ["screencapture", "-x"] + (["-R", region] if region else []) + subprocess.run(cmd + [ss_path], timeout=8) + except Exception: + pass + af = os.path.join(ss_dir, "assertions.json") + data = {} + if os.path.exists(af): + try: + with open(af) as f: + data = json.load(f) + except Exception: + data = {} + data[f"{test_name}.png"] = description + with open(af, "w") as f: + json.dump(data, f, indent=2) + + +RESULTS_DIR = os.environ.get("RESULTS_DIR", os.path.dirname(os.path.abspath(__file__))) + +# Discriminating on-screen strings (EN + a couple of localisation fallbacks) — matched +# case-insensitively as substrings, so a recreation that words a row slightly +# differently is still driven by the same test. +UPDATES_ROW = "Check for updates" # bottom preference row -> "the pane is open" +CHOOSE_FOLDER = "Choose folder" # label revealed together with "> Open" +CHOOSER_TITLE = "Open" # native file/folder chooser window title +CHOOSER_CANCEL = "Cancel" # the chooser's dismiss button + +# Label keywords of the save-path button ("> Open" on the reference). +OPEN_BTN_KWS = ("open", "choose", "browse", "select", "ordner", "选择") +# Never treat these as the save-path button (they would close/quit something). +BTN_BLOCKLIST = ("close", "quit", "cancel", "delete", "remove", "exit") + + +def _visible_named_button(ax, keywords=OPEN_BTN_KWS): + """The VISIBLE push control whose LABEL (AXTitle/AXDescription) matches `keywords`. + + Located by role + visible label, with a pressable-element fallback — no DOM ids, no + indices. Visibility is the point: the settings pane stays in the tree at all times, + so a presence-only lookup would "find" the save-path button even while it is hidden. + """ + wframes = H.window_frames(ax) + for pool in (ax.find(role="button", max_results=60), + ax.find_clickable(max_results=60)): + for el in pool: + if el.role in ("menu_item", "menu_bar_item", "link", "window"): + continue + nm = (el.name or "").strip().lower() + if not nm or any(b in nm for b in BTN_BLOCKLIST): + continue + if any(k in nm for k in keywords) and H.is_visible(ax, el, wframes): + return el + return None + + +def _button_names(ax, root_id): + """Every button LABEL owned by `root_id` (window), blanks dropped.""" + out = [] + for b in ax.find(role="button", root_id=root_id, max_results=80): + nm = (b.name or "").strip() + if nm: + out.append(nm) + return out + + +# ─────────────────────────────────────────────────────────────────────────────── +class TestSettingsGlyphs: + """The two icon glyphs that open / close the in-window settings pane. They are + AXGroups with AXPress and no label, so they are found by helper, and judged purely + by what pressing them does to the on-screen text.""" + + @pytest.mark.rb(depth=1, jump_kind="reach", + expect="'Check for updates' row becomes visible when the ⋯ glyph is pressed") + def test_open_settings_glyph_reveals_the_pane(self, ax): + H.ensure_ax_ready(ax) + H.dismiss_alerts(ax) + + el = H.settings_trigger(ax) + assert el is not None, ( + "expected a pressable settings trigger (the '...' glyph at the window's " + "bottom-right); observed none among the app's pressable elements") + actions = list(el.actions or []) + assert "AXPress" in actions, ( + f"settings trigger role={el.role!r} name={el.name!r}: expected its action " + f"interface to offer 'AXPress'; observed actions={actions}") + assert len(actions) >= 1, f"expected >=1 action, observed {actions}" + assert el.enabled, f"settings trigger should be enabled; observed enabled={el.enabled}" + assert H.is_visible(ax, el), ( + "settings trigger should be on screen; observed frame=" + f"{H.frame(ax, el)} against windows {H.window_frames(ax)}") + + before = H.visible_set(ax) + assert not H.text_is_visible(ax, [UPDATES_ROW]), ( + f"the pane must start closed; observed {UPDATES_ROW!r} already visible: " + f"{sorted(H.visible_texts(ax))}") + + ax.action(el.id, "AXPress") + time.sleep(H.NAV_SETTLE) + after = H.visible_set(ax) + if not H.rb_reach_appear(before, after, target=UPDATES_ROW): + # A recreation may wire the glyph elsewhere (menu item / ⌘,) — take the + # multi-strategy route, then re-measure, so the CONSEQUENCE still decides. + H.rb_enter_settings(ax) + after = H.visible_set(ax) + assert H.rb_reach_appear(before, after, target=UPDATES_ROW), ( + f"expected the settings pane to become visible (a new {UPDATES_ROW!r} row); " + f"observed newly visible={sorted(after - before)}") + assert H.settings_open(ax) is True, ( + "settings_open() should report the pane on screen; observed visible texts=" + f"{sorted(H.visible_texts(ax))}") + + screenshot_assert( + "button_test_open_settings_glyph", + "Image Shrinker's settings pane is open: a near-black overlay fills the " + "340x550 window with the 'Settings' heading at the top and six preference " + "rows, each a left-aligned label plus an iOS-style switch on the right — " + "'Save shrinked files in same folder', 'Enable notifications', " + "'Add .min suffix to shrinked files', 'Add subfolder \"minified\"', " + "'Clear result list, when shrinking new images', 'Check for updates'. " + "An 'App by' + CLICKPRESS logo sits bottom-left and an x glyph bottom-right. " + "The drop-zone home surface is no longer visible.", + RESULTS_DIR, ax=ax) + + assert H.rb_back_settings(ax), ( + "teardown: expected the pane to close again; observed visible texts=" + f"{sorted(H.visible_texts(ax))}") + + @pytest.mark.rb(depth=1, jump_kind="reach", + expect="the six preference rows disappear when the settings pane is dismissed") + def test_close_settings_glyph_hides_the_pane(self, ax): + H.ensure_ax_ready(ax) + H.dismiss_alerts(ax) + + assert H.rb_enter_settings(ax), ( + "precondition: could not open the settings pane; observed visible texts=" + f"{sorted(H.visible_texts(ax))}") + before = H.visible_set(ax) + assert any(UPDATES_ROW.lower() in k.lower() for k in before), ( + f"precondition: expected {UPDATES_ROW!r} visible with the pane open; " + f"observed {sorted(before)}") + + # rb_back_settings dismisses the pane the way a user does: Escape, else AXPress + # on the 'x' close glyph (an unnamed AXGroup — located by helper, not by id). + assert H.rb_back_settings(ax), ( + "expected the close control to dismiss the settings pane; observed it still " + f"open with visible texts={sorted(H.visible_texts(ax))}") + after = H.visible_set(ax) + + assert H.rb_reach_gone(before, after, UPDATES_ROW), ( + f"expected the preference rows (incl. {UPDATES_ROW!r}) to leave the screen; " + f"observed still visible={sorted(k for k in after if UPDATES_ROW.lower() in k.lower())}, " + f"disappeared={sorted(before - after)}") + assert H.settings_open(ax) is False, ( + "settings_open() should report the pane gone; observed visible texts=" + f"{sorted(H.visible_texts(ax))}") + assert H.text_is_visible(ax, ["drag"]) or H.text_is_visible(ax, ["allowed"]), ( + "expected the home drop-zone surface back after dismissing the pane; " + f"observed visible texts={sorted(H.visible_texts(ax))}") + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="visible-text count 2 → 10 → 2 across open/close of the settings pane") + def test_settings_glyph_toggles_are_reversible(self, ax): + H.ensure_ax_ready(ax) + H.dismiss_alerts(ax) + + n_closed = len(H.visible_texts(ax)) + assert H.rb_enter_settings(ax), ( + f"could not open the settings pane; observed {n_closed} visible texts") + n_open = len(H.visible_texts(ax)) + + assert kit.rb_flip(n_closed, n_open), ( + "pressing the settings glyph must change what is on screen; observed the " + f"same visible-text count before and after ({n_closed})") + assert n_open >= n_closed + 6, ( + "expected the pane to add at least the 6 preference row labels " + f"(reference: 2 -> 10); observed {n_closed} -> {n_open}") + + assert H.rb_back_settings(ax), ( + f"could not close the settings pane; observed {n_open} visible texts") + n_closed_again = len(H.visible_texts(ax)) + assert n_closed_again == n_closed, ( + "closing the pane must restore the home surface exactly; observed " + f"{n_closed} -> {n_open} -> {n_closed_again} visible texts") + + +# ─────────────────────────────────────────────────────────────────────────────── +class TestDropZone: + """The drop zone ('Drag files here') doubles as the app's file-picker control: it is + an AXGroup with AXPress whose activation opens a native chooser window.""" + + @pytest.mark.rb(depth=1, jump_kind="reach", + expect="a native 'Open' chooser window appears when the drop zone is activated") + def test_dropzone_opens_the_file_chooser(self, ax): + H.ensure_ax_ready(ax) + H.dismiss_alerts(ax) + + dz = H.dropzone(ax) + assert dz is not None, ( + "expected a pressable drop zone around the 'Drag files here' hint; observed " + f"none. visible texts={sorted(H.visible_texts(ax))}") + actions = list(dz.actions or []) + assert "AXPress" in actions, ( + f"drop zone role={dz.role!r} name={dz.name!r}: expected 'AXPress' in its " + f"action interface; observed actions={actions}") + assert dz.enabled, f"drop zone should be enabled; observed enabled={dz.enabled}" + assert H.is_visible(ax, dz), ( + f"drop zone should be on screen; observed frame={H.frame(ax, dz)}") + + n_before = len(H.windows(ax)) + before = kit.rb_showing(ax, max_depth=8) + w = H.rb_enter_file_dialog(ax) + after = kit.rb_showing(ax, max_depth=8) + + assert w is not None, ( + "expected activating the drop zone to open a chooser window; observed the " + f"window count staying at {n_before} ({[x.name for x in H.windows(ax)]})") + assert CHOOSER_TITLE.lower() in (w.name or "").lower(), ( + f"expected the new window to be the native chooser titled ~{CHOOSER_TITLE!r}; " + f"observed name={w.name!r} frame={H.frame(ax, w)}") + assert kit.rb_reach(before, after, target=CHOOSER_TITLE), ( + "expected the chooser surface to be NEW in the AX tree; observed newly " + f"reachable={sorted(list(after - before))[:12]}") + + screenshot_assert( + "button_test_dropzone_file_chooser", + "Activating Image Shrinker's drop zone opened a native macOS 'Open' file " + "chooser panel (roughly 800x448) in front of the small 340x550 app window. " + "The panel shows a Favorites sidebar on the left, a file browser on the " + "right, and 'Cancel' and 'Open' buttons in its bottom-right corner. The app " + "window behind it still shows the dashed drop zone.", + RESULTS_DIR, ax=ax) + + assert H.rb_back_dialog(ax), ( + "teardown: expected Cancel to dismiss the chooser; observed extra windows=" + f"{[x.name for x in H.extra_windows(ax)]}") + + @pytest.mark.rb(depth=2, jump_kind="value", + expect="the chooser window owns buttons named 'Cancel' and 'Open'") + def test_file_chooser_offers_cancel_and_open_buttons(self, ax): + H.ensure_ax_ready(ax) + H.dismiss_alerts(ax) + + w = H.rb_enter_file_dialog(ax) + assert w is not None, ( + "precondition: the drop zone did not open a chooser window; observed " + f"windows={[x.name for x in H.windows(ax)]}") + + names = _button_names(ax, w.id) + blob = " | ".join(sorted(names)).lower() + + assert kit.rb_value(blob, "cancel"), ( + f"expected the chooser to own a 'Cancel' button; observed buttons={names}") + assert kit.rb_value(blob, "open"), ( + f"expected the chooser to own an 'Open' button; observed buttons={names}") + + assert H.rb_back_dialog(ax), ( + "teardown: expected Cancel to dismiss the chooser; observed extra windows=" + f"{[x.name for x in H.extra_windows(ax)]}") + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="window count 1 → 2 → 1 as the chooser is opened and cancelled") + def test_file_chooser_cancel_returns_to_one_window(self, ax): + H.ensure_ax_ready(ax) + H.dismiss_alerts(ax) + + n_before = len(H.windows(ax)) + assert n_before == 1, ( + "precondition: expected exactly the main window before opening the chooser; " + f"observed {n_before} ({[x.name for x in H.windows(ax)]})") + + w = H.rb_enter_file_dialog(ax) + n_open = len(H.windows(ax)) + assert w is not None, ( + f"the drop zone did not open a chooser; observed window count {n_open}") + + assert kit.rb_flip(n_before, n_open), ( + "activating the drop zone must add a window; observed the count staying at " + f"{n_before}") + assert n_open == n_before + 1, ( + f"expected exactly one extra window; observed {n_before} -> {n_open} " + f"({[x.name for x in H.windows(ax)]})") + + assert H.rb_back_dialog(ax), ( + "expected Cancel to close the chooser; observed extra windows=" + f"{[x.name for x in H.extra_windows(ax)]}") + n_after = len(H.windows(ax)) + assert n_after == n_before, ( + f"cancelling must restore the original window set; observed {n_before} -> " + f"{n_open} -> {n_after}") + + +# ─────────────────────────────────────────────────────────────────────────────── +class TestSavePathButton: + """The save-path '> Open' button — the app's only labelled AXButton. It lives on the + settings pane and only exists while "Save ... in same folder" is switched OFF, so + reaching it costs two surfaces: pane -> revealed row.""" + + @pytest.mark.rb(depth=2, jump_kind="reach", + expect="a '> Open' button and the 'Choose folder' label appear when " + "'Save … in same folder' is switched off") + def test_savepath_button_appears_when_same_folder_is_off(self, ax): + H.ensure_ax_ready(ax) + H.dismiss_alerts(ax) + + assert H.rb_enter_settings(ax), ( + "precondition: could not open the settings pane; observed visible texts=" + f"{sorted(H.visible_texts(ax))}") + cb = H.find_toggle(ax, H.KW_SAME_FOLDER) + assert cb is not None, ( + "precondition: no 'save in same folder' toggle found next to its row label; " + f"observed rows={[t for t, _ in H.setting_rows(ax)]}") + orig = H.toggle_value(ax, cb) + assert orig in (0, 1), ( + f"expected the toggle to expose AXValue 0/1; observed {orig!r}") + # The launch default is ON; normalise so the APPEARANCE is measurable, and leave + # it ON at the end (the app's own default, which later tests rely on). + if orig != 1: + H.set_toggle(ax, cb, 1) + + before = H.visible_set(ax) + assert _visible_named_button(ax) is None, ( + "precondition: no save-path button should be visible while 'same folder' is " + f"ON; observed one named {(_visible_named_button(ax) or cb).name!r}") + + assert H.set_toggle(ax, cb, 0) == 0, ( + f"could not switch 'same folder' off; observed value={H.toggle_value(ax, cb)}") + after = H.visible_set(ax) + + assert H.rb_reach_appear(before, after, target=CHOOSE_FOLDER), ( + f"expected a new {CHOOSE_FOLDER!r} label once the output folder becomes " + f"user-selectable; observed newly visible={sorted(after - before)}") + btn = _visible_named_button(ax) + assert btn is not None, ( + "expected a labelled button (reference: '> Open') for picking the output " + f"folder; observed newly visible={sorted(after - before)}") + assert "open" in (btn.name or "").lower(), ( + f"expected the save-path button's label to read like '> Open'; observed " + f"name={btn.name!r}") + assert btn.enabled, ( + f"the save-path button must be usable; observed enabled={btn.enabled} on " + f"{btn.name!r}") + assert "AXPress" in list(btn.actions or []), ( + f"save-path button {btn.name!r}: expected 'AXPress' in its action interface; " + f"observed actions={list(btn.actions or [])}") + + screenshot_assert( + "button_test_savepath_button_revealed", + "Image Shrinker's settings pane with 'Save shrinked files in same folder' " + "switched OFF: a new row is inserted directly under it showing the label " + "'Choose folder' and a full-width blue button reading '> Open'. The " + "remaining preference rows ('Enable notifications', 'Add .min suffix to " + "shrinked files', 'Add subfolder \"minified\"', 'Clear result list, when " + "shrinking new images', 'Check for updates') have shifted down.", + RESULTS_DIR, ax=ax) + + assert H.set_toggle(ax, cb, 1) == 1, ( + f"teardown: could not switch 'same folder' back on; observed value=" + f"{H.toggle_value(ax, cb)}") + assert _visible_named_button(ax) is None, ( + "switching 'same folder' back on must remove the save-path button; observed " + f"{(_visible_named_button(ax) or cb).name!r} still on screen") + assert not H.text_is_visible(ax, [CHOOSE_FOLDER]), ( + f"expected {CHOOSE_FOLDER!r} gone again; observed visible texts=" + f"{sorted(H.visible_texts(ax))}") + H.rb_back_settings(ax) + + @pytest.mark.rb(depth=2, jump_kind="reach", + expect="pressing '> Open' opens a native chooser window") + def test_savepath_button_opens_a_folder_chooser(self, ax): + H.ensure_ax_ready(ax) + H.dismiss_alerts(ax) + + assert H.rb_enter_settings(ax), ( + "precondition: could not open the settings pane; observed visible texts=" + f"{sorted(H.visible_texts(ax))}") + cb = H.find_toggle(ax, H.KW_SAME_FOLDER) + assert cb is not None, ( + "precondition: no 'save in same folder' toggle found; observed rows=" + f"{[t for t, _ in H.setting_rows(ax)]}") + orig = H.toggle_value(ax, cb) + assert orig in (0, 1), ( + f"expected the toggle to expose AXValue 0/1; observed {orig!r}") + + assert H.set_toggle(ax, cb, 0) == 0, ( + f"could not switch 'same folder' off; observed value={H.toggle_value(ax, cb)}") + btn = _visible_named_button(ax) + assert btn is not None, ( + "precondition: no save-path button on screen after switching 'same folder' " + f"off; observed visible texts={sorted(H.visible_texts(ax))}") + + n_before = len(H.windows(ax)) + before = kit.rb_showing(ax, max_depth=8) + assert ax.action(btn.id, "AXPress"), ( + f"AXPress on the save-path button {btn.name!r} was refused; observed " + f"actions={list(btn.actions or [])}") + extra = H.wait_for(lambda: H.extra_windows(ax), timeout=6) + after = kit.rb_showing(ax, max_depth=8) + + assert extra, ( + f"expected pressing {btn.name!r} to open a native folder chooser; observed " + f"the window count staying at {n_before} " + f"({[x.name for x in H.windows(ax)]})") + assert kit.rb_reach(before, after, target=CHOOSER_CANCEL), ( + f"expected the chooser's {CHOOSER_CANCEL!r} control to be NEW in the AX " + f"tree; observed new windows={[x.name for x in extra]}, newly reachable=" + f"{sorted(list(after - before))[:12]}") + + assert H.rb_back_dialog(ax), ( + "teardown: expected Cancel to dismiss the chooser; observed extra windows=" + f"{[x.name for x in H.extra_windows(ax)]}") + H.set_toggle(ax, cb, orig if orig == 1 else 1) + H.rb_back_settings(ax) diff --git a/macos/stefansl-image-shrinker/tests/test_ax_computation.py b/macos/stefansl-image-shrinker/tests/test_ax_computation.py new file mode 100644 index 0000000000000000000000000000000000000000..2bf226e8b062022dad2594d41fff92d0a72ad346 --- /dev/null +++ b/macos/stefansl-image-shrinker/tests/test_ax_computation.py @@ -0,0 +1,527 @@ +"""AX computation tests for Image Shrinker — input image → shrunken file + 'You saved N%'. + +The app's computation is image shrinking: an image file goes in, a smaller file plus a +"You saved N%. Your shrunken image is here:" result line come out. + +Everything is driven through the validated helper module `imgshrink_helpers` (deployed +next to this file): + +* Image Shrinker is an Electron app whose window subtree is EMPTY until the Chromium + a11y handshake runs, so `H.ensure_ax_ready(ax)` is the FIRST statement of every test. +* the shrink pipeline is only reachable through the app's own open-file handler + (`H.shrink_file`) — never `open`/`subprocess` here, never a hardcoded bundle id/path. +* a fixture is ALWAYS copied into a fresh scratch dir first (the app writes its output + next to the input; FIXTURES_DIR must stay pristine). +* no percentage is ever hardcoded: the expectation is computed from the REAL byte sizes + with `H.expected_percent(before, after)` and asserted through `kit.rb_value()`. +* the displayed path is the RESOLVED path (`/var/folders/...` shows as + `/private/var/folders/...`), so paths are compared by basename / `os.path.realpath`. +""" +import json, math, os, subprocess, time + +import pytest + +import imgshrink_helpers as H +import rb_testgen_kit as kit + + +def screenshot_assert(test_name, description, results_dir, ax=None): + """Capture the screen and record what a VLM judge should see in it. + + When `ax` is given the capture is delegated to the helper module, which crops the + shot to the app's window(s) (same screenshots dir, same assertions.json), so the + judge sees the 340x550 app window instead of the whole desktop. + """ + if ax is not None: + try: + H.screenshot_assert(test_name, description, out_dir=results_dir, ax=ax) + 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=8) + except Exception: + pass + af = os.path.join(ss_dir, "assertions.json") + data = {} + if os.path.exists(af): + try: + with open(af) as f: + data = json.load(f) + except Exception: + data = {} + data[f"{test_name}.png"] = description + with open(af, "w") as f: + json.dump(data, f, indent=2) + + +RESULTS_DIR = os.environ.get("RESULTS_DIR", os.path.dirname(os.path.abspath(__file__))) + + +# ── small local helpers (diagnosable failures + state restoration) ─────────── +def _scratch(tag, fixture, as_name): + """A fresh scratch dir with `fixture` copied in as `as_name`. + + Returns (dir, path, size_before). The app writes its output NEXT TO the input, so a + test must never hand it a file inside FIXTURES_DIR. + """ + src_dir = H.fixtures_dir() + src = os.path.join(src_dir, fixture) + assert os.path.isfile(src), f"fixture {fixture!r} is missing from {src_dir!r}" + d = H.workdir(tag) + p = H.copy_fixture(fixture, d, as_name) + return d, p, os.path.getsize(p) + + +def _shrink(ax, path, timeout=15.0): + """H.shrink_file with a diagnosable failure message (visible texts of the app).""" + res = H.shrink_file(ax, path, timeout=timeout) + assert res is not None, ( + f"no result line appeared within {timeout}s after handing {path!r} to the app's " + f"open-file handler; visible texts = {H.visible_texts(ax)!r}") + return res + + +def _wait_file(path, timeout=5.0): + """Wait until `path` exists and is non-empty; return its size (or None).""" + ok = H.wait_for(lambda: os.path.isfile(path) and os.path.getsize(path) > 0, + timeout=timeout) + return os.path.getsize(path) if ok else None + + +def _listing(d): + try: + return sorted(os.listdir(d)) + except Exception as exc: # pragma: no cover - only for the failure message + return [f""] + + +def _remember(ax, changes, keywords, label): + """Locate a preference toggle, record its CURRENT value in `changes` and return it. + + `changes` is a list of (keywords, original_value) the test's finally-block feeds to + `_restore_toggles` — preference values persist across app restarts, so every test + must put back exactly what it read. + """ + cb = H.find_toggle(ax, keywords) + assert cb is not None, ( + f"could not locate the {label!r} preference toggle; visible texts = " + f"{H.visible_texts(ax)!r}") + cur = H.toggle_value(ax, cb) + assert cur in (0, 1), f"{label!r} toggle has a non-boolean AXValue: {cur!r}" + changes.append((keywords, cur)) + return cb + + +def _restore_toggles(ax, changes): + """Best-effort: drive every recorded toggle back to the value it had at test start. + + Presses the collapsed control first (Chromium keeps it in the tree); if the value + does not take, the settings pane is reopened and the toggle is driven there. + """ + for keywords, want in reversed(changes): + if want is None: + continue + try: + cb = H.find_toggle(ax, keywords) + if cb is not None and H.set_toggle(ax, cb, want) == want: + continue + H.rb_enter_settings(ax) + cb = H.find_toggle(ax, keywords) + if cb is not None: + H.set_toggle(ax, cb, want) + H.rb_back_settings(ax) + except Exception: + pass + + +class TestShrinkFormats: + """One shrink per supported format: the file really shrinks and the reported saving + equals round(100 / before * (before - after)) computed from the actual byte sizes.""" + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="PNG shrunk to /a.min.png and the reported saving equals " + "round(100*(before-after)/before)") + def test_png_is_shrunk_and_percent_matches_file_sizes(self, ax): + assert H.ensure_ax_ready(ax), "the app's web UI never became reachable through AX" + d, p, size_before = _scratch("png", "sample.png", "a.png") + + res = _shrink(ax, p) + + out = os.path.join(d, "a.min.png") + size_after = _wait_file(out) + assert size_after is not None, ( + f"expected the shrunken file {out!r}; directory holds {_listing(d)!r}, " + f"reported path = {res['path']!r}") + assert size_after < size_before, ( + f"PNG did not shrink: {size_after} B after vs {size_before} B before") + exp = H.expected_percent(size_before, size_after) + assert kit.rb_value(res["percent"], exp), ( + f"reported saving {res['percent']!r}% != expected {exp}% for " + f"{size_before} B -> {size_after} B (text={res['text']!r})") + assert os.path.basename(res["path"]) == "a.min.png", ( + f"result line points at {res['path']!r}, expected basename 'a.min.png'") + + screenshot_assert( + "computation_test_png_shrink", + f"Image Shrinker's 340x550 window with one result line under the dashed " + f"'Drag files here' drop zone: small grey text 'You saved {exp}%. Your " + f"shrunken image is here:' and, below it, the italic path link ending in " + f"'a.min.png' (the {size_before}-byte PNG was rewritten as a " + f"{size_after}-byte file). No settings pane, no dialog.", + RESULTS_DIR, ax=ax) + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="JPEG shrunk to /b.min.jpg and the reported saving equals " + "round(100*(before-after)/before)") + def test_jpeg_is_shrunk_and_percent_matches_file_sizes(self, ax): + assert H.ensure_ax_ready(ax), "the app's web UI never became reachable through AX" + d, p, size_before = _scratch("jpg", "sample.jpg", "b.jpg") + + res = _shrink(ax, p) + + out = os.path.join(d, "b.min.jpg") + size_after = _wait_file(out) + assert size_after is not None, ( + f"expected the shrunken file {out!r}; directory holds {_listing(d)!r}, " + f"reported path = {res['path']!r}") + assert size_after < size_before, ( + f"JPEG did not shrink: {size_after} B after vs {size_before} B before") + exp = H.expected_percent(size_before, size_after) + assert kit.rb_value(res["percent"], exp), ( + f"reported saving {res['percent']!r}% != expected {exp}% for " + f"{size_before} B -> {size_after} B (text={res['text']!r})") + assert os.path.basename(res["path"]) == "b.min.jpg", ( + f"result line points at {res['path']!r}, expected basename 'b.min.jpg'") + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="SVG shrunk to /c.min.svg and the reported saving equals " + "round(100*(before-after)/before)") + def test_svg_is_shrunk_and_percent_matches_file_sizes(self, ax): + assert H.ensure_ax_ready(ax), "the app's web UI never became reachable through AX" + d, p, size_before = _scratch("svg", "sample.svg", "c.svg") + + res = _shrink(ax, p) + + out = os.path.join(d, "c.min.svg") + size_after = _wait_file(out) + assert size_after is not None, ( + f"expected the shrunken file {out!r}; directory holds {_listing(d)!r}, " + f"reported path = {res['path']!r}") + assert size_after < size_before, ( + f"SVG did not shrink: {size_after} B after vs {size_before} B before") + exp = H.expected_percent(size_before, size_after) + assert kit.rb_value(res["percent"], exp), ( + f"reported saving {res['percent']!r}% != expected {exp}% for " + f"{size_before} B -> {size_after} B (text={res['text']!r})") + assert os.path.basename(res["path"]) == "c.min.svg", ( + f"result line points at {res['path']!r}, expected basename 'c.min.svg'") + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="GIF processed to /d.min.gif; the reported saving equals " + "round(100*(before-after)/before), which is 0% on the reference") + def test_gif_is_processed_and_percent_matches_file_sizes(self, ax): + assert H.ensure_ax_ready(ax), "the app's web UI never became reachable through AX" + d, p, size_before = _scratch("gif", "sample.gif", "d.gif") + + res = _shrink(ax, p) + + out = os.path.join(d, "d.min.gif") + size_after = _wait_file(out) + assert size_after is not None, ( + f"expected the processed file {out!r}; directory holds {_listing(d)!r}, " + f"reported path = {res['path']!r}") + # A GIF legitimately saves ~0% — the FORMULA is the assertion, not a non-zero, + # and on this fixture the reference app's GIF optimiser comes out 2 B LARGER + # (6392 B vs 6390 B). Requiring size_after <= size_before therefore failed on the + # reference itself and contradicted this test's own premise, so the size relation + # is recorded rather than asserted; the percent-vs-formula check below is the + # real value assertion and still holds (both round to 0%). + exp = H.expected_percent(size_before, size_after) + assert res["percent"] == exp, ( + f"reported saving {res['percent']!r}% != expected {exp}% for " + f"{size_before} B -> {size_after} B (text={res['text']!r})") + assert kit.rb_value(res["percent"], exp), ( + f"value verdict failed: observed {res['percent']!r}%, expected {exp}%") + assert os.path.basename(res["path"]) == "d.min.gif", ( + f"result line points at {res['path']!r}, expected basename 'd.min.gif'") + + +class TestResultLine: + """What the result list SAYS: the headline wording + percent, the path link, the + newest-first stacking, and the rejection of an unsupported format.""" + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="result headline reads 'You saved %. Your shrunken image is " + "here:' with N computed from the byte sizes, and a link names the " + "output file") + def test_result_headline_wording_and_percent(self, ax): + assert H.ensure_ax_ready(ax), "the app's web UI never became reachable through AX" + d, p, size_before = _scratch("headline", "sample.png", "hl.png") + + res = _shrink(ax, p) + + out = os.path.join(d, "hl.min.png") + size_after = _wait_file(out) + assert size_after is not None, ( + f"expected the shrunken file {out!r}; directory holds {_listing(d)!r}") + exp = H.expected_percent(size_before, size_after) + text = res["text"] or "" + assert "saved" in text.lower(), ( + f"result headline {text!r} does not mention the saving ('saved')") + assert kit.rb_value(text, f"{exp}%"), ( + f"result headline {text!r} does not report {exp}% " + f"({size_before} B -> {size_after} B)") + + links = ax.find(role="link", max_results=10) + observed = [f"{(el.name or '')!r}/{(el.value or '')!r}" for el in links] + assert any((el.name or "").endswith("hl.min.png") + or str(el.value or "").endswith("hl.min.png") for el in links), ( + f"no link names the output file 'hl.min.png'; links = {observed!r}") + + screenshot_assert( + "computation_test_result_headline", + f"Image Shrinker's window showing exactly one result line below the drop " + f"zone: the grey headline 'You saved {exp}%. Your shrunken image is here:' " + f"followed by the italic clickable path ending in 'hl.min.png'. The dashed " + f"'Drag files here' zone and the bottom-right dots glyph are still visible.", + RESULTS_DIR, ax=ax) + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="two shrinks leave two result lines, the newest (second.min.png) " + "on top and first.min.png below it") + def test_two_shrinks_stack_newest_first(self, ax): + assert H.ensure_ax_ready(ax), "the app's web UI never became reachable through AX" + d, p1, size1 = _scratch("stack", "sample.png", "first.png") + p2 = H.copy_fixture("sample.png", d, "second.png") + + first = _shrink(ax, p1) + second = _shrink(ax, p2) + + saved = H.saved_texts(ax) + assert len(saved) == 2, ( + f"expected 2 result headlines after 2 shrinks, got {len(saved)}: {saved!r}") + lines = H.result_lines(ax) + assert len(lines) == 2, ( + f"expected 2 parsed result lines, got {len(lines)}: {lines!r}") + assert kit.rb_value(os.path.basename(lines[0]["path"]), "second.min.png"), ( + f"newest result line should be 'second.min.png', got " + f"{lines[0]['path']!r} (all lines: {[l['path'] for l in lines]!r})") + assert os.path.basename(lines[1]["path"]) == "first.min.png", ( + f"older result line should be 'first.min.png', got {lines[1]['path']!r}") + assert os.path.basename(second["path"]) == "second.min.png", ( + f"the second shrink reported {second['path']!r}, expected 'second.min.png'") + assert os.path.basename(first["path"]) == "first.min.png", ( + f"the first shrink reported {first['path']!r}, expected 'first.min.png'") + assert os.path.isfile(os.path.join(d, "first.min.png")), ( + f"first.min.png missing; directory holds {_listing(d)!r}") + assert os.path.isfile(os.path.join(d, "second.min.png")), ( + f"second.min.png missing; directory holds {_listing(d)!r}") + + screenshot_assert( + "computation_test_two_results_stack", + f"Image Shrinker's window with TWO stacked result lines under the drop zone. " + f"The TOP one is the newest shrink and its italic path ends in " + f"'second.min.png'; the one below it ends in 'first.min.png'. Both headlines " + f"read 'You saved %. Your shrunken image is here:' (both shrank the same " + f"{size1}-byte PNG, so both show the same percentage).", + RESULTS_DIR, ax=ax) + + @pytest.mark.rb(depth=1, jump_kind="reach", + expect="modal alert 'Only PNG SVG, JPG and GIF allowed' appears and no " + "result line is produced for a .txt file") + def test_unsupported_format_is_rejected_with_a_message(self, ax): + assert H.ensure_ax_ready(ax), "the app's web UI never became reachable through AX" + d = H.workdir("badformat") + bad = os.path.join(d, "notanimage.txt") + with open(bad, "w") as f: + f.write("Image Shrinker must refuse this: it is plain text, not an image.\n") + + before = kit.rb_showing(ax) + res = H.shrink_file(ax, bad, timeout=6) + after = kit.rb_showing(ax) + + try: + screenshot_assert( + "computation_test_unsupported_format_alert", + "A modal alert sheet in front of Image Shrinker's window carrying the app " + "icon, the message 'Only PNG SVG, JPG and GIF allowed' and a single OK " + "button. The window behind it still shows the empty drop zone — NO 'You " + "saved N%' result line was added for the .txt file.", + RESULTS_DIR, ax=ax) + + assert res is None, ( + f"a .txt file must NOT produce a result line, but the app reported " + f"{res!r}") + assert kit.rb_reach(before, after, target="allowed"), ( + "no new 'Only PNG SVG, JPG and GIF allowed' node appeared after handing " + f"the app a .txt file; new nodes = {sorted(after - before)!r}") + saved = H.saved_texts(ax) + assert len(saved) == 0, ( + f"expected 0 result headlines after rejecting a .txt, got {saved!r}") + assert not os.path.isfile(os.path.join(d, "notanimage.min.txt")), ( + f"the app wrote an output file for the .txt input; directory holds " + f"{_listing(d)!r}") + finally: + H.dismiss_alerts(ax) + + +class TestSettingsAffectOutput: + """The preference toggles change WHERE the computation writes its output. Each test + opens the settings pane (the depth-1 navigation), flips one location toggle, shrinks + a real file, asserts the output location, and restores what it read.""" + + @pytest.mark.rb(depth=2, jump_kind="value", + expect="with 'Add subfolder \"minified\"' on, the output path is " + "/minified/s.min.png") + def test_subfolder_setting_writes_into_minified(self, ax): + assert H.ensure_ax_ready(ax), "the app's web UI never became reachable through AX" + changes = [] + try: + assert H.rb_enter_settings(ax), ( + f"settings pane did not open; visible texts = {H.visible_texts(ax)!r}") + + # keep the suffix at its shipped default so the expected NAME is deterministic + cb_suffix = _remember(ax, changes, H.KW_SUFFIX, "Add .min suffix") + H.set_toggle(ax, cb_suffix, 1) + cb_sub = _remember(ax, changes, H.KW_SUBFOLDER, 'Add subfolder "minified"') + got = H.set_toggle(ax, cb_sub, 1) + assert got == 1, f"subfolder toggle stayed at {got!r} instead of 1" + assert H.rb_back_settings(ax), ( + f"settings pane did not close; visible texts = {H.visible_texts(ax)!r}") + + d, p, size_before = _scratch("subfolder", "sample.png", "s.png") + res = _shrink(ax, p) + + out = os.path.join(d, "minified", "s.min.png") + size_after = _wait_file(out) + assert size_after is not None, ( + f"expected the output in the 'minified' subfolder ({out!r}); directory " + f"holds {_listing(d)!r}, reported path = {res['path']!r}") + assert "/minified/" in res["path"], ( + f"reported path {res['path']!r} does not sit in a 'minified' subfolder") + assert kit.rb_value(os.path.basename(res["path"]), "s.min.png"), ( + f"reported path {res['path']!r} should be named 's.min.png'") + assert os.path.isfile(p), ( + f"the source s.png disappeared; directory holds {_listing(d)!r}") + exp = H.expected_percent(size_before, size_after) + assert kit.rb_value(res["percent"], exp), ( + f"reported saving {res['percent']!r}% != expected {exp}% for " + f"{size_before} B -> {size_after} B (text={res['text']!r})") + + screenshot_assert( + "computation_test_subfolder_output", + f"Image Shrinker's window with one result line whose italic path contains " + f"a '/minified/' component and ends in 's.min.png' — the headline reads " + f"'You saved {exp}%. Your shrunken image is here:'. The settings pane is " + f"closed again, so the dashed drop zone is visible above the result.", + RESULTS_DIR, ax=ax) + finally: + _restore_toggles(ax, changes) + + @pytest.mark.rb(depth=2, jump_kind="value", + expect="with the '.min suffix' toggle off, the shrunken file replaces " + "x.png and the reported path has no '.min'") + def test_suffix_setting_off_overwrites_in_place(self, ax): + assert H.ensure_ax_ready(ax), "the app's web UI never became reachable through AX" + changes = [] + try: + assert H.rb_enter_settings(ax), ( + f"settings pane did not open; visible texts = {H.visible_texts(ax)!r}") + + # keep the subfolder at its shipped default so the output stays in + cb_sub = _remember(ax, changes, H.KW_SUBFOLDER, 'Add subfolder "minified"') + H.set_toggle(ax, cb_sub, 0) + cb_suffix = _remember(ax, changes, H.KW_SUFFIX, "Add .min suffix") + got = H.set_toggle(ax, cb_suffix, 0) + assert got == 0, f".min suffix toggle stayed at {got!r} instead of 0" + assert H.rb_back_settings(ax), ( + f"settings pane did not close; visible texts = {H.visible_texts(ax)!r}") + + d, p, size_before = _scratch("suffix", "sample.png", "x.png") + res = _shrink(ax, p) + + base = os.path.basename(res["path"]) + assert ".min" not in base, ( + f"with the suffix toggle OFF the reported name must not carry '.min', " + f"got {res['path']!r}") + assert kit.rb_value(base, "x.png"), ( + f"reported path {res['path']!r} should be named 'x.png'") + assert base == "x.png", ( + f"reported basename {base!r} != 'x.png' (path {res['path']!r})") + assert H.wait_for(lambda: os.path.getsize(p) < size_before, timeout=5), ( + f"x.png was not rewritten in place: still {os.path.getsize(p)} B, " + f"original was {size_before} B") + size_after = os.path.getsize(p) + assert _listing(d) == ["x.png"], ( + f"the scratch dir should hold only the overwritten x.png, holds " + f"{_listing(d)!r}") + exp = H.expected_percent(size_before, size_after) + assert kit.rb_value(res["percent"], exp), ( + f"reported saving {res['percent']!r}% != expected {exp}% for " + f"{size_before} B -> {size_after} B (text={res['text']!r})") + + screenshot_assert( + "computation_test_suffix_off_in_place", + f"Image Shrinker's window with one result line whose italic path ends in " + f"'x.png' — WITHOUT a '.min' before the extension, because the '.min " + f"suffix' preference was switched off; the headline reads 'You saved " + f"{exp}%. Your shrunken image is here:'. Settings pane closed.", + RESULTS_DIR, ax=ax) + finally: + _restore_toggles(ax, changes) + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="with the shipped defaults the output is /y.min.png beside " + "the untouched input y.png") + def test_default_settings_write_min_file_next_to_the_input(self, ax): + assert H.ensure_ax_ready(ax), "the app's web UI never became reachable through AX" + changes = [] + try: + assert H.rb_enter_settings(ax), ( + f"settings pane did not open; visible texts = {H.visible_texts(ax)!r}") + + cb_sub = _remember(ax, changes, H.KW_SUBFOLDER, 'Add subfolder "minified"') + H.set_toggle(ax, cb_sub, 0) + cb_suffix = _remember(ax, changes, H.KW_SUFFIX, "Add .min suffix") + H.set_toggle(ax, cb_suffix, 1) + cb_same = _remember(ax, changes, H.KW_SAME_FOLDER, "same folder") + H.set_toggle(ax, cb_same, 1) + assert H.rb_back_settings(ax), ( + f"settings pane did not close; visible texts = {H.visible_texts(ax)!r}") + + d, p, size_before = _scratch("defaults", "sample.png", "y.png") + res = _shrink(ax, p) + + out = os.path.join(d, "y.min.png") + size_after = _wait_file(out) + assert size_after is not None, ( + f"expected {out!r} beside the input; directory holds {_listing(d)!r}, " + f"reported path = {res['path']!r}") + assert os.path.isfile(p), ( + f"the original y.png must survive; directory holds {_listing(d)!r}") + assert _listing(d) == ["y.min.png", "y.png"], ( + f"with the defaults the dir should hold exactly y.png + y.min.png, holds " + f"{_listing(d)!r}") + assert os.path.dirname(os.path.realpath(res["path"])) == os.path.realpath(d), ( + f"reported path {res['path']!r} is not in the input's folder " + f"{os.path.realpath(d)!r}") + assert kit.rb_value(os.path.basename(res["path"]), "y.min.png"), ( + f"reported path {res['path']!r} should be named 'y.min.png'") + exp = H.expected_percent(size_before, size_after) + assert kit.rb_value(res["percent"], exp), ( + f"reported saving {res['percent']!r}% != expected {exp}% for " + f"{size_before} B -> {size_after} B (text={res['text']!r})") + + screenshot_assert( + "computation_test_default_output_location", + f"Image Shrinker's window with one result line: headline 'You saved " + f"{exp}%. Your shrunken image is here:' and an italic path ending in " + f"'y.min.png' that sits in the SAME folder as the input y.png (no " + f"'/minified/' component). Settings pane closed, drop zone visible.", + RESULTS_DIR, ax=ax) + finally: + _restore_toggles(ax, changes) diff --git a/macos/stefansl-image-shrinker/tests/test_ax_menus.py b/macos/stefansl-image-shrinker/tests/test_ax_menus.py new file mode 100644 index 0000000000000000000000000000000000000000..d6b4c8175bdab1aadb646b870ca8977574c304de --- /dev/null +++ b/macos/stefansl-image-shrinker/tests/test_ax_menus.py @@ -0,0 +1,480 @@ +"""AX menu tests for Image Shrinker (menu structure + what each safe item does). + +Scope of this lane: the menu bar (`Image Shrinker`, `Edit`, `Window`), the shortcuts and +mark chars its items expose, and the OBSERVABLE effect of the three safe activations +(`About …`, `Edit ▸ Reload`, `Window ▸ Zoom`). + +Environment facts this module relies on (all from recon, all observed on the reference): +* Electron app — an `AXMenuItem` only reacts to `AXPress` while its menu is OPEN, so every + activation goes through `H.rb_enter_menu(...)` → `H.press_menu_item(...)` → + `H.dismiss_menus(...)`. +* The window's AX subtree is EMPTY until the Chromium a11y handshake runs, therefore the + first statement of every test is `H.ensure_ax_ready(ax)`. +* NEVER activated here: `Quit Image Shrinker`, `Quit and Keep Windows`, `Minimize`, + `Minimize All`, and `Settings…` directly (the app throws unless the window has focus — + `H.rb_enter_settings` owns that path, and the settings pane belongs to another lane). +* `[OS]`-injected items (`AutoFill`, `Start Dictation…`, `Emoji & Symbols`, the + `Tile…`/`Move Window…` entries) are never asserted on. +""" +import json +import os +import subprocess +import time + +import pytest + +import imgshrink_helpers as H +import rb_testgen_kit as kit + + +def screenshot_assert(test_name, description, results_dir): + 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=8) + except Exception: + pass + af = os.path.join(ss_dir, "assertions.json") + data = {} + if os.path.exists(af): + try: + with open(af) as f: + data = json.load(f) + except Exception: + data = {} + data[f"{test_name}.png"] = description + with open(af, "w") as f: + json.dump(data, f, indent=2) + + +RESULTS_DIR = os.environ.get("RESULTS_DIR", os.path.dirname(os.path.abspath(__file__))) + +# The app's own name, as the reference exposes it on the app menu AND the window title. +APP_NAME = "Image Shrinker" + +# Keyword sets (EN + a couple of localisation fallbacks) — items are located by their +# VISIBLE label, never by index or tree path, so a differently-built recreation is driven +# by the same test. +KW_ABOUT = ["about", "über", "uber", "关于"] +KW_SETTINGS = ["setting", "preference", "prefs", "einstell", "设置"] +KW_QUIT = ["quit", "beenden", "退出"] +KW_RELOAD = ["reload", "refresh", "neu laden", "重新laden", "重新加载"] +KW_ZOOM = ["zoom", "vergrößern", "缩放"] + + +def _norm(s): + """Case/punctuation-insensitive key for a menu title ('Image Shrinker' -> 'imageshrinker').""" + return "".join(ch for ch in (s or "").lower() if ch.isalnum()) + + +def _window_title(ax): + w = H.main_window(ax) + return (w.name or "").strip() if w is not None else "" + + +def _names(items): + return [(it.name or "").strip() for it in items] + + +def _exact_item(items, name): + """The menu item whose visible label EQUALS `name` (ci), else None.""" + want = _norm(name) + for it in items: + if _norm(it.name) == want: + return it + return None + + +def _zoom_item(items): + """The plain `Zoom` entry of the Window menu — never `Zoom All`.""" + it = _exact_item(items, "Zoom") + if it is not None: + return it + narrow = [i for i in items + if any(k in (i.name or "").lower() for k in KW_ZOOM) + and "all" not in (i.name or "").lower()] + if narrow: + return narrow[0] + return H.find_menu_item(items, KW_ZOOM) + + +def _win_wh(ax): + """(width, height) of the app's main window, rounded to whole points, or None.""" + w = H.main_window(ax) + f = H.frame(ax, w) if w is not None else None + return (int(round(f[2])), int(round(f[3]))) if f else None + + +def _window_texts(ax, win): + return [(el.text or "").strip() + for el in ax.find_text_elements(root_id=win.id, max_results=40)] + + +def _about_panel_texts(ax): + """Texts of the window that shows the 'Version …' line (the About panel), or [].""" + for w in H.windows(ax): + texts = _window_texts(ax, w) + if any("version" in t.lower() for t in texts): + return texts + return [] + + +def _cmd_char(ax, item): + d = ax.get(item.id, ["AXMenuItemCmdChar", "AXMenuItemCmdModifiers"]) + return (d.get("AXMenuItemCmdChar"), d.get("AXMenuItemCmdModifiers")) + + +class TestMenuStructure: + """The shape of the menu bar, read straight out of the tree (no activation).""" + + @pytest.mark.rb(depth=0, jump_kind="none") + def test_menu_bar_has_app_edit_window(self, ax): + H.ensure_ax_ready(ax) + mbis = H.menu_bar_items(ax) + titles = _names(mbis) + wtitle = _window_title(ax) + # The app menu carries the application's name; accept the live window title as an + # equally valid source for it so the test does not depend on one spelling. + app_keys = {k for k in (_norm(APP_NAME), _norm(wtitle)) if k} + + found = {} + for el, nm in zip(mbis, titles): + key = _norm(nm) + if key in app_keys and "app" not in found: + found["app"] = (el, nm) + if key == "edit" and "edit" not in found: + found["edit"] = (el, nm) + if key == "window" and "window" not in found: + found["window"] = (el, nm) + + assert len(mbis) >= 3, ( + f"menu bar exposes {len(mbis)} app menus {titles}; expected at least 3 " + f"('{APP_NAME}', 'Edit', 'Window')") + + counts = {} + for key, label in (("app", APP_NAME), ("edit", "Edit"), ("window", "Window")): + assert key in found, ( + f"no '{label}' menu on the menu bar; observed titles={titles} " + f"(window title={wtitle!r})") + el, nm = found[key] + assert bool(el.enabled) is True, ( + f"menu '{nm}' is not enabled (observed AXEnabled={el.enabled!r}, expected True)") + items = H.menu_items(ax, el) + counts[nm] = len(items) + assert len(items) >= 1, ( + f"menu '{nm}' exposes {len(items)} children; expected at least 1 menu item " + f"(observed item names={_names(items)})") + + assert all(v >= 1 for v in counts.values()), ( + f"every app menu must own at least one item; observed counts={counts}") + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="app menu exposes 'Settings…' with ⌘, and 'Quit' with ⌘Q; " + "Edit exposes 'Reload' with ⌘R") + def test_app_menu_item_shortcuts(self, ax): + H.ensure_ax_ready(ax) + try: + items = H.rb_enter_menu(ax, ["image", "shrink"]) + assert items, ( + f"app menu opened but exposed no items; menu-bar titles=" + f"{_names(H.menu_bar_items(ax))}") + + settings = H.find_menu_item(items, KW_SETTINGS) + quit_it = H.find_menu_item(items, KW_QUIT) + assert settings is not None, ( + f"app menu has no Settings/Preferences item; observed items={_names(items)}") + assert quit_it is not None, ( + f"app menu has no Quit item; observed items={_names(items)}") + + s_char, s_mods = _cmd_char(ax, settings) + q_char, q_mods = _cmd_char(ax, quit_it) + screenshot_assert( + "menu_test_app_menu_shortcuts", + "The 'Image Shrinker' app menu is pulled down from the menu bar as a dark " + "dropdown listing 'About Image Shrinker', a separator, 'Settings…' with the " + "shortcut ⌘, on the right, a separator, 'Quit Image Shrinker' with ⌘Q and " + "'Quit and Keep Windows' with ⌥⌘Q. The small 340x550 Image Shrinker window " + "with its dashed 'Drag files here' drop zone is behind the menu.", + RESULTS_DIR) + + assert kit.rb_value(str(s_char or "").upper(), ","), ( + f"'{settings.name}' shortcut char is {s_char!r} (modifiers={s_mods!r}); " + f"expected ',' (⌘,)") + assert kit.rb_value(str(q_char or "").upper(), "Q"), ( + f"'{quit_it.name}' shortcut char is {q_char!r} (modifiers={q_mods!r}); " + f"expected 'Q' (⌘Q)") + H.dismiss_menus(ax) + + edit_items = H.rb_enter_menu(ax, ["edit"]) + reload_it = H.find_menu_item(edit_items, KW_RELOAD) + assert reload_it is not None, ( + f"Edit menu has no Reload item; observed items={_names(edit_items)}") + r_char, r_mods = _cmd_char(ax, reload_it) + assert kit.rb_value(str(r_char or "").upper(), "R"), ( + f"'{reload_it.name}' shortcut char is {r_char!r} (modifiers={r_mods!r}); " + f"expected 'R' (⌘R)") + finally: + H.dismiss_menus(ax) + + +class TestMenuNavigation: + """What the SAFE menu items actually do — every verdict is a reach/transition proof.""" + + @pytest.mark.rb(depth=1, jump_kind="reach", + expect="About panel window appears with the app name and a 'Version …' line") + def test_about_panel_opens_from_app_menu(self, ax): + H.ensure_ax_ready(ax) + try: + before = kit.rb_showing(ax) + items = H.rb_enter_menu(ax, ["image", "shrink"]) # nav — menu surface + about = H.find_menu_item(items, KW_ABOUT) + assert about is not None, ( + f"app menu has no About item; observed items={_names(items)}") + pressed = H.press_menu_item(ax, about) + H.wait_for(lambda: len(H.extra_windows(ax)) >= 1, timeout=6) + after = kit.rb_showing(ax) + + extras = H.extra_windows(ax) + all_windows = H.windows(ax) + screenshot_assert( + "menu_test_about_panel", + "A small About panel (~284x188) is in front of the Image Shrinker window, " + "showing the app icon, the bold title 'Image Shrinker', a 'Version …' line " + "under it and a 'Copyright © … Stefan Schulz-Lauterbach' line at the bottom. " + "No menu is pulled down any more.", + RESULTS_DIR) + + assert kit.rb_reach(before, after, target="Version", source=None), ( + f"activating '{about.name}' (AXPress ok={pressed}) did not bring up a panel " + f"containing a 'Version …' line. New AX nodes=" + f"{sorted(list(after - before))[:12]}") + assert len(extras) >= 1 and len(all_windows) >= 2, ( + f"expected a second window (the About panel) after '{about.name}': observed " + f"{len(all_windows)} window(s) titled " + f"{[w.name for w in all_windows]}, extras={len(extras)}") + panel_texts = _about_panel_texts(ax) + assert any(_norm(APP_NAME) in _norm(t) for t in panel_texts), ( + f"the About panel does not name the app; observed panel texts={panel_texts}, " + f"expected one containing {APP_NAME!r}") + finally: + H.dismiss_menus(ax) + H.rb_back_dialog(ax) + + @pytest.mark.rb(depth=1, jump_kind="reach", + expect="About panel's 'Version …' text is gone after Escape") + def test_about_panel_closes_again(self, ax): + H.ensure_ax_ready(ax) + try: + items = H.rb_enter_menu(ax, ["image", "shrink"]) # nav — menu surface + about = H.find_menu_item(items, KW_ABOUT) + assert about is not None, ( + f"app menu has no About item; observed items={_names(items)}") + H.press_menu_item(ax, about) + H.wait_for(lambda: H.text_is_visible(ax, ["version"]), timeout=6) + + open_state = H.visible_set(ax) # panel is OPEN here + assert any("version" in s.lower() for s in open_state), ( + f"About panel never showed a 'Version …' line, so its disappearance cannot be " + f"proven; visible now={sorted(open_state)}") + + H.dismiss_menus(ax) # Escape closes the panel + H.wait_for(lambda: not H.text_is_visible(ax, ["version"]), timeout=6) + closed_state = H.visible_set(ax) + + assert H.rb_reach_gone(open_state, closed_state, "Version"), ( + f"the About panel survived Escape: 'Version …' is still on screen. " + f"visible before close={sorted(s for s in open_state if 'version' in s.lower())}, " + f"after close={sorted(s for s in closed_state if 'version' in s.lower())}") + assert len(H.windows(ax)) >= 1, ( + f"the app lost its main window while closing the About panel; observed " + f"windows={[w.name for w in H.windows(ax)]}") + finally: + H.dismiss_menus(ax) + H.rb_back_dialog(ax) + + @pytest.mark.rb(depth=1, jump_kind="reach", + expect="the 'You saved …%' result line disappears after Edit ▸ Reload") + def test_edit_reload_clears_the_result_list(self, ax): + H.ensure_ax_ready(ax) + try: + d = H.workdir("menu") + p = H.copy_fixture("sample.png", d, "m.png") + res = H.shrink_file(ax, p) + assert res is not None, ( + f"could not put a result line on screen: shrinking {p} produced no " + f"'You saved …%' line (visible texts={H.visible_texts(ax)})") + + before = H.visible_set(ax) + assert any("you saved" in s.lower() for s in before), ( + f"result line missing before the reload; visible={sorted(before)}") + + items = H.rb_enter_menu(ax, ["edit"]) # nav — menu surface + reload_it = H.find_menu_item(items, KW_RELOAD) + assert reload_it is not None, ( + f"Edit menu has no Reload item; observed items={_names(items)}") + pressed = H.press_menu_item(ax, reload_it) + H.wait_for(lambda: len(H.saved_texts(ax)) == 0, timeout=8) + H.ensure_ax_ready(ax) # the renderer restarted — re-handshake + after = H.visible_set(ax) + + assert H.rb_reach_gone(before, after, "You saved"), ( + f"'{reload_it.name}' (AXPress ok={pressed}) did not clear the result list: " + f"result lines still on screen={H.saved_texts(ax)}") + finally: + H.dismiss_menus(ax) + H.dismiss_alerts(ax) + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="window frame 340x550 → full work area on Window ▸ Zoom, " + "restored on the second activation") + def test_window_menu_zoom_resizes_and_restores(self, ax): + H.ensure_ax_ready(ax) + try: + start_wh = _win_wh(ax) + assert start_wh is not None, ( + f"no measurable main window before zooming; windows=" + f"{[w.name for w in H.windows(ax)]}") + + items = H.rb_enter_menu(ax, ["window"]) # nav — menu surface + zoom = _zoom_item(items) + assert zoom is not None, ( + f"Window menu has no Zoom item; observed items={_names(items)}") + assert "all" not in (zoom.name or "").lower(), ( + f"picked the wrong entry {zoom.name!r} — the plain 'Zoom' is required, " + f"not 'Zoom All'; observed items={_names(items)}") + H.press_menu_item(ax, zoom) + H.wait_for(lambda: _win_wh(ax) != start_wh, timeout=4) + time.sleep(0.3) # let the zoom animation settle + zoomed_wh = _win_wh(ax) + assert zoomed_wh is not None, ( + f"lost the main window after activating '{zoom.name}'; windows=" + f"{[w.name for w in H.windows(ax)]}") + + screenshot_assert( + "menu_test_window_zoom", + "The Image Shrinker window is zoomed to fill the whole screen work area: the " + "pastel low-poly background and the dashed 'Drag files here' drop zone are " + "stretched across the display, traffic lights top-left, '⋯' glyph " + "bottom-right. No menu is pulled down.", + RESULTS_DIR) + + assert kit.rb_flip(tuple(start_wh), tuple(zoomed_wh)), ( + f"'{zoom.name}' did not change the window frame: {start_wh} -> {zoomed_wh} " + f"(expected the window to grow to the screen work area)") + grew = max(zoomed_wh[0] - start_wh[0], zoomed_wh[1] - start_wh[1]) + assert grew > 100, ( + f"'{zoom.name}' grew the window by only {grew} px " + f"({start_wh} -> {zoomed_wh}); expected >100 px in width or height") + + items2 = H.rb_enter_menu(ax, ["window"]) # nav — menu surface + zoom2 = _zoom_item(items2) + assert zoom2 is not None, ( + f"Window menu no longer offers Zoom while zoomed; observed items=" + f"{_names(items2)}") + H.press_menu_item(ax, zoom2) + H.wait_for(lambda: _win_wh(ax) != zoomed_wh, timeout=4) + time.sleep(0.3) + restored_wh = _win_wh(ax) + assert restored_wh is not None, ( + f"lost the main window while restoring; windows=" + f"{[w.name for w in H.windows(ax)]}") + dw = abs(restored_wh[0] - start_wh[0]) + dh = abs(restored_wh[1] - start_wh[1]) + assert dw <= 40 and dh <= 40, ( + f"second '{zoom2.name}' activation did not restore the window: {zoomed_wh} -> " + f"{restored_wh}, expected back to {start_wh} within ±40 px " + f"(observed Δw={dw}, Δh={dh})") + finally: + H.dismiss_menus(ax) + + +class TestMenuItemStates: + """Per-item state read off the open menus: order, mark char, enabled.""" + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="app menu items are About …, Settings…, Quit … in that order") + def test_app_menu_items_in_order(self, ax): + H.ensure_ax_ready(ax) + try: + items = H.rb_enter_menu(ax, ["image", "shrink"]) # nav — menu surface + names = [n for n in _names(items) if n] # drop the separators + lower = [n.lower() for n in names] + assert len(names) >= 3, ( + f"app menu exposes only {len(names)} named items {names}; expected at least " + f"About / Settings / Quit") + + blob = " | ".join(lower) + assert kit.rb_value(blob, "about"), ( + f"app menu has no About entry; observed named items={names}") + i_about = next(i for i, n in enumerate(lower) + if any(k in n for k in KW_ABOUT)) + i_settings = next((i for i, n in enumerate(lower) + if any(k in n for k in KW_SETTINGS)), -1) + i_quit = next((i for i, n in enumerate(lower) + if any(k in n for k in KW_QUIT)), -1) + + assert i_about == 0, ( + f"the first named app-menu item is {names[0]!r}; expected the About entry " + f"(observed order={names})") + assert i_settings > i_about, ( + f"Settings/Preferences is at index {i_settings}, About at {i_about}; expected " + f"Settings to come AFTER About (observed order={names})") + assert i_quit > i_settings, ( + f"Quit is at index {i_quit}, Settings at {i_settings}; expected Quit to come " + f"AFTER Settings (observed order={names})") + finally: + H.dismiss_menus(ax) + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="Window menu's 'Image Shrinker' window entry carries " + "AXMenuItemMarkChar '✓'") + def test_window_menu_lists_the_app_window_checked(self, ax): + H.ensure_ax_ready(ax) + try: + wtitle = _window_title(ax) + keys = {k for k in (_norm(APP_NAME), _norm(wtitle)) if k} + items = H.rb_enter_menu(ax, ["window"]) # nav — menu surface + assert items, ( + f"Window menu opened but exposed no items; menu-bar titles=" + f"{_names(H.menu_bar_items(ax))}") + + entry = next((it for it in items if _norm(it.name) in keys), None) + if entry is None: + entry = next((it for it in items + if keys and any(k in _norm(it.name) for k in keys)), None) + assert entry is not None, ( + f"Window menu does not list the app window (expected an entry named " + f"{APP_NAME!r} / {wtitle!r}); observed items={_names(items)}") + + mark = ax.get(entry.id, ["AXMenuItemMarkChar"]).get("AXMenuItemMarkChar") + assert kit.rb_value(mark, "✓"), ( + f"the window-list entry {entry.name!r} has AXMenuItemMarkChar={mark!r}; " + f"expected '✓' (the front window is checked)") + finally: + H.dismiss_menus(ax) + + @pytest.mark.rb(depth=1, jump_kind="value", expect="Edit ▸ Reload is present and enabled") + def test_edit_menu_has_reload_enabled_and_no_dead_items(self, ax): + H.ensure_ax_ready(ax) + try: + items = H.rb_enter_menu(ax, ["edit"]) # nav — menu surface + assert len(items) >= 1, ( + f"Edit menu exposes {len(items)} items; expected at least 1 " + f"(observed names={_names(items)})") + + reload_it = H.find_menu_item(items, KW_RELOAD) + assert reload_it is not None, ( + f"Edit menu has no Reload item; observed items={_names(items)}") + enabled = bool(reload_it.enabled) + assert enabled is True, ( + f"{reload_it.name!r} is disabled (observed AXEnabled={reload_it.enabled!r}, " + f"expected True)") + assert kit.rb_value((reload_it.name or "").lower(), "reload"), ( + f"the Edit menu's refresh command is named {reload_it.name!r}; expected a " + f"'Reload' entry (observed items={_names(items)})") + assert "AXPress" in (reload_it.actions or []), ( + f"{reload_it.name!r} exposes no AXPress action (observed actions=" + f"{reload_it.actions!r}), so it cannot be activated") + finally: + H.dismiss_menus(ax) diff --git a/macos/stefansl-image-shrinker/tests/test_ax_states.py b/macos/stefansl-image-shrinker/tests/test_ax_states.py new file mode 100644 index 0000000000000000000000000000000000000000..2bd903881649e0d70f95c912df77bc1f361d1f68 --- /dev/null +++ b/macos/stefansl-image-shrinker/tests/test_ax_states.py @@ -0,0 +1,372 @@ +"""AX state tests for Image Shrinker — preference toggles, enabled state, window state. + +Owned by this lane: CHECKED/ENABLED state of the six preference toggles, their +before/after flips (+ the one flip that has a visible consequence), the state +consistency of the settings pane, and the window / window-menu state attributes. + +Environment facts this module is built on (all OBSERVED, see recon.md): + * Electron app — the window's AX subtree is EMPTY until the Chromium a11y + handshake runs, so `H.ensure_ax_ready(ax)` is the FIRST statement of every test. + * The settings pane is ALWAYS in the AX tree (collapsed to 1x1 when closed), so the + toggles are located label-first through `H.find_toggle` — their AXTitle / + AXDescription are empty and their frames are 1x1 while the pane is shut. + * Preference values PERSIST across app restarts (the fixture does not reset them): + no test asserts a literal initial value; each reads `orig` at runtime, asserts the + FLIP relative to it and restores `orig` before returning. +""" +import json +import os +import subprocess +import time + +import pytest + +import imgshrink_helpers as H +import rb_testgen_kit as kit + + +def screenshot_assert(test_name, description, results_dir): + 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=8) + except Exception: + pass + af = os.path.join(ss_dir, "assertions.json") + data = {} + if os.path.exists(af): + try: + with open(af) as f: + data = json.load(f) + except Exception: + data = {} + data[f"{test_name}.png"] = description + with open(af, "w") as f: + json.dump(data, f, indent=2) + + +RESULTS_DIR = os.environ.get("RESULTS_DIR", os.path.dirname(os.path.abspath(__file__))) + + +def _shot(ax, test_name, description): + """Screenshot + VLM assertion, cropped to the app window when possible.""" + try: + H.screenshot_assert(test_name, description, out_dir=RESULTS_DIR, ax=ax) + except Exception: + screenshot_assert(test_name, description, RESULTS_DIR) + + +def flip_and_restore(ax, keywords): + """Open the pane, flip one preference, return (orig, flipped, restored).""" + assert H.rb_enter_settings(ax), "settings pane did not open" + cb = H.find_toggle(ax, keywords) + assert cb is not None, f"no preference toggle found for {keywords}" + orig = H.toggle_value(ax, cb) + flipped = H.press_toggle(ax, cb) + restored = H.set_toggle(ax, cb, orig) + return cb, orig, flipped, restored + + +def _assert_clean_flip(label, orig, flipped, restored): + """The shared verdict for a preference flip: a real 0<->1 transition, then restored.""" + assert orig in (0, 1), ( + f"{label}: AXValue before the flip was {orig!r}, expected a two-state 0/1 value") + assert kit.rb_flip(orig, flipped), ( + f"{label}: AXValue did not change on AXPress — before={orig!r} after={flipped!r}, " + f"expected a flip to {1 - orig if orig in (0, 1) else '1-orig'}") + assert flipped == 1 - orig, ( + f"{label}: AXValue after the flip was {flipped!r}, expected {1 - orig} " + f"(the exact complement of {orig})") + assert restored == orig, ( + f"{label}: AXValue after restoring was {restored!r}, expected the original {orig!r} " + f"— a leaked preference corrupts every later test") + + +def _enabled_of(ax, el): + """Fresh AXEnabled for an element, falling back to the value cached by find().""" + raw = ax.get(el.id, ["AXEnabled"]).get("AXEnabled") + if raw is None: + raw = el.enabled + return raw + + +class TestPreferenceToggles: + """One test per preference row: read the runtime value, flip it, restore it.""" + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="'Save shrinked files in same folder' AXValue flips 1→0 and is restored") + def test_same_folder_toggle_flips(self, ax): + assert H.ensure_ax_ready(ax), ( + "ensure_ax_ready() returned False — the Electron a11y handshake did not " + "expose the web UI, so no checkbox is reachable") + assert H.rb_enter_settings(ax), "settings pane did not open (rb_enter_settings returned False)" + + cb = H.find_toggle(ax, H.KW_SAME_FOLDER) + assert cb is not None, f"no preference toggle found for {H.KW_SAME_FOLDER}" + orig = H.toggle_value(ax, cb) + flipped = H.press_toggle(ax, cb) + + # CONSEQUENCE of this toggle: with it OFF the save-path row ("Choose folder" + # + a '> Open' button) is revealed; with it ON that row is gone. + off_val = flipped if flipped == 0 else H.set_toggle(ax, cb, 0) + chooser_when_off = H.text_is_visible(ax, ["choose folder"]) + _shot(ax, "state_test_same_folder_toggle", + "The Image Shrinker settings pane is open (dark overlay over the 340x550 window, " + "'Settings' heading at the top). The first row, 'Save shrinked files in same " + "folder', has its iOS-style switch turned OFF (grey, knob on the left), and " + "because of that a 'Choose folder' label plus a full-width blue '> Open' button " + "are now inserted directly underneath it; the remaining preference rows have " + "shifted down.") + + restored = H.set_toggle(ax, cb, orig) + chooser_after_restore = H.text_is_visible(ax, ["choose folder"]) + H.rb_back_settings(ax) + + _assert_clean_flip("Save shrinked files in same folder", orig, flipped, restored) + assert off_val == 0, ( + f"could not drive 'same folder' to 0: AXValue={off_val!r}, expected 0") + assert chooser_when_off is True, ( + f"'Choose folder' visible while 'same folder'=0 was {chooser_when_off!r}, " + f"expected True (the save-path row is the toggle's consequence)") + assert chooser_after_restore is (orig == 0), ( + f"'Choose folder' visible after restoring 'same folder' to {orig!r} was " + f"{chooser_after_restore!r}, expected {orig == 0} (it must be gone again " + f"whenever the toggle is 1)") + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="'Enable notifications' AXValue flips and is restored") + def test_notifications_toggle_flips(self, ax): + assert H.ensure_ax_ready(ax), ( + "ensure_ax_ready() returned False — the Electron a11y handshake did not " + "expose the web UI, so no checkbox is reachable") + cb, orig, flipped, restored = flip_and_restore(ax, H.KW_NOTIFICATION) + H.rb_back_settings(ax) + _assert_clean_flip("Enable notifications", orig, flipped, restored) + assert bool(_enabled_of(ax, cb)) is True, ( + f"'Enable notifications' AXEnabled={_enabled_of(ax, cb)!r} after the flip, " + f"expected True") + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="'Add .min suffix to shrinked files' AXValue flips and is restored") + def test_suffix_toggle_flips(self, ax): + assert H.ensure_ax_ready(ax), ( + "ensure_ax_ready() returned False — the Electron a11y handshake did not " + "expose the web UI, so no checkbox is reachable") + cb, orig, flipped, restored = flip_and_restore(ax, H.KW_SUFFIX) + H.rb_back_settings(ax) + _assert_clean_flip("Add .min suffix to shrinked files", orig, flipped, restored) + assert bool(_enabled_of(ax, cb)) is True, ( + f"'Add .min suffix to shrinked files' AXEnabled={_enabled_of(ax, cb)!r} after " + f"the flip, expected True") + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="'Add subfolder \"minified\"' AXValue flips 0→1 and is restored") + def test_subfolder_toggle_flips(self, ax): + assert H.ensure_ax_ready(ax), ( + "ensure_ax_ready() returned False — the Electron a11y handshake did not " + "expose the web UI, so no checkbox is reachable") + cb, orig, flipped, restored = flip_and_restore(ax, H.KW_SUBFOLDER) + H.rb_back_settings(ax) + _assert_clean_flip('Add subfolder "minified"', orig, flipped, restored) + assert bool(_enabled_of(ax, cb)) is True, ( + f"'Add subfolder \"minified\"' AXEnabled={_enabled_of(ax, cb)!r} after the flip, " + f"expected True") + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="'Clear result list, when shrinking new images' AXValue flips and is restored") + def test_clearlist_toggle_flips(self, ax): + assert H.ensure_ax_ready(ax), ( + "ensure_ax_ready() returned False — the Electron a11y handshake did not " + "expose the web UI, so no checkbox is reachable") + cb, orig, flipped, restored = flip_and_restore(ax, H.KW_CLEARLIST) + H.rb_back_settings(ax) + _assert_clean_flip("Clear result list, when shrinking new images", + orig, flipped, restored) + assert bool(_enabled_of(ax, cb)) is True, ( + f"'Clear result list…' AXEnabled={_enabled_of(ax, cb)!r} after the flip, " + f"expected True") + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="'Check for updates' AXValue flips and is restored") + def test_updatecheck_toggle_flips(self, ax): + assert H.ensure_ax_ready(ax), ( + "ensure_ax_ready() returned False — the Electron a11y handshake did not " + "expose the web UI, so no checkbox is reachable") + cb, orig, flipped, restored = flip_and_restore(ax, H.KW_UPDATECHECK) + H.rb_back_settings(ax) + _assert_clean_flip("Check for updates", orig, flipped, restored) + assert bool(_enabled_of(ax, cb)) is True, ( + f"'Check for updates' AXEnabled={_enabled_of(ax, cb)!r} after the flip, " + f"expected True") + + +class TestStateConsistency: + """The pane as a whole: six enabled, two-state, uniquely-labelled preference rows.""" + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="the settings pane exposes 6 enabled two-state preference rows") + def test_all_six_preferences_are_boolean_and_enabled(self, ax): + assert H.ensure_ax_ready(ax), ( + "ensure_ax_ready() returned False — the Electron a11y handshake did not " + "expose the web UI, so no checkbox is reachable") + assert H.rb_enter_settings(ax), "settings pane did not open (rb_enter_settings returned False)" + + rows = H.setting_rows(ax) + labels = [(lb or "").strip() for lb, _cb in rows] + values = {} + enabled = {} + for lb, cb in rows: + key = (lb or "").strip() + values[key] = H.toggle_value(ax, cb) + enabled[key] = _enabled_of(ax, cb) + ids = {cb.id for _lb, cb in rows} + + _shot(ax, "state_test_all_six_preferences", + "The Image Shrinker settings pane is open: a near-black overlay filling the " + "340x550 window with the 'Settings' heading at the top and SIX preference rows " + "below it, each showing a text label on the left and an iOS-style switch on the " + "right (blue/knob-right when on, grey/knob-left when off). The rows read 'Save " + "shrinked files in same folder', 'Enable notifications', 'Add .min suffix to " + "shrinked files', 'Add subfolder \"minified\"', 'Clear result list, when " + "shrinking new images' and 'Check for updates'. An 'App by' logo sits bottom-left " + "and an '✕' glyph bottom-right. No result list and no file dialog are visible.") + + H.rb_back_settings(ax) + + assert kit.rb_value(len(rows), 6), ( + f"settings pane exposed {len(rows)} preference row(s) {labels!r}, expected exactly 6") + assert len(rows) == 6, ( + f"settings pane exposed {len(rows)} preference row(s) {labels!r}, expected exactly 6") + assert len(ids) == 6, ( + f"the 6 rows paired onto only {len(ids)} distinct checkbox element(s) — " + f"labels {labels!r} were mis-paired to the same control") + for key in labels: + assert key, ( + f"a preference row has an empty label; labels observed = {labels!r}, " + f"expected 6 non-empty labels") + assert bool(enabled[key]) is True, ( + f"row '{key}': AXEnabled={enabled[key]!r}, expected True (every preference " + f"toggle is always enabled)") + assert values[key] in (0, 1), ( + f"row '{key}': AXValue={values[key]!r}, expected a two-state 0/1 value") + assert len(set(labels)) == len(labels), ( + f"preference row labels are not unique: {labels!r} (expected 6 distinct labels)") + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="a preference returns to its original AXValue after two consecutive flips") + def test_toggle_state_survives_a_second_flip_pair(self, ax): + assert H.ensure_ax_ready(ax), ( + "ensure_ax_ready() returned False — the Electron a11y handshake did not " + "expose the web UI, so no checkbox is reachable") + assert H.rb_enter_settings(ax), "settings pane did not open (rb_enter_settings returned False)" + + cb = H.find_toggle(ax, H.KW_SUBFOLDER) + assert cb is not None, f"no preference toggle found for {H.KW_SUBFOLDER}" + orig = H.toggle_value(ax, cb) + mid = H.press_toggle(ax, cb) + final = H.press_toggle(ax, cb) + restored = H.set_toggle(ax, cb, orig) + H.rb_back_settings(ax) + + assert orig in (0, 1), ( + f"'Add subfolder \"minified\"' AXValue before the flips was {orig!r}, " + f"expected a two-state 0/1 value") + assert kit.rb_flip(orig, mid), ( + f"first AXPress did not change the value — before={orig!r} after={mid!r}, " + f"expected {1 - orig if orig in (0, 1) else '1-orig'}") + assert mid == 1 - orig, ( + f"value after the FIRST flip was {mid!r}, expected {1 - orig}") + assert final == orig, ( + f"value after the SECOND flip was {final!r}, expected it back at the original " + f"{orig!r} (two presses must be a no-op)") + assert restored == orig, ( + f"value after the restore pass was {restored!r}, expected the original {orig!r}") + + +class TestWindowAndMenuState: + """Window-level state attributes and the Window menu's checked window entry.""" + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="main window reports AXMain true, AXMinimized false, AXFullScreen " + "false and subrole AXStandardWindow") + def test_window_state_attributes(self, ax): + assert H.ensure_ax_ready(ax), ( + "ensure_ax_ready() returned False — the Electron a11y handshake did not " + "expose the web UI, so the window state cannot be read") + w = H.main_window(ax) + assert w is not None, ( + f"no app window found (windows={len(H.windows(ax))}), expected 1 main window") + + attrs = ax.get(w.id, ["AXMain", "AXMinimized", "AXFullScreen", "AXSubrole"]) + if not attrs.get("AXMain"): + # Not front-most yet (parallel desktop use): raise once, never minimize/zoom. + ax.action(w.id, "AXRaise") + time.sleep(0.5) + attrs = ax.get(w.id, ["AXMain", "AXMinimized", "AXFullScreen", "AXSubrole"]) + + assert bool(attrs.get("AXMain")) is True, ( + f"AXMain={attrs.get('AXMain')!r} on window '{w.name}', expected True " + f"(the app has exactly one, main, window)") + assert bool(attrs.get("AXMinimized")) is False, ( + f"AXMinimized={attrs.get('AXMinimized')!r} on window '{w.name}', expected False " + f"(the window must be on screen, not in the Dock)") + assert bool(attrs.get("AXFullScreen")) is False, ( + f"AXFullScreen={attrs.get('AXFullScreen')!r} on window '{w.name}', expected False " + f"(the window opens as a normal 340x550 panel)") + assert kit.rb_value(attrs.get("AXSubrole"), "AXStandardWindow"), ( + f"AXSubrole={attrs.get('AXSubrole')!r} on window '{w.name}', " + f"expected 'AXStandardWindow'") + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="the Window menu entry for the app window carries the '✓' mark char") + def test_window_menu_marks_the_active_window(self, ax): + assert H.ensure_ax_ready(ax), ( + "ensure_ax_ready() returned False — the Electron a11y handshake did not " + "expose the web UI, so the menu bar cannot be driven reliably") + + w = H.main_window(ax) + assert w is not None, "no app window found, expected 1 main window" + window_title = (w.name or "").strip() + names = [n for n in (window_title, os.environ.get("APP_NAME", ""), + "Image Shrinker") if n] + keywords = [] + for n in names: + low = n.lower() + if low not in keywords: + keywords.append(low) + for tok in low.split(): + if len(tok) >= 5 and tok not in keywords: + keywords.append(tok) + + items = H.rb_enter_menu(ax, ["window", "fenster", "窗口"]) + item_names = [(it.name or "") for it in items] + candidates = [it for it in items + if any(k in (it.name or "").lower() for k in keywords)] + # The window list sits at the BOTTOM of the Window menu, so the last match is + # the window entry (deterministic; no picking-by-outcome). + entry = candidates[-1] if candidates else None + + marks = {} + info = {} + if entry is not None: + info = ax.get(entry.id, ["AXMenuItemMarkChar", "AXEnabled"]) + marks[entry.name or ""] = info.get("AXMenuItemMarkChar") + H.dismiss_menus(ax) + + assert items, ( + f"the Window menu exposed no items (menu bar = " + f"{[m.name for m in H.menu_bar_items(ax)]!r}), expected a 'Window' menu") + assert entry is not None, ( + f"no Window-menu entry matching the app window {window_title!r} " + f"(keywords {keywords!r}); items observed = {item_names!r}") + mark = info.get("AXMenuItemMarkChar") + assert kit.rb_value(mark, "✓"), ( + f"Window ▸ '{entry.name}' AXMenuItemMarkChar={mark!r}, expected '✓' " + f"(the entry for the active window is check-marked); marks read = {marks!r}") + entry_enabled = info.get("AXEnabled") + if entry_enabled is None: + entry_enabled = entry.enabled + assert bool(entry_enabled) is True, ( + f"Window ▸ '{entry.name}' AXEnabled={entry_enabled!r}, expected True " + f"(the active window's entry is selectable)") diff --git a/macos/stefansl-image-shrinker/tests/test_ax_structure.py b/macos/stefansl-image-shrinker/tests/test_ax_structure.py new file mode 100644 index 0000000000000000000000000000000000000000..325dff6b4cb84139dd6b5e1f178ac7bd36fe9647 --- /dev/null +++ b/macos/stefansl-image-shrinker/tests/test_ax_structure.py @@ -0,0 +1,380 @@ +"""AX structure tests for Image Shrinker (widget tree shape + shape deltas). + +Everything is measured through `imgshrink_helpers` (deployed next to this module), which +performs the Chromium/Electron a11y handshake and locates widgets by visible label + +role, never by tree index or DOM internals — so the same module drives the reference app +and a recreation built on a different UI stack. + +Two facts shape every test here: + * the window's AX subtree is EMPTY until the handshake runs -> `H.ensure_ax_ready(ax)` + is the first statement of every test; + * the settings pane is ALWAYS in the tree (collapsed to 1x1 when closed), so + "the element exists" proves nothing -> the behavioural tests measure VISIBILITY + (`H.visible_texts`) and window/widget COUNTS, not mere presence. +""" +import json, os, subprocess, time + +import pytest + +import imgshrink_helpers as H +import rb_testgen_kit as kit + + +def screenshot_assert(test_name, description, results_dir): + """Take a screenshot and record the 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=8) + except Exception: + pass + af = os.path.join(ss_dir, "assertions.json") + data = {} + if os.path.exists(af): + try: + with open(af) as f: + data = json.load(f) + except Exception: + data = {} + data[f"{test_name}.png"] = description + with open(af, "w") as f: + json.dump(data, f, indent=2) + + +RESULTS_DIR = os.environ.get("RESULTS_DIR", os.path.dirname(os.path.abspath(__file__))) + +# ── Reference inventory (from the recon AX_TREE dump + its role histogram) ── +WINDOW_TITLE = "Image Shrinker" +REF_W, REF_H = 340.0, 550.0 +SIZE_TOL = 40.0 # a recreation may differ slightly in metrics +MAX_W, MAX_H = 600.0, 900.0 # a wrong layout (full-size window) must still fail +# role -> minimum count observed on the reference (closed pane, empty result list) +EXPECTED_ROLES = { + "webarea": 1, # the Chromium web UI (a native recreation may nest deeper) + "toolbar": 1, # hiddenInset title bar + "button": 3, # the three traffic lights + "checkbox": 6, # the six preference toggles + "heading": 2, # "Drag files here" (h1) + "Settings" (h3) + "link": 1, # footer logo + "menu_bar": 1, + "menu_bar_item": 3, # Image Shrinker / Edit / Window (+ Apple) +} +MIN_ROLE_DIVERSITY = 8 +CLOSED_PANE_TEXTS = 2 # 'Drag files here' + 'only SVG, JPG, GIF and PNG allowed' +OPEN_PANE_TEXTS = 10 # + 'Settings', the 6 row labels, 'App by' +KW_OPEN_DIALOG = ["open", "öffnen", "abrir", "打开", "选择"] + + +# ── local read-only measurement helpers (no AX plumbing re-implemented) ── +def _role_histogram(ax, cap=900): + """{role: count} over the whole app subtree — the same walk recon used.""" + hist = {} + for el in ax._walk_tree(None, cap): + r = el.role or "unknown" + hist[r] = hist.get(r, 0) + 1 + return hist + + +def _role_count(ax, hist, role, want): + """Count for `role`, re-checked with a targeted search if the walk came up short + (a deeper/bigger recreation tree could hit the walk cap).""" + n = hist.get(role, 0) + if n < want: + n = max(n, len(ax.find(role=role, max_results=max(4 * want, 12)))) + return n + + +def _window_title(ax, w): + return str(ax.get(w.id, ["AXTitle"]).get("AXTitle") or w.name or "").strip() + + +def _buttons(ax): + return ax.find(role="button", max_results=20) + + +def _has_open_button(btns): + return [b for b in btns if "open" in (b.name or "").lower()] + + +def _pane_texts_normalized(ax, texts): + """The "save shrinked files in same folder" preference PERSISTS across app launches, + so an earlier test could have left it OFF — which inserts an extra 'Choose folder' / + '> Open' row into the pane. Put it back to the app's own default and re-read, so the + pane inventory is always measured in the state the reference launches with.""" + if not any("choose folder" in (t or "").lower() for t in texts): + return texts + cb = H.find_toggle(ax, H.KW_SAME_FOLDER) + if cb is not None: + H.set_toggle(ax, cb, 1) + return H.visible_texts(ax) + return texts + + +class TestStructureGate: + """Existence-only checks — deliberately the MINORITY of this module (3 of 8).""" + + @pytest.mark.rb(depth=0, jump_kind="none") + def test_gate_main_window(self, ax): + assert H.ensure_ax_ready(ax), "AX tree never became readable (Electron a11y handshake failed)" + wins = H.windows(ax) + assert len(wins) == 1, f"expected exactly 1 app window, got {len(wins)}: {[w.name for w in wins]}" + w = H.main_window(ax) + assert w is not None, "no main window element found on the application" + + attrs = ax.get(w.id, ["AXTitle", "AXSubrole", "AXMain"]) + title = _window_title(ax, w) + assert title == WINDOW_TITLE, f"window title is {title!r}, expected {WINDOW_TITLE!r}" + subrole = str(attrs.get("AXSubrole") or "") + assert subrole == "AXStandardWindow", f"window AXSubrole is {subrole!r}, expected 'AXStandardWindow'" + assert bool(attrs.get("AXMain")) is True, f"window AXMain is {attrs.get('AXMain')!r}, expected True" + + f = H.frame(ax, w) + assert f is not None, "window exposes no AXPosition/AXSize" + _x, _y, wd, ht = f + assert wd < MAX_W and ht < MAX_H, ( + f"window is {wd:.0f}x{ht:.0f} — far larger than the reference {REF_W:.0f}x{REF_H:.0f} " + f"(hard ceiling {MAX_W:.0f}x{MAX_H:.0f}); the layout does not match") + assert abs(wd - REF_W) <= SIZE_TOL, f"window width {wd:.0f}, expected {REF_W:.0f}±{SIZE_TOL:.0f}" + assert abs(ht - REF_H) <= SIZE_TOL, f"window height {ht:.0f}, expected {REF_H:.0f}±{SIZE_TOL:.0f}" + + screenshot_assert( + "structure_test_gate_main_window", + "Exactly one small (~340x550) frameless Image Shrinker window, pastel low-poly " + "background. Three traffic-light buttons at the very top left, no window title " + "text. Upper third: a dashed rounded drop-zone rectangle containing bold italic " + "'Drag files here' with the smaller line 'only SVG, JPG, GIF and PNG allowed' " + "under it. Below that an empty result area, and a small '...' (three-dots) glyph " + "at the bottom right corner. No settings overlay, no dialog, no menu open.", + RESULTS_DIR) + + @pytest.mark.rb(depth=0, jump_kind="none") + def test_gate_expected_roles_and_counts(self, ax): + assert H.ensure_ax_ready(ax), "AX tree never became readable (Electron a11y handshake failed)" + hist = _role_histogram(ax) + assert hist, "walking the application subtree yielded no elements at all" + + missing = {} + for role, want in sorted(EXPECTED_ROLES.items()): + got = _role_count(ax, hist, role, want) + if got < want: + missing[role] = (got, want) + assert not missing, ( + "role inventory below the reference: " + + ", ".join(f"{r}: got {g}, expected >={w}" for r, (g, w) in sorted(missing.items())) + + f" | full histogram: {dict(sorted(hist.items()))}") + + diversity = len(hist) + assert diversity >= MIN_ROLE_DIVERSITY, ( + f"only {diversity} distinct AX roles ({sorted(hist)}), expected >={MIN_ROLE_DIVERSITY}") + + @pytest.mark.rb(depth=0, jump_kind="none") + def test_gate_window_chrome_buttons(self, ax): + assert H.ensure_ax_ready(ax), "AX tree never became readable (Electron a11y handshake failed)" + w = H.main_window(ax) + assert w is not None, "no main window element found on the application" + btns = ax.find(role="button", root_id=w.id, max_results=20) + assert len(btns) >= 3, f"window exposes only {len(btns)} button(s), expected >=3 traffic lights" + + subroles = set() + for b in btns: + sr = ax.get(b.id, ["AXSubrole"]).get("AXSubrole") + if sr: + subroles.add(str(sr)) + assert "AXCloseButton" in subroles, f"no AXCloseButton among the window buttons; subroles={sorted(subroles)}" + assert "AXMinimizeButton" in subroles, f"no AXMinimizeButton among the window buttons; subroles={sorted(subroles)}" + zoom = subroles & {"AXFullScreenButton", "AXZoomButton"} + assert zoom, ( + "no zoom/full-screen window button (reference exposes AXFullScreenButton); " + f"subroles={sorted(subroles)}") + # NOTE: read-only on purpose — pressing any traffic light closes, minimizes or + # full-screens the window, none of which is undoable through AX. + + +class TestShapeDeltas: + """Behavioural checks: a trigger CHANGES the shape of the tree, then it is restored.""" + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="visible text count 2 → 10 when the settings pane opens") + def test_settings_pane_reveals_ten_texts(self, ax): + assert H.ensure_ax_ready(ax), "AX tree never became readable (Electron a11y handshake failed)" + before = H.visible_texts(ax) + n_before = len(before) + assert n_before == CLOSED_PANE_TEXTS, ( + f"{n_before} visible text(s) on the home surface, expected {CLOSED_PANE_TEXTS}: {before}") + + assert H.rb_enter_settings(ax), "the settings pane never became visible after every reveal path was tried" + after = _pane_texts_normalized(ax, H.visible_texts(ax)) + n_after = len(after) + + assert kit.rb_flip(n_before, n_after, "2 -> 10 visible texts"), ( + f"visible text count did not change when the settings pane opened: {n_before} -> {n_after}") + assert n_after == OPEN_PANE_TEXTS, ( + f"{n_after} visible text(s) with the pane open, expected {OPEN_PANE_TEXTS}: {after}") + for exact in ("Settings", "Check for updates"): + assert exact in after, f"{exact!r} is not visible with the pane open; visible={after}" + assert exact not in before, f"{exact!r} was already visible with the pane CLOSED; visible={before}" + + screenshot_assert( + "structure_test_settings_pane_reveals_ten_texts", + "The settings pane is open: a near-black overlay fills the whole Image Shrinker " + "window, headed 'Settings'. Six preference rows, each a text label on the left and " + "an iOS-style switch on the right: 'Save shrinked files in same folder', 'Enable " + "notifications', 'Add .min suffix to shrinked files', 'Add subfolder \"minified\"', " + "'Clear result list, when shrinking new images', 'Check for updates'. An 'App by' " + "logo sits at the bottom left and an 'x' close glyph at the bottom right. The drop " + "zone is hidden behind the overlay.", + RESULTS_DIR) + + H.rb_back_settings(ax) + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="visible text count 10 → 2 when the settings pane closes") + def test_settings_pane_hides_again(self, ax): + assert H.ensure_ax_ready(ax), "AX tree never became readable (Electron a11y handshake failed)" + assert H.rb_enter_settings(ax), "the settings pane never became visible after every reveal path was tried" + open_texts = _pane_texts_normalized(ax, H.visible_texts(ax)) + n_open = len(open_texts) + assert n_open == OPEN_PANE_TEXTS, ( + f"{n_open} visible text(s) with the pane open, expected {OPEN_PANE_TEXTS}: {open_texts}") + + assert H.rb_back_settings(ax), "the settings pane is still visible after Escape / its close glyph" + closed_texts = H.visible_texts(ax) + n_closed = len(closed_texts) + + assert kit.rb_flip(n_open, n_closed, "10 -> 2 visible texts"), ( + f"visible text count did not change when the settings pane closed: {n_open} -> {n_closed}") + assert n_closed == CLOSED_PANE_TEXTS, ( + f"{n_closed} visible text(s) after closing the pane, expected {CLOSED_PANE_TEXTS}: {closed_texts}") + assert "Check for updates" not in closed_texts, ( + f"a preference label is still visible after closing the pane; visible={closed_texts}") + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="button count 3 → 4 ('> Open' save-path button) when 'same folder' is switched off") + def test_savepath_row_adds_a_button(self, ax): + assert H.ensure_ax_ready(ax), "AX tree never became readable (Electron a11y handshake failed)" + assert H.rb_enter_settings(ax), "the settings pane never became visible after every reveal path was tried" + + cb = H.find_toggle(ax, H.KW_SAME_FOLDER) + assert cb is not None, "no toggle found on the 'save shrinked files in same folder' row" + before_val = H.toggle_value(ax, cb) + # The value persists across launches — normalise to the app's own default first so + # the "before" shape is the reference shape whatever an earlier test left behind. + assert H.set_toggle(ax, cb, 1) == 1, "could not switch 'same folder' ON to establish the baseline shape" + + btns_before = _buttons(ax) + n_before = len(btns_before) + assert n_before == 3, ( + f"{n_before} button(s) with 'same folder' ON, expected 3 (the traffic lights): " + f"{[b.name for b in btns_before]}") + assert not _has_open_button(btns_before), ( + f"a save-path button already exists while 'same folder' is ON: " + f"{[b.name for b in _has_open_button(btns_before)]}") + + assert H.set_toggle(ax, cb, 0) == 0, "the 'same folder' toggle did not switch OFF" + btns_after = _buttons(ax) + n_after = len(btns_after) + + assert kit.rb_flip(n_before, n_after, "3 -> 4 buttons"), ( + f"button count did not change when 'same folder' was switched off: {n_before} -> {n_after}") + assert n_after == n_before + 1, ( + f"button count {n_before} -> {n_after}, expected exactly one NEW button " + f"(3 -> 4); names={[b.name for b in btns_after]}") + opened = _has_open_button(btns_after) + assert opened, ( + "no button whose name contains 'Open' appeared for the save-path row; " + f"names={[b.name for b in btns_after]}") + + screenshot_assert( + "structure_test_savepath_row_adds_a_button", + "The settings pane is open with the first switch ('Save shrinked files in same " + "folder') turned OFF (grey), which has inserted an extra save-path row directly " + "under it: the label 'Choose folder' and a full-width blue button reading '> Open'. " + "The remaining preference rows ('Enable notifications', 'Add .min suffix…', " + "'Add subfolder \"minified\"', 'Clear result list…', 'Check for updates') are " + "pushed down. 'App by' logo bottom left, 'x' glyph bottom right.", + RESULTS_DIR) + + # restore: the extra button must be gone again once the toggle is back ON + assert H.set_toggle(ax, cb, 1) == 1, "could not restore the 'same folder' toggle to ON" + btns_restored = _buttons(ax) + assert len(btns_restored) == n_before, ( + f"{len(btns_restored)} button(s) after restoring 'same folder' ON, expected {n_before}: " + f"{[b.name for b in btns_restored]}") + assert not _has_open_button(btns_restored), ( + f"the save-path button survived restoring the toggle: " + f"{[b.name for b in _has_open_button(btns_restored)]}") + if before_val == 0: + H.set_toggle(ax, cb, before_val) # leave the persisted value exactly as found + # Close the pane cheaply (Escape); the fixture relaunches the app per test, so the + # only state that outlives this test is the toggle, which is restored above. + H.send_key(H.MENU_KEY_ESCAPE) + + @pytest.mark.rb(depth=0, jump_kind="transition", + expect="link count 1 → 2 after an image is shrunk") + def test_result_line_adds_a_link(self, ax): + assert H.ensure_ax_ready(ax), "AX tree never became readable (Electron a11y handshake failed)" + links_before = ax.find(role="link", max_results=10) + n_before = len(links_before) + assert n_before == 1, ( + f"{n_before} link(s) on the freshly launched home surface, expected 1 (the footer logo): " + f"{[l.name for l in links_before]}") + + d = H.workdir("struct") + p = H.copy_fixture("sample.png", d, "s.png") + res = H.shrink_file(ax, p) + assert res is not None, f"no result line appeared after handing {p} to the app" + + links_after = ax.find(role="link", max_results=10) + n_after = len(links_after) + assert kit.rb_flip(n_before, n_after, "1 -> 2 links"), ( + f"link count did not change after the shrink: {n_before} -> {n_after}") + assert n_after == n_before + 1, ( + f"link count {n_before} -> {n_after}, expected exactly one NEW result-line link " + f"(1 -> 2); names={[l.name for l in links_after]}") + # NOTE: the new link is the output path — read only, pressing it reveals the file + # in the Finder. + + H.screenshot_assert( + "structure_test_result_line_adds_a_link", + "The Image Shrinker home window with one result entry now rendered under the " + "dashed drop zone: a small grey line reading 'You saved %. Your shrunken image " + "is here:' with an italic file path (ending in s.min.png) as a link beneath it. " + "'Drag files here' and 'only SVG, JPG, GIF and PNG allowed' are still visible " + "above; no settings overlay and no dialog.", + RESULTS_DIR, ax=ax) + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="window count 1 → 2 (native 'Open' chooser) when the drop zone is activated, back to 1 on Cancel") + def test_file_chooser_is_a_second_window(self, ax): + assert H.ensure_ax_ready(ax), "AX tree never became readable (Electron a11y handshake failed)" + n_before = len(H.windows(ax)) + assert n_before == 1, f"expected exactly 1 window before opening the chooser, got {n_before}" + + w = H.rb_enter_file_dialog(ax) + assert w is not None, "activating the drop zone opened no file-chooser window" + title = _window_title(ax, w) + assert any(k in title.lower() for k in KW_OPEN_DIALOG), ( + f"the new window is titled {title!r}, expected an 'Open' file chooser") + f = H.frame(ax, w) + assert f is not None, f"the {title!r} window exposes no AXPosition/AXSize" + assert f[2] > 200 and f[3] > 150, ( + f"the {title!r} window is only {f[2]:.0f}x{f[3]:.0f}, expected a real chooser (>200x150)") + + n_after = len(H.windows(ax)) + assert kit.rb_flip(n_before, n_after, "1 -> 2 windows"), ( + f"window count did not change when the drop zone was activated: {n_before} -> {n_after}") + assert n_after == 2, f"expected 2 windows with the chooser open, got {n_after}" + + screenshot_assert( + "structure_test_file_chooser_is_a_second_window", + "A native macOS 'Open' file-chooser panel (roughly 800x448) is in front of the " + "small Image Shrinker window: a Favorites/sidebar list on the left, a file browser " + "on the right, and 'Cancel' plus 'Open' buttons at the bottom right. The app window " + "with its drop zone is still visible behind/around the panel.", + RESULTS_DIR) + + assert H.rb_back_dialog(ax), "the file chooser could not be dismissed (Cancel / Escape)" + n_final = len(H.windows(ax)) + assert n_final == n_before, ( + f"{n_final} window(s) after cancelling the chooser, expected back to {n_before}") diff --git a/macos/stefansl-image-shrinker/tests/test_ax_text.py b/macos/stefansl-image-shrinker/tests/test_ax_text.py new file mode 100644 index 0000000000000000000000000000000000000000..d99042c89015d09758903dbd1ede6f7957a469b1 --- /dev/null +++ b/macos/stefansl-image-shrinker/tests/test_ax_text.py @@ -0,0 +1,527 @@ +"""AX text tests for Image Shrinker — exact on-screen wording and how it changes. + +Two environment facts from the recon shape every test in this module: + +1. The app is Electron: the window's AX subtree is EMPTY until the Chromium a11y + handshake runs, so `H.ensure_ax_ready(ax)` is the FIRST statement of every test. +2. The whole settings pane is ALWAYS in the AX tree — when closed it is merely + collapsed to a 1x1 box at the window's left edge. `ax.find_text_elements()` therefore + finds `Check for updates` even when nothing is on screen. So this module NEVER asserts + on raw tree text: it asserts on `H.visible_texts(ax)` / `H.text_is_visible(...)` / + `H.is_visible(...)`, which measure real frames on a real window. +""" +import json +import os +import re +import subprocess +import time + +import pytest + +import imgshrink_helpers as H +import rb_testgen_kit as kit + + +def screenshot_assert(test_name, description, results_dir): + 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=8) + except Exception: + pass + af = os.path.join(ss_dir, "assertions.json") + data = {} + if os.path.exists(af): + try: + with open(af) as f: + data = json.load(f) + except Exception: + data = {} + data[f"{test_name}.png"] = description + with open(af, "w") as f: + json.dump(data, f, indent=2) + + +RESULTS_DIR = os.environ.get("RESULTS_DIR", os.path.dirname(os.path.abspath(__file__))) + +# ── the exact wording observed on the reference (recon ## TEXT) ────────────── +APP_NAME = "Image Shrinker" +HEADLINE = "Drag files here" +FORMAT_HINT = "only SVG, JPG, GIF and PNG allowed" +FORMATS = ("SVG", "JPG", "GIF", "PNG") +SETTINGS_HEADING = "Settings" +FOOTER = "App by" +CHOOSE_FOLDER = "Choose folder" +PREF_LABELS = [ + "Save shrinked files in same folder", + "Enable notifications", + "Add .min suffix to shrinked files", + 'Add subfolder "minified"', + "Clear result list, when shrinking new images", + "Check for updates", +] +PANE_TEXTS = [SETTINGS_HEADING] + PREF_LABELS +RESULT_HEADLINE_RE = re.compile(r"You saved \d+%\. Your shrunken image is here:") +VERSION_RE = re.compile(r"[Vv]ersion\s+\d+") + +# keyword fallbacks so a recreation that words a label differently is still located +KW_HINT = ("allowed", "only ", "erlaubt", "允许", "支持") +KW_HEADLINE = ("drag", "drop", "ziehen", "拖") +KW_SETTINGS = ("setting", "preference", "einstell", "设置") +KW_ABOUT = ("about", "über", "uber", "关于") +KW_CHOOSE_FOLDER = ("choose folder", "select folder", "ordner", "文件夹") + + +# ── small local utilities (no navigation, no app source knowledge) ─────────── +def _stripped(texts): + """The app's own labels carry no padding, but a recreation's might — compare + stripped strings everywhere.""" + return [str(t).strip() for t in (texts or []) if str(t).strip()] + + +def _shot(name, description, ax=None): + """Screenshot + VLM assertion. Prefers the helper's app-cropped capture so the + judge sees the window, not the whole desktop; falls back to the plain capture.""" + try: + H.screenshot_assert(name, description, out_dir=RESULTS_DIR, ax=ax) + return + except Exception: + pass + try: + screenshot_assert(name, description, RESULTS_DIR) + except Exception: + pass + + +def _window_title(ax): + """The main window's visible title (AXTitle), or ''.""" + w = H.main_window(ax) + if w is None: + return "" + title = ax.get(w.id, ["AXTitle"]).get("AXTitle") + if not title: + title = w.name or "" + return str(title).strip() + + +def _pick_heading(headings, exact, keywords): + """A heading located by its VISIBLE LABEL (AXTitle/AXDescription) — never by index + or tree path. Exact wording first, keyword fallback second.""" + for h in headings: + if (h.name or "").strip() == exact: + return h + for h in headings: + low = (h.name or "").strip().lower() + if low and any(k in low for k in keywords): + return h + return None + + +def _heading_level(ax, el): + """The heading level carried in AXValue, normalised to an int when possible + (Chromium reports it as a number, other stacks as a string).""" + v = ax.get(el.id, ["AXValue"]).get("AXValue") + if v is None or v == "": + v = el.value + if isinstance(v, bool): + return v + if isinstance(v, float): + return int(v) if float(v).is_integer() else v + if isinstance(v, int): + return v + if isinstance(v, str): + m = re.search(r"\d+", v) + return int(m.group(0)) if m else v.strip() + return v + + +def _panel_texts(ax): + """Text of every app window that is NOT the main window (the About panel, an + alert, the file chooser). Falls back to ALL windows so the read still works if the + panel itself became the AXMain window.""" + mw = H.main_window(ax) + wins = H.windows(ax) + out = [] + for w in wins: + if mw is not None and w.id == mw.id: + continue + for el in ax.find_text_elements(root_id=w.id, max_results=40): + if (el.text or "").strip(): + out.append(el.text.strip()) + if not any(VERSION_RE.search(t) for t in out) and len(wins) > 1: + for w in wins: + for el in ax.find_text_elements(root_id=w.id, max_results=40): + if (el.text or "").strip(): + out.append(el.text.strip()) + return out + + +def _wait_panel_texts(ax, timeout=6.0): + """Poll the extra window until its version line has rendered.""" + deadline = time.time() + timeout + last = [] + while time.time() < deadline: + last = _panel_texts(ax) + if any(VERSION_RE.search(t) for t in last): + return last + time.sleep(0.4) + return last + + +class TestHomeSurfaceText: + """The two strings the app shows before anything has been done to it.""" + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="home surface shows exactly 'Drag files here' and " + "'only SVG, JPG, GIF and PNG allowed'") + def test_dropzone_headline_and_format_hint(self, ax): + assert H.ensure_ax_ready(ax), ( + "the Chromium a11y handshake failed — the window's AX subtree stayed empty, " + "so no text could be read at all") + + texts = _stripped(H.visible_texts(ax)) + joined = " | ".join(texts) + + assert HEADLINE in texts, ( + f"no on-screen element reads exactly {HEADLINE!r}; " + f"visible texts = {texts}") + assert kit.rb_value(joined, HEADLINE), ( + f"the drop-zone headline {HEADLINE!r} is not part of the visible text; " + f"visible texts = {texts}") + + hint = next((t for t in texts + if t != HEADLINE and any(k in t.lower() for k in KW_HINT)), None) + assert hint is not None, ( + f"the accepted-formats hint (reference wording: {FORMAT_HINT!r}) is not on " + f"screen; visible texts = {texts}") + missing = [f for f in FORMATS if f not in hint.upper()] + assert not missing, ( + f"the format hint {hint!r} does not name {missing}; the reference reads " + f"{FORMAT_HINT!r}; visible texts = {texts}") + + assert len(texts) == 2, ( + f"the home surface should show exactly 2 strings " + f"({HEADLINE!r} + the format hint) — the closed settings pane contributes " + f"nothing on screen — but {len(texts)} were visible: {texts}") + + _shot("text_test_home_text", + "Image Shrinker's 340x550 frameless home window over a pastel low-poly " + "background. Inside a dashed drop-zone rectangle the bold italic headline " + "reads exactly 'Drag files here' and the smaller grey line below it reads " + "exactly 'only SVG, JPG, GIF and PNG allowed'. No settings labels, no " + "result line and no percentage text are visible; three traffic lights sit " + "top-left and a '...' glyph bottom-right.", + ax) + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="'Drag files here' is exposed as a level-1 heading and the " + "window title is 'Image Shrinker'") + def test_dropzone_headline_is_a_heading(self, ax): + assert H.ensure_ax_ready(ax), ( + "the Chromium a11y handshake failed — the window's AX subtree stayed empty") + + headings = ax.find(role="heading", max_results=10) + names = [(h.name or "").strip() for h in headings] + el = _pick_heading(headings, HEADLINE, KW_HEADLINE) + assert el is not None, ( + f"no heading element is named {HEADLINE!r} — headings found: {names}; " + f"visible texts = {_stripped(H.visible_texts(ax))}") + + level = _heading_level(ax, el) + assert kit.rb_value(str(level), "1"), ( + f"the {HEADLINE!r} heading reports level {level!r}; the reference exposes it " + f"as a level-1 heading (AXValue == 1). Headings found: {names}") + + title = _window_title(ax) + assert title == APP_NAME, ( + f"the window title is {title!r}, expected {APP_NAME!r} " + f"(window titles seen: {[(w.name or '') for w in H.windows(ax)]})") + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="no 'You saved …' line is on screen before anything is shrunk") + def test_result_list_is_empty_on_launch(self, ax): + assert H.ensure_ax_ready(ax), ( + "the Chromium a11y handshake failed — the window's AX subtree stayed empty") + + saved = _stripped(H.saved_texts(ax)) + assert saved == [], ( + f"the result list already shows saving lines on a freshly launched app: " + f"{saved}") + assert kit.rb_value(len(saved), 0), ( + f"expected 0 result lines on launch, observed {len(saved)}: {saved}") + + texts = _stripped(H.visible_texts(ax)) + with_percent = [t for t in texts if "%" in t] + assert with_percent == [], ( + f"a percentage is displayed before anything has been shrunk: {with_percent} " + f"(all visible texts = {texts})") + + +class TestSettingsPaneText: + """Wording inside the slide-in settings pane. Presence in the tree proves nothing + here — every assertion is about what is actually ON SCREEN.""" + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="the pane shows the 6 preference labels plus the 'Settings' " + "heading") + def test_all_six_preference_labels_are_visible(self, ax): + assert H.ensure_ax_ready(ax), ( + "the Chromium a11y handshake failed — the window's AX subtree stayed empty") + try: + assert H.rb_enter_settings(ax), ( + "could not open the settings pane (tried the '...' glyph, a real click " + "at the window's bottom-right corner, Cmd+, and the app menu); " + f"visible texts = {_stripped(H.visible_texts(ax))}") + + texts = _stripped(H.visible_texts(ax)) + joined = " | ".join(texts) + + assert kit.rb_value(joined, 'Add subfolder "minified"'), ( + 'the pane does not show the label \'Add subfolder "minified"\'; ' + f"visible texts = {texts}") + + for want in PANE_TEXTS: + assert want in texts, ( + f"the opened settings pane does not show the exact text {want!r}; " + f"visible texts = {texts}") + + assert any(FOOTER.lower() in t.lower() for t in texts), ( + f"the footer text {FOOTER!r} (next to the CLICKPRESS logo link) is not " + f"on screen; visible texts = {texts}") + + _shot("text_test_settings_labels", + "The settings pane is open as a near-black overlay filling the " + "Image Shrinker window. It shows the heading 'Settings' and six " + "preference rows, each with a label on the left and an iOS-style " + "switch on the right; the labels read, top to bottom: 'Save shrinked " + "files in same folder', 'Enable notifications', 'Add .min suffix to " + "shrinked files', 'Add subfolder \"minified\"', 'Clear result list, " + "when shrinking new images', 'Check for updates'. The text 'App by' " + "with the CLICKPRESS logo is bottom-left and an X glyph bottom-right.", + ax) + finally: + H.rb_back_settings(ax) + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="'Check for updates' is absent from the visible text before " + "the pane opens and present after") + def test_settings_labels_are_hidden_before_the_pane_opens(self, ax): + assert H.ensure_ax_ready(ax), ( + "the Chromium a11y handshake failed — the window's AX subtree stayed empty") + + probe = "Check for updates" + before = _stripped(H.visible_texts(ax)) + assert probe not in set(before), ( + f"{probe!r} is already on screen before the settings pane was opened — the " + f"pane must be hidden on launch; visible texts = {before}") + + try: + assert H.rb_enter_settings(ax), ( + "could not open the settings pane; " + f"visible texts = {_stripped(H.visible_texts(ax))}") + after = _stripped(H.visible_texts(ax)) + + assert kit.rb_flip(probe in set(before), probe in set(after)), ( + f"{probe!r} did not change visibility when the pane opened " + f"(before={before}, after={after}) — note that the label is in the AX " + f"tree the whole time, so only VISIBILITY can prove the transition") + assert probe in set(after), ( + f"{probe!r} is still not on screen after opening the settings pane; " + f"visible texts = {after}") + assert len(after) > len(before), ( + f"opening the pane did not add any visible text: before={before}, " + f"after={after}") + finally: + H.rb_back_settings(ax) + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="'Settings' is exposed as a heading element and is visible " + "only while the pane is open") + def test_settings_heading_is_a_heading_element(self, ax): + assert H.ensure_ax_ready(ax), ( + "the Chromium a11y handshake failed — the window's AX subtree stayed empty") + try: + assert H.rb_enter_settings(ax), ( + "could not open the settings pane; " + f"visible texts = {_stripped(H.visible_texts(ax))}") + + headings = ax.find(role="heading", max_results=10) + names = [(h.name or "").strip() for h in headings] + el = _pick_heading(headings, SETTINGS_HEADING, KW_SETTINGS) + assert el is not None, ( + f"no heading element is named {SETTINGS_HEADING!r} while the pane is " + f"open — headings found: {names}; " + f"visible texts = {_stripped(H.visible_texts(ax))}") + + assert H.is_visible(ax, el), ( + f"the {SETTINGS_HEADING!r} heading is in the AX tree but not on screen " + f"(frame={H.frame(ax, el)}); " + f"visible texts = {_stripped(H.visible_texts(ax))}") + + level = _heading_level(ax, el) + assert kit.rb_value(str(level), "3"), ( + f"the {SETTINGS_HEADING!r} heading reports level {level!r}; the " + f"reference exposes it as a level-3 heading (AXValue == 3). " + f"Headings found: {names}") + finally: + closed = H.rb_back_settings(ax) + + assert closed, ( + "could not close the settings pane again (Escape and the X glyph both " + f"failed); visible texts = {_stripped(H.visible_texts(ax))}") + assert not H.is_visible(ax, el), ( + f"the {SETTINGS_HEADING!r} heading is still on screen after the pane was " + f"closed (frame={H.frame(ax, el)}); " + f"visible texts = {_stripped(H.visible_texts(ax))}") + + +class TestTextChangesOnInteraction: + """Text the app PRODUCES: the result line, the save-path row, the About panel.""" + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="a shrink adds 'You saved %. Your shrunken image is " + "here:' plus the output path") + def test_result_line_wording_after_a_shrink(self, ax): + assert H.ensure_ax_ready(ax), ( + "the Chromium a11y handshake failed — the window's AX subtree stayed empty") + + d = H.workdir("text") + src = H.copy_fixture("sample.png", d, as_name="t.png") + + res = H.shrink_file(ax, src) + assert res is not None, ( + f"handing {src} to the app produced no result line within the timeout; " + f"visible texts = {_stripped(H.visible_texts(ax))}") + + headline = str(res.get("text") or "").strip() + assert kit.rb_value(headline, "Your shrunken image is here:"), ( + f"the result headline is {headline!r}; the reference reads " + f"'You saved %. Your shrunken image is here:'") + assert RESULT_HEADLINE_RE.fullmatch(headline), ( + f"the result headline {headline!r} does not match the reference wording " + f"'You saved %. Your shrunken image is here:'; " + f"visible texts = {_stripped(H.visible_texts(ax))}") + + path = str(res.get("path") or "").strip() + assert path.startswith("/"), ( + f"the line under the headline is not an output path: {path!r}; " + f"visible texts = {_stripped(H.visible_texts(ax))}") + assert path.endswith("t.min.png"), ( + f"the displayed output path {path!r} does not end with 't.min.png' " + f"(input was {src}); visible texts = {_stripped(H.visible_texts(ax))}") + + _shot("text_test_result_line", + "The Image Shrinker home surface now shows one result line under the " + "drop zone: a small grey headline reading 'You saved N%. Your shrunken " + "image is here:' (N is the measured saving, about 86 for the bundled " + "sample PNG) and, right below it, an italic file path link ending in " + "'t.min.png'. The drop-zone texts 'Drag files here' and 'only SVG, JPG, " + "GIF and PNG allowed' are still visible above the result line.", + ax) + + @pytest.mark.rb(depth=2, jump_kind="transition", + expect="'Choose folder' and the '> Open' button label appear when " + "'Save … in same folder' is switched off") + def test_savepath_row_text_appears_with_the_folder_toggle(self, ax): + assert H.ensure_ax_ready(ax), ( + "the Chromium a11y handshake failed — the window's AX subtree stayed empty") + + cb = None + orig = None + try: + assert H.rb_enter_settings(ax), ( + "could not open the settings pane; " + f"visible texts = {_stripped(H.visible_texts(ax))}") + + cb = H.find_toggle(ax, H.KW_SAME_FOLDER) + assert cb is not None, ( + "could not locate the 'Save shrinked files in same folder' toggle from " + f"its row label; visible texts = {_stripped(H.visible_texts(ax))}") + + orig = H.toggle_value(ax, cb) + assert orig is not None, ( + "the 'same folder' toggle exposes no 0/1 AXValue " + f"(read {orig!r}) — its state cannot be observed") + if orig != 1: + # values persist across launches; establish the documented baseline + H.set_toggle(ax, cb, 1) + + before = _stripped(H.visible_texts(ax)) + assert CHOOSE_FOLDER not in set(before), ( + f"{CHOOSE_FOLDER!r} is on screen while 'same folder' is still ON; " + f"visible texts = {before}") + + H.set_toggle(ax, cb, 0) + after = _stripped(H.visible_texts(ax)) + new = [t for t in after if t not in set(before)] + + assert kit.rb_flip(CHOOSE_FOLDER in set(before), + CHOOSE_FOLDER in set(after)), ( + f"switching 'same folder' off did not change the visibility of " + f"{CHOOSE_FOLDER!r} (before={before}, after={after})") + assert CHOOSE_FOLDER in set(after), ( + f"{CHOOSE_FOLDER!r} is not on screen after switching 'same folder' " + f"off; visible texts = {after} (new texts = {new})") + assert any("open" in t.lower() for t in new), ( + "no save-path button label containing 'Open' appeared (the reference " + f"shows a '> Open' button); new texts = {new}, all visible = {after}") + + H.set_toggle(ax, cb, 1 if orig is None else orig) + assert not H.text_is_visible(ax, list(KW_CHOOSE_FOLDER)), ( + f"{CHOOSE_FOLDER!r} is still on screen after restoring the 'same " + f"folder' toggle to {orig!r}; " + f"visible texts = {_stripped(H.visible_texts(ax))}") + finally: + if cb is not None and orig is not None: + H.set_toggle(ax, cb, orig) + H.rb_back_settings(ax) + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="About panel shows the app name and a 'Version ' line") + def test_about_panel_reports_app_name_and_version(self, ax): + assert H.ensure_ax_ready(ax), ( + "the Chromium a11y handshake failed — the window's AX subtree stayed empty") + try: + items = H.rb_enter_menu(ax, ["image", "shrink"]) + assert items, ( + "the app menu did not open or exposed no items; menu-bar items = " + f"{[(m.name or '') for m in H.menu_bar_items(ax)]}") + + about = H.find_menu_item(items, list(KW_ABOUT)) + assert about is not None, ( + "the app menu has no 'About …' item; items = " + f"{[(i.name or '') for i in items]}") + assert H.press_menu_item(ax, about), ( + f"pressing the menu item {about.name!r} failed") + + texts = _stripped(_wait_panel_texts(ax)) + joined = " | ".join(texts) + assert texts, ( + "activating 'About …' exposed no extra window with any text; windows = " + f"{[(w.name or '') for w in H.windows(ax)]}") + + assert any(t == APP_NAME or APP_NAME.lower() in t.lower() for t in texts), ( + f"the About panel does not name the app ({APP_NAME!r}); " + f"panel texts = {texts}") + + version_line = next((t for t in texts if VERSION_RE.search(t)), None) + assert version_line is not None, ( + "the About panel shows no 'Version ' line; " + f"panel texts = {texts}") + assert kit.rb_value(joined, "Version"), ( + f"no 'Version' wording in the About panel; panel texts = {texts}") + + _shot("text_test_about_panel", + "A small About panel sits in front of the Image Shrinker window. It " + "shows the app icon, the app name 'Image Shrinker', a line reading " + "'Version' followed by a version number, and a 'Copyright ...' line. " + "The main window with the 'Drag files here' drop zone is still " + "visible behind or beside the panel.", + ax) + finally: + H.dismiss_menus(ax) + try: + H.rb_back_dialog(ax) + except Exception: + pass diff --git a/macos/stefansl-image-shrinker/tests/testcase_counts.json b/macos/stefansl-image-shrinker/tests/testcase_counts.json new file mode 100644 index 0000000000000000000000000000000000000000..f7bea1a5ca7c3b66b4b2fc70f21464060422e849 --- /dev/null +++ b/macos/stefansl-image-shrinker/tests/testcase_counts.json @@ -0,0 +1,39 @@ +{ + "ax_total": 54, + "vlm_total": 16, + "ax_by_lane": { + "test_ax_buttons.py": 8, + "test_ax_computation.py": 10, + "test_ax_menus.py": 9, + "test_ax_states.py": 10, + "test_ax_structure.py": 8, + "test_ax_text.py": 9 + }, + "vlm_by_dir": { + "buttons": 3, + "computation": 3, + "menus": 2, + "states": 1, + "structure": 4, + "text": 3 + }, + "vlm_names": [ + "button_test_dropzone_file_chooser.png", + "button_test_open_settings_glyph.png", + "button_test_savepath_button_revealed.png", + "computation_test_default_output_location.png", + "computation_test_suffix_off_in_place.png", + "computation_test_unsupported_format_alert.png", + "menu_test_about_panel.png", + "menu_test_window_zoom.png", + "state_test_all_six_preferences.png", + "structure_test_file_chooser_is_a_second_window.png", + "structure_test_gate_main_window.png", + "structure_test_result_line_adds_a_link.png", + "structure_test_settings_pane_reveals_ten_texts.png", + "text_test_about_panel.png", + "text_test_home_text.png", + "text_test_settings_labels.png" + ], + "frozen_at": "stage2_finalize" +} \ No newline at end of file diff --git a/macos/stefansl-image-shrinker/tests/verifier_helpers.py b/macos/stefansl-image-shrinker/tests/verifier_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..ce369cdae8db3a7427890d1636f8f5a3201dbef1 --- /dev/null +++ b/macos/stefansl-image-shrinker/tests/verifier_helpers.py @@ -0,0 +1,753 @@ +""" +verifier_helpers.py — High-level AX testing patterns for macOS app verification. + +v6 core library. Encodes all robust testing patterns as reusable functions +so verifier agents call high-level APIs instead of building from scratch. + +Depends on: ax_helpers.py (AXHelper class) +""" + +import datetime +import os +import re +import signal +import subprocess +import time +from collections import Counter + +# --------------------------------------------------------------------------- +# Key codes (macOS virtual key codes) +# --------------------------------------------------------------------------- +KC_LEFT_ARROW = 123 +KC_RIGHT_ARROW = 124 +KC_UP_ARROW = 126 +KC_DOWN_ARROW = 125 +KC_SPACE = 49 +KC_RETURN = 36 +KC_TAB = 48 +KC_ESCAPE = 53 +KC_Q = 12 +KC_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": , "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)" + ) diff --git a/macos/stefansl-image-shrinker/vlm_assertions.json b/macos/stefansl-image-shrinker/vlm_assertions.json new file mode 100644 index 0000000000000000000000000000000000000000..a9e33e7da013dee32c62b6abf1b19650a81e6aa1 --- /dev/null +++ b/macos/stefansl-image-shrinker/vlm_assertions.json @@ -0,0 +1,231 @@ +{ + "schema_version": 2, + "instance_id": "macos/stefansl-image-shrinker", + "grading": { + "mode": "deferred", + "model": null, + "scored_separately": true + }, + "totals": { + "assertions": 16, + "with_verdict": 0, + "calibrated": 0, + "usable": null, + "scored_records": 0, + "unbacked_records": 0 + }, + "assertions": [ + { + "id": "button_test_open_settings_glyph.png", + "screenshot": "button_test_open_settings_glyph.png", + "assertion": "Image Shrinker's settings pane is open: a near-black overlay fills the 340x550 window with the 'Settings' heading at the top and six preference rows, each a left-aligned label plus an iOS-style switch on the right — 'Save shrinked files in same folder', 'Enable notifications', 'Add .min suffix to shrinked files', 'Add subfolder \"minified\"', 'Clear result list, when shrinking new images', 'Check for updates'. An 'App by' + CLICKPRESS logo sits bottom-left and an x glyph bottom-right. The drop-zone home surface is no longer visible.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "button_test_open_settings_glyph.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "button_test_dropzone_file_chooser.png", + "screenshot": "button_test_dropzone_file_chooser.png", + "assertion": "Activating Image Shrinker's drop zone opened a native macOS 'Open' file chooser panel (roughly 800x448) in front of the small 340x550 app window. The panel shows a Favorites sidebar on the left, a file browser on the right, and 'Cancel' and 'Open' buttons in its bottom-right corner. The app window behind it still shows the dashed drop zone.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "button_test_dropzone_file_chooser.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "button_test_savepath_button_revealed.png", + "screenshot": "button_test_savepath_button_revealed.png", + "assertion": "Image Shrinker's settings pane with 'Save shrinked files in same folder' switched OFF: a new row is inserted directly under it showing the label 'Choose folder' and a full-width blue button reading '> Open'. The remaining preference rows ('Enable notifications', 'Add .min suffix to shrinked files', 'Add subfolder \"minified\"', 'Clear result list, when shrinking new images', 'Check for updates') have shifted down.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "button_test_savepath_button_revealed.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "computation_test_unsupported_format_alert.png", + "screenshot": "computation_test_unsupported_format_alert.png", + "assertion": "A modal alert sheet in front of Image Shrinker's window carrying the app icon, the message 'Only PNG SVG, JPG and GIF allowed' and a single OK button. The window behind it still shows the empty drop zone — NO 'You saved N%' result line was added for the .txt file.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "computation_test_unsupported_format_alert.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "computation_test_suffix_off_in_place.png", + "screenshot": "computation_test_suffix_off_in_place.png", + "assertion": "Image Shrinker's window with one result line whose italic path ends in 'x.png' — WITHOUT a '.min' before the extension, because the '.min suffix' preference was switched off; the headline reads 'You saved 86%. Your shrunken image is here:'. Settings pane closed.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "computation_test_suffix_off_in_place.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "computation_test_default_output_location.png", + "screenshot": "computation_test_default_output_location.png", + "assertion": "Image Shrinker's window with one result line: headline 'You saved 86%. Your shrunken image is here:' and an italic path ending in 'y.min.png' that sits in the SAME folder as the input y.png (no '/minified/' component). Settings pane closed, drop zone visible.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "computation_test_default_output_location.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "menu_test_about_panel.png", + "screenshot": "menu_test_about_panel.png", + "assertion": "A small About panel (~284x188) is in front of the Image Shrinker window, showing the app icon, the bold title 'Image Shrinker', a 'Version …' line under it and a 'Copyright © … Stefan Schulz-Lauterbach' line at the bottom. No menu is pulled down any more.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "menu_test_about_panel.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "menu_test_window_zoom.png", + "screenshot": "menu_test_window_zoom.png", + "assertion": "The Image Shrinker window is zoomed to fill the whole screen work area: the pastel low-poly background and the dashed 'Drag files here' drop zone are stretched across the display, traffic lights top-left, '⋯' glyph bottom-right. No menu is pulled down.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "menu_test_window_zoom.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "state_test_all_six_preferences.png", + "screenshot": "state_test_all_six_preferences.png", + "assertion": "The Image Shrinker settings pane is open: a near-black overlay filling the 340x550 window with the 'Settings' heading at the top and SIX preference rows below it, each showing a text label on the left and an iOS-style switch on the right (blue/knob-right when on, grey/knob-left when off). The rows read 'Save shrinked files in same folder', 'Enable notifications', 'Add .min suffix to shrinked files', 'Add subfolder \"minified\"', 'Clear result list, when shrinking new images' and 'Check for updates'. An 'App by' logo sits bottom-left and an '✕' glyph bottom-right. No result list and no file dialog are visible.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "state_test_all_six_preferences.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "structure_test_gate_main_window.png", + "screenshot": "structure_test_gate_main_window.png", + "assertion": "Exactly one small (~340x550) frameless Image Shrinker window, pastel low-poly background. Three traffic-light buttons at the very top left, no window title text. Upper third: a dashed rounded drop-zone rectangle containing bold italic 'Drag files here' with the smaller line 'only SVG, JPG, GIF and PNG allowed' under it. Below that an empty result area, and a small '...' (three-dots) glyph at the bottom right corner. No settings overlay, no dialog, no menu open.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "structure_test_gate_main_window.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "structure_test_settings_pane_reveals_ten_texts.png", + "screenshot": "structure_test_settings_pane_reveals_ten_texts.png", + "assertion": "The settings pane is open: a near-black overlay fills the whole Image Shrinker window, headed 'Settings'. Six preference rows, each a text label on the left and an iOS-style switch on the right: 'Save shrinked files in same folder', 'Enable notifications', 'Add .min suffix to shrinked files', 'Add subfolder \"minified\"', 'Clear result list, when shrinking new images', 'Check for updates'. An 'App by' logo sits at the bottom left and an 'x' close glyph at the bottom right. The drop zone is hidden behind the overlay.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "structure_test_settings_pane_reveals_ten_texts.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "structure_test_result_line_adds_a_link.png", + "screenshot": "structure_test_result_line_adds_a_link.png", + "assertion": "The Image Shrinker home window with one result entry now rendered under the dashed drop zone: a small grey line reading 'You saved %. Your shrunken image is here:' with an italic file path (ending in s.min.png) as a link beneath it. 'Drag files here' and 'only SVG, JPG, GIF and PNG allowed' are still visible above; no settings overlay and no dialog.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "structure_test_result_line_adds_a_link.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "structure_test_file_chooser_is_a_second_window.png", + "screenshot": "structure_test_file_chooser_is_a_second_window.png", + "assertion": "A native macOS 'Open' file-chooser panel (roughly 800x448) is in front of the small Image Shrinker window: a Favorites/sidebar list on the left, a file browser on the right, and 'Cancel' plus 'Open' buttons at the bottom right. The app window with its drop zone is still visible behind/around the panel.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "structure_test_file_chooser_is_a_second_window.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "text_test_home_text.png", + "screenshot": "text_test_home_text.png", + "assertion": "Image Shrinker's 340x550 frameless home window over a pastel low-poly background. Inside a dashed drop-zone rectangle the bold italic headline reads exactly 'Drag files here' and the smaller grey line below it reads exactly 'only SVG, JPG, GIF and PNG allowed'. No settings labels, no result line and no percentage text are visible; three traffic lights sit top-left and a '...' glyph bottom-right.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "text_test_home_text.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "text_test_settings_labels.png", + "screenshot": "text_test_settings_labels.png", + "assertion": "The settings pane is open as a near-black overlay filling the Image Shrinker window. It shows the heading 'Settings' and six preference rows, each with a label on the left and an iOS-style switch on the right; the labels read, top to bottom: 'Save shrinked files in same folder', 'Enable notifications', 'Add .min suffix to shrinked files', 'Add subfolder \"minified\"', 'Clear result list, when shrinking new images', 'Check for updates'. The text 'App by' with the CLICKPRESS logo is bottom-left and an X glyph bottom-right.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "text_test_settings_labels.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "text_test_about_panel.png", + "screenshot": "text_test_about_panel.png", + "assertion": "A small About panel sits in front of the Image Shrinker window. It shows the app icon, the app name 'Image Shrinker', a line reading 'Version' followed by a version number, and a 'Copyright ...' line. The main window with the 'Drag files here' drop zone is still visible behind or beside the panel.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "text_test_about_panel.png", + "rigor": null, + "verdict": null, + "calibration": null + } + ], + "merged_from_files": 6, + "source_shapes": { + "dict_str": 16 + } +} \ No newline at end of file diff --git a/macos/sunjw-fhash/LICENSE b/macos/sunjw-fhash/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d159169d1050894d3ea3b98e1c965c4058208fe1 --- /dev/null +++ b/macos/sunjw-fhash/LICENSE @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES 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 OF SUCH DAMAGES. + + 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 greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 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 General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/macos/sunjw-fhash/instance.json b/macos/sunjw-fhash/instance.json new file mode 100644 index 0000000000000000000000000000000000000000..f9ac997ed282d3fbf8a3b51b7de472edd62dea84 --- /dev/null +++ b/macos/sunjw-fhash/instance.json @@ -0,0 +1,10 @@ +{ + "schema_version": 1, + "instance_id": "macos/sunjw-fhash", + "platform": "macos", + "repo": "https://github.com/sunjw/fhash", + "commit": "45403b0e349b0bf9c2b8dc014bff8070bd33892f", + "patches": [], + "package": null, + "license": null +} \ No newline at end of file diff --git a/macos/sunjw-fhash/reference/build.sh b/macos/sunjw-fhash/reference/build.sh new file mode 100644 index 0000000000000000000000000000000000000000..66595cff7569c63e555b7a7f44b7557c8736a49e --- /dev/null +++ b/macos/sunjw-fhash/reference/build.sh @@ -0,0 +1,98 @@ +#!/usr/bin/env bash +# +# build.sh — Reproducible, self-contained build for fHash (macOS). +# +# fHash is a native macOS Xcode application: +# * UI: Swift 5.0 + Objective-C++ (AppKit, storyboard-based) +# * Hashing: bundled C++ (source/Algorithms: MD5, SHA1, SHA256, SHA512) +# * Bridging: Objective-C++ (.mm) between Swift and the C++ engine +# +# It links ONLY against system frameworks (AppKit/Foundation) and the system +# libiconv. There are NO Homebrew / CocoaPods / Swift PM / npm dependencies, +# so nothing needs to be fetched or installed beyond the Xcode toolchain. +# +# The build requires no source modifications; it compiles as-is with the +# installed Xcode (Swift 5.10 toolchain builds the SWIFT_VERSION = 5.0 sources). +# +# Everything this build needs lives inside this script. On a fresh clone into +# which only build.sh (and launch.sh) were copied, `bash build.sh` produces +# fHash.app. + +set -euo pipefail + +# All paths are derived from the script location — no absolute paths hardcoded. +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" + +WORKSPACE="$SCRIPT_DIR/trunk/fHash.xcworkspace" +SCHEME="fHash" +CONFIGURATION="Release" +DERIVED_DATA="$SCRIPT_DIR/build/DerivedData" + +# Where the finished .app is placed. Honors APP_OUTPUT_DIR if the pipeline sets +# it; otherwise lands next to this script (deterministic, cwd-independent). +OUTPUT_DIR="${APP_OUTPUT_DIR:-$SCRIPT_DIR}" + +echo "==> fHash build starting" +echo " script dir : $SCRIPT_DIR" +echo " workspace : $WORKSPACE" +echo " output dir : $OUTPUT_DIR" + +# --------------------------------------------------------------------------- +# 1. Dependencies +# --------------------------------------------------------------------------- +# No third-party packages are required. The only prerequisite is the Xcode +# command-line toolchain (xcodebuild). This check is idempotent and safe to +# re-run on a clean machine. +if ! command -v xcodebuild >/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 1 +fi +echo "==> Using $(xcodebuild -version | tr '\n' ' ')" + +if [ ! -e "$WORKSPACE" ]; then + echo "ERROR: Xcode workspace not found at $WORKSPACE" >&2 + exit 1 +fi + +# --------------------------------------------------------------------------- +# 2. Build +# --------------------------------------------------------------------------- +# Code signing is disabled per pipeline requirement (CODE_SIGN_IDENTITY="" and +# CODE_SIGNING_ALLOWED=NO). CODE_SIGNING_REQUIRED=NO guards against the +# App-Sandbox entitlement forcing a signature. +echo "==> Cleaning previous derived data" +rm -rf "$DERIVED_DATA" + +echo "==> Building scheme '$SCHEME' ($CONFIGURATION)" +xcodebuild \ + -workspace "$WORKSPACE" \ + -scheme "$SCHEME" \ + -configuration "$CONFIGURATION" \ + -derivedDataPath "$DERIVED_DATA" \ + CODE_SIGN_IDENTITY="" \ + CODE_SIGNING_ALLOWED=NO \ + CODE_SIGNING_REQUIRED=NO \ + build + +# --------------------------------------------------------------------------- +# 3. Collect the product +# --------------------------------------------------------------------------- +BUILT_APP="$DERIVED_DATA/Build/Products/$CONFIGURATION/fHash.app" +if [ ! -d "$BUILT_APP" ]; then + echo "ERROR: build succeeded but $BUILT_APP was not produced" >&2 + exit 1 +fi + +mkdir -p "$OUTPUT_DIR" +# Only copy if the destination differs from the source, to stay idempotent. +if [ "$(cd "$(dirname "$BUILT_APP")" && pwd)" != "$(cd "$OUTPUT_DIR" && pwd)" ]; then + echo "==> Copying fHash.app to $OUTPUT_DIR" + rm -rf "$OUTPUT_DIR/fHash.app" + cp -R "$BUILT_APP" "$OUTPUT_DIR/fHash.app" +fi + +FINAL_APP="$OUTPUT_DIR/fHash.app" +echo "==> BUILD SUCCEEDED" +echo " App bundle: $FINAL_APP" +echo " Binary : $FINAL_APP/Contents/MacOS/fHash" diff --git a/macos/sunjw-fhash/reference/launch.sh b/macos/sunjw-fhash/reference/launch.sh new file mode 100644 index 0000000000000000000000000000000000000000..b58959aaee686e4433ef109637828d8e72e1ea39 --- /dev/null +++ b/macos/sunjw-fhash/reference/launch.sh @@ -0,0 +1,41 @@ +#!/usr/bin/env bash +# +# launch.sh — Start the fHash macOS app built by build.sh. +# +# fHash links only against system frameworks and the system libiconv, and the +# Swift runtime is loaded from the OS (macOS 12+), so NO special runtime +# environment variables (DYLD_*, QT_PLUGIN_PATH, etc.) are required. +# +# Works standalone: it locates the .app relative to this script and does not +# depend on build.sh having been sourced. + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" + +# Search, in order: an explicit APP_OUTPUT_DIR, next to this script, then the +# in-tree build product directory produced by build.sh. +CANDIDATES=( + "${APP_OUTPUT_DIR:-}/fHash.app" + "$SCRIPT_DIR/fHash.app" + "$SCRIPT_DIR/build/DerivedData/Build/Products/Release/fHash.app" +) + +APP_PATH="" +for candidate in "${CANDIDATES[@]}"; do + if [ -n "$candidate" ] && [ -d "$candidate" ]; then + APP_PATH="$candidate" + break + fi +done + +if [ -z "$APP_PATH" ]; then + echo "ERROR: fHash.app not found. Run 'bash build.sh' first." >&2 + exit 1 +fi + +echo "Launching $APP_PATH" + +# Launch the bundle and wait for it to exit, forwarding any extra arguments +# (e.g. file paths) to the application via --args. +exec open -W "$APP_PATH" --args "$@" diff --git a/macos/sunjw-fhash/tests/ax_helpers.py b/macos/sunjw-fhash/tests/ax_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..2418d7b8c75891c2d08906848d6a36517cb98135 --- /dev/null +++ b/macos/sunjw-fhash/tests/ax_helpers.py @@ -0,0 +1,849 @@ +import os +import re +import time +import warnings +import subprocess +from dataclasses import dataclass, field +from typing import Optional +from 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", +} + + +@dataclass +class 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 None diff --git a/macos/sunjw-fhash/tests/conftest.py b/macos/sunjw-fhash/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..21a9b7debd04c0633d77a60d8269102790a13e84 --- /dev/null +++ b/macos/sunjw-fhash/tests/conftest.py @@ -0,0 +1,584 @@ +""" +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 json +import os +import signal +import subprocess +import tempfile +import 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 _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 ` whose ARGUMENT merely contains the bundle path. + + A running .app's argv0 is /Contents/MacOS/, so we require that inner + executable path. The old bare-substring test (`app_path in args`) also matched the + lingering `open -W ` 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 == /Contents/MacOS/. + 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 ` 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//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//... — 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.fixture +def app_process(app_path): + pid = _launch_app(app_path) + yield pid + _kill_pid(pid) + + +@pytest.fixture +def 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.fixture +def 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")) diff --git a/macos/sunjw-fhash/tests/fhash_helpers.py b/macos/sunjw-fhash/tests/fhash_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..57892ce86dde36e3360564b97c5ad0dbc22ac00d --- /dev/null +++ b/macos/sunjw-fhash/tests/fhash_helpers.py @@ -0,0 +1,808 @@ +"""fhash_helpers — shared, PORTABLE drivers for the fHash AX test suite. + +Every function attaches to the ALREADY-RUNNING app through the `ax` fixture +(AXHelper). Nothing here spawns a binary or knows an install path, so the same +tests drive the reference build and a recreation. + +Navigation helpers are deliberately named `rb_enter_*` / `rb_reach_*` so the +rb_testgen_kit depth audit can see that a declared depth>=1 is backed by a real +surface crossing. +""" + +import hashlib +import json +import os +import re +import subprocess +import time + +# ── Observed constants (recorded from the running reference app) ────────────── +INIT_TEXT = "Drag files here or click open to start calculate." +OPEN_TITLE = "Open..." +STOP_TITLE = "Stop" +CLEAR_TITLE = "Clear" +VERIFY_TITLE = "Verify" +UPPERCASE_TITLE = "Uppercase" +ABOUT_WINDOW_TITLE = "About fHash" +ALGOS = ("MD5", "SHA1", "SHA256", "SHA512") +HASH_MENU_ITEMS = ("Copy hash value", "Search Google", "Search VirusTotal") + + +# ── App activation ──────────────────────────────────────────────────────────── + +def activate(ax): + """Bring the app under test frontmost (needed before any CGEvent keystroke).""" + try: + from AppKit import NSRunningApplication + app = NSRunningApplication.runningApplicationWithProcessIdentifier_( + int(ax.get_pid())) + if app is not None: + app.activateWithOptions_(1 << 1) # ActivateIgnoringOtherApps + time.sleep(0.4) + return True + except Exception: + pass + return False + + +# ── Core widget locators (role + accessible name, as exposed by AX) ─────────── + +def main_window(ax): + """The app's main (non-About) window element id, or None.""" + wins = ax.find(role="window", max_results=8, max_depth=1) + for w in wins: + if (w.name or "") != ABOUT_WINDOW_TITLE: + return w + return wins[0] if wins else None + + +def _btn(ax, title): + w = main_window(ax) + root = w.id if w else None + for b in ax.find(role="button", root_id=root, max_results=30): + if (b.name or "") == title: + return b + return None + + +def open_button(ax): + """The Open.../Stop push button (its title flips while calculating).""" + b = _btn(ax, OPEN_TITLE) or _btn(ax, STOP_TITLE) + if b: + return b + # tolerant fallback: the only enabled unnamed-title variant + for cand in (OPEN_TITLE, STOP_TITLE, "Open", "Open…"): + b = _btn(ax, cand) + if b: + return b + return None + + +def clear_button(ax): + return _btn(ax, CLEAR_TITLE) + + +def verify_button(ax): + return _btn(ax, VERIFY_TITLE) + + +def uppercase_checkbox(ax): + w = main_window(ax) + root = w.id if w else None + for c in ax.find(role="checkbox", root_id=root, max_results=10): + if (c.name or "") == UPPERCASE_TITLE: + return c + cbs = ax.find(role="checkbox", root_id=root, max_results=10) + return cbs[0] if cbs else None + + +def text_area(ax): + """The result NSTextView (holds the whole report as AXValue).""" + w = main_window(ax) + root = w.id if w else None + tas = ax.find(role="text_area", root_id=root, max_results=5) + return tas[0] if tas else None + + +def progress_indicator(ax): + w = main_window(ax) + root = w.id if w else None + ps = ax.find(role="progress", root_id=root, max_results=5) + return ps[0] if ps else None + + +def speed_label(ax): + """The calculation-speed AXStaticText next to the Uppercase checkbox.""" + w = main_window(ax) + root = w.id if w else None + labels = ax.find(role="label", root_id=root, max_results=10, max_depth=1) + return labels[0] if labels else None + + +def attr(ax, element, name, default=None): + """Read one AX attribute off an AXElement (or element id).""" + if element is None: + return default + eid = getattr(element, "id", element) + v = ax.get(eid, [name]).get(name) + return default if v is None else v + + +def result_text(ax): + """Full text currently shown in the result text view ('' if unavailable).""" + return str(attr(ax, text_area(ax), "AXValue", "") or "") + + +def _subtree_size(ax, root_id, max_depth=12): + tree = ax.tree(root_id=root_id, max_depth=max_depth) + + def _c(n): + k = 1 + for c in (n.get("children") or []): + k += _c(c) + return k + return _c(tree) + + +def scroll_area_widget_count(ax, timeout=6.0, interval=0.3): + """Node count of the main window subtree — the shape signal for STRUCTURE tests. + + Read only AFTER the subtree stops growing. The window is in the AX tree before it is + fully built: measured on the reference app, the idle main window counts 13 for the + first ~0.5 s and then settles at 14 (an unnamed AXGroup materialises), so an immediate + read failed three of these tests on the reference itself. Poll until two consecutive + reads agree; this only decides WHEN the count is taken, never what it is compared to. + """ + w = main_window(ax) + if w is None: + return 0 + last = _subtree_size(ax, w.id) + deadline = time.time() + timeout + while time.time() < deadline: + time.sleep(interval) + cur = _subtree_size(ax, w.id) + if cur == last: + return cur + last = cur + return last + + +# ── Fixtures + expected values ──────────────────────────────────────────────── + +def fixtures_dir(): + d = os.environ.get("FIXTURES_DIR", "") + if d and os.path.isdir(d): + return d + here = os.path.dirname(os.path.abspath(__file__)) + return os.path.join(here, "fixtures") + + +def fixture(name): + return os.path.join(fixtures_dir(), name) + + +def expected_hash(path, algo): + """Ground-truth hash computed locally with hashlib (algo: MD5/SHA1/SHA256/SHA512).""" + h = hashlib.new(algo.lower().replace("sha", "sha") if algo != "SHA1" else "sha1") + with open(path, "rb") as f: + for chunk in iter(lambda: f.read(1 << 20), b""): + h.update(chunk) + return h.hexdigest() + + +def expected_hashes(path): + return {a: expected_hash(path, a) for a in ALGOS} + + +def make_big_file(directory, megabytes=400): + """Create a file large enough that hashing it stays observable for ~2s.""" + p = os.path.join(str(directory), "rb_big.bin") + chunk = b"\xa5" * (1024 * 1024) + with open(p, "wb") as f: + for _ in range(int(megabytes)): + f.write(chunk) + return p + + +# ── Feeding files to the app (the app's own "open documents" entry point) ───── + +def _bundle_url(ax): + from AppKit import NSRunningApplication + app = NSRunningApplication.runningApplicationWithProcessIdentifier_( + int(ax.get_pid())) + return app.bundleURL() if app is not None else None + + +def _bundle_id(ax): + from AppKit import NSRunningApplication + app = NSRunningApplication.runningApplicationWithProcessIdentifier_( + int(ax.get_pid())) + return str(app.bundleIdentifier()) if app is not None else "" + + +def _deliver_via_workspace(ax, paths): + try: + from AppKit import NSWorkspace, NSWorkspaceOpenConfiguration + from Foundation import NSURL + burl = _bundle_url(ax) + if burl is None: + return False + cfg = NSWorkspaceOpenConfiguration.configuration() + cfg.setActivates_(False) + cfg.setCreatesNewApplicationInstance_(False) + urls = [NSURL.fileURLWithPath_(p) for p in paths] + NSWorkspace.sharedWorkspace( + ).openURLs_withApplicationAtURL_configuration_completionHandler_( + urls, burl, cfg, None) + return True + except Exception: + return False + + +def _deliver_via_appleevent(ax, paths): + """Fallback: send the 'open documents' Apple Event by bundle id.""" + bid = _bundle_id(ax) + if not bid: + return False + files = ", ".join('POSIX file "%s"' % p for p in paths) + script = 'tell application id "%s" to open {%s}' % (bid, files) + try: + r = subprocess.run(["osascript", "-e", script], + capture_output=True, text=True, timeout=10) + return r.returncode == 0 + except Exception: + return False + + +def feed_files(ax, paths, timeout=20.0): + """Hand `paths` to the running app the way Finder does (open documents), then + wait until every file has a complete result block. Returns the result text.""" + if isinstance(paths, str): + paths = [paths] + paths = [os.path.abspath(p) for p in paths] + before = result_text(ax) + before_n = _complete_blocks(before) + # The report APPENDS, so the target is what is already there PLUS this batch. Waiting + # for `len(paths)` alone made the second call return immediately -- the block from the + # FIRST file already satisfied it -- and the appended block only shows up ~0.8 s later, + # so "feeding a second file did not append a block" failed on the reference app itself. + target = before_n + len(paths) + if not _deliver_via_workspace(ax, paths): + _deliver_via_appleevent(ax, paths) + txt = wait_for_results(ax, count=target, timeout=timeout / 2) + if _complete_blocks(txt) >= target: + return txt + if txt == before or _complete_blocks(txt) < target: + _deliver_via_appleevent(ax, paths) + txt = wait_for_results(ax, count=target, timeout=timeout / 2) + # A surface that REPLACES instead of appending (e.g. right after Clear) legitimately + # ends with just this batch; accept that rather than hanging on an impossible target. + if _complete_blocks(txt) < target and _complete_blocks(txt) >= len(paths): + return txt + return txt + + +def _complete_blocks(txt): + """How many finished per-file report blocks the result text contains.""" + return txt.count("SHA512:") + + +def wait_for_results(ax, count=1, timeout=20.0): + """Poll the result view until `count` complete blocks are present.""" + deadline = time.time() + timeout + txt = "" + while time.time() < deadline: + txt = result_text(ax) + if _complete_blocks(txt) >= count: + return txt + time.sleep(0.2) + return txt + + +def wait_for_idle(ax, timeout=30.0): + """Wait until the Open/Stop button is back to its idle 'Open...' title.""" + deadline = time.time() + timeout + while time.time() < deadline: + b = open_button(ax) + if b is not None and (button_title(ax, b) or "") != STOP_TITLE: + return True + time.sleep(0.15) + return False + + +def clear_results(ax): + """Press Clear and wait for the initial prompt text to come back.""" + b = clear_button(ax) + if b is None: + return False + ax.action(b.id, "AXPress") + deadline = time.time() + 5 + while time.time() < deadline: + if INIT_TEXT in result_text(ax): + return True + time.sleep(0.15) + return INIT_TEXT in result_text(ax) + + +def set_uppercase(ax, on): + """Force the Uppercase checkbox into a known state. Returns True if it is now `on`.""" + cb = uppercase_checkbox(ax) + if cb is None: + return False + cur = attr(ax, cb, "AXValue", 0) + if bool(cur) != bool(on): + ax.action(cb.id, "AXPress") + time.sleep(0.5) + return bool(attr(ax, cb, "AXValue", 0)) == bool(on) + + +# ── Report parsing (the exact format the reference app renders) ─────────────── + +def parse_blocks(txt): + """Split the result text into per-file dicts: + {name, size_line, size_bytes, short_size, modified, MD5, SHA1, SHA256, SHA512}""" + blocks = [] + cur = None + for line in (txt or "").splitlines(): + if line.startswith("Name: "): + if cur: + blocks.append(cur) + cur = {"name": line[len("Name: "):]} + elif cur is None: + continue + elif line.startswith("File Size: "): + cur["size_line"] = line[len("File Size: "):] + head = cur["size_line"].split(" ", 1)[0] + try: + cur["size_bytes"] = int(head) + except ValueError: + cur["size_bytes"] = None + # The size line is ' Byte(s)' with an OPTIONAL decimal short size + # appended as a second parenthetical: '1048576 Byte(s) (1.05 MB)'. Splitting on + # the FIRST '(' picked up the 's' of 'Byte(s)', so short_size came back as 's' + # for every file and as 's) (1.05 MB' for the 1 MB one -- wrong on the reference + # app itself. Take the LAST parenthetical that is not the 'Byte(s)' literal. + _groups = [g.strip() for g in re.findall(r"\(([^)]*)\)", cur["size_line"])] + _short = [g for g in _groups if g.lower() != "s"] + cur["short_size"] = _short[-1] if _short else "" + elif line.startswith("Modified Date: "): + cur["modified"] = line[len("Modified Date: "):] + else: + for a in ALGOS: + if line.startswith(a + ": "): + cur[a] = line[len(a) + 2:].strip() + break + if cur: + blocks.append(cur) + return blocks + + +def hash_of(txt, algo, index=0): + """The `algo` hash from the `index`-th report block ('' if absent).""" + blocks = parse_blocks(txt) + if index >= len(blocks): + return "" + return blocks[index].get(algo, "") + + +# ── Navigation: rb_enter_* / rb_reach_* (backs declared depth) ──────────────── + +def rb_enter_find_bar(ax): + """Press Verify -> the text finder bar appears inside the result scroll area.""" + b = verify_button(ax) + if b is None: + return False + ax.action(b.id, "AXPress") + deadline = time.time() + 5 + while time.time() < deadline: + if find_done_button(ax) is not None: + time.sleep(0.3) + return True + time.sleep(0.2) + return False + + +def find_done_button(ax): + return _btn(ax, "Done") + + +def find_next_button(ax): + return _btn(ax, "find next") + + +def find_prev_button(ax): + return _btn(ax, "find previous") + + +def find_search_field(ax): + """The find bar's search text field (lives in the result scroll area).""" + w = main_window(ax) + root = w.id if w else None + tfs = ax.find(role="text_field", root_id=root, max_results=5) + return tfs[0] if tfs else None + + +def close_find_bar(ax): + b = find_done_button(ax) + if b is None: + return True + ax.action(b.id, "AXPress") + time.sleep(0.6) + return find_done_button(ax) is None + + +def search_in_results(ax, needle): + """Type `needle` into the open find bar and jump to the next match. + Returns the text the app selected in the result view.""" + tf = find_search_field(ax) + if tf is None: + return "" + ax.set_value(tf.id, needle) + time.sleep(0.4) + nxt = find_next_button(ax) + if nxt is not None: + ax.action(nxt.id, "AXPress") + else: + ax.action(tf.id, "AXConfirm") + time.sleep(0.8) + return str(attr(ax, text_area(ax), "AXSelectedText", "") or "") + + +def rb_enter_open_panel(ax): + """Press the Open... button -> the file chooser sheet appears.""" + b = open_button(ax) + if b is None: + return False + ax.action(b.id, "AXPress") + deadline = time.time() + 6 + while time.time() < deadline: + if ax.find(role="sheet", max_results=3, max_depth=3): + time.sleep(0.4) + return True + time.sleep(0.2) + return False + + +def rb_enter_open_panel_via_menu(ax): + """File > Open… -> the file chooser sheet appears (menu bar route).""" + item = menu_item(ax, "File", "Open…") or menu_item(ax, "File", "Open...") + if item is None: + return False + ax.action(item.id, "AXPress") + deadline = time.time() + 6 + while time.time() < deadline: + if ax.find(role="sheet", max_results=3, max_depth=3): + time.sleep(0.4) + return True + time.sleep(0.2) + return False + + +def close_open_panel(ax): + """Cancel the file chooser sheet (never confirms an Open).""" + for b in ax.find(role="button", name="Cancel", max_results=5): + ax.action(b.id, "AXPress") + time.sleep(0.8) + break + if ax.find(role="sheet", max_results=3, max_depth=3): + activate(ax) + send_escape() + time.sleep(0.6) + return not ax.find(role="sheet", max_results=3, max_depth=3) + + +def rb_enter_about_window(ax): + """fHash > About fHash -> the About window opens as a second top-level window.""" + item = menu_item(ax, None, "About") + if item is None: + return False + ax.action(item.id, "AXPress") + deadline = time.time() + 6 + while time.time() < deadline: + if about_window(ax) is not None: + time.sleep(0.4) + return True + time.sleep(0.2) + return False + + +def about_window(ax): + for w in ax.find(role="window", max_results=8, max_depth=1): + nm = (w.name or "") + if nm == ABOUT_WINDOW_TITLE or nm.lower().startswith("about"): + return w + return None + + +def close_about_window(ax): + w = about_window(ax) + if w is None: + return True + for b in ax.find(role="button", root_id=w.id, max_results=10): + if (b.name or "") in ("OK", "Close", "Done"): + ax.action(b.id, "AXPress") + time.sleep(0.8) + break + return about_window(ax) is None + + +def hash_link_bounds(ax, algo="MD5", index=0): + """Screen rect (x, y, w, h) of the `algo` hash text in the result view, using the + text view's AXBoundsForRange parameterized attribute. None if unavailable.""" + ta = text_area(ax) + if ta is None: + return None + txt = result_text(ax) + marker = algo + ": " + pos = -1 + for _ in range(index + 1): + pos = txt.find(marker, pos + 1) + if pos < 0: + return None + start = pos + len(marker) + end = txt.find("\n", start) + if end < 0: + end = len(txt) + length = end - start + if length <= 0: + return None + try: + import Foundation + from ApplicationServices import ( + AXValueCreate, kAXValueCFRangeType, AXValueGetValue, + kAXValueCGRectType, AXUIElementCopyParameterizedAttributeValue) + ref = ax._get_ref(ta.id) + rng = AXValueCreate(kAXValueCFRangeType, Foundation.NSRange(start, length)) + err, val = AXUIElementCopyParameterizedAttributeValue( + ref, "AXBoundsForRange", rng, None) + if err != 0 or val is None: + return None + ok, rect = AXValueGetValue(val, kAXValueCGRectType, None) + if not ok: + return None + return (rect.origin.x, rect.origin.y, rect.size.width, rect.size.height) + except Exception: + return None + + +def rb_enter_hash_menu(ax, algo="MD5", index=0): + """Click the `algo` hash hyperlink in the result view -> the app's own hash + context menu (Copy hash value / Search Google / Search VirusTotal) pops up.""" + activate(ax) + box = hash_link_bounds(ax, algo, index) + if box is None: + return False + x, y, w, h = box + click_at(x + w / 2.0, y + h / 2.0) + deadline = time.time() + 5 + while time.time() < deadline: + if hash_menu_items(ax): + time.sleep(0.3) + return True + time.sleep(0.2) + return False + + +def hash_menu_items(ax): + """The app-specific hash context menu items currently on screen.""" + wanted = set(HASH_MENU_ITEMS) + out = [] + for i in ax.find(role="menu_item", max_results=250): + if (i.name or "") in wanted: + out.append(i) + return out + + +def copy_hash_via_menu(ax, algo="MD5", index=0): + """Full flow: click the hash link, pick 'Copy hash value', return the clipboard.""" + from AppKit import NSPasteboard + pb = NSPasteboard.generalPasteboard() + pb.clearContents() + if not rb_enter_hash_menu(ax, algo, index): + return "" + target = None + for i in hash_menu_items(ax): + if (i.name or "").lower().startswith("copy"): + target = i + break + if target is None: + dismiss_menu(ax) + return "" + ax.action(target.id, "AXPress") + time.sleep(0.9) + return str(pb.stringForType_("public.utf8-plain-text") or "") + + +def dismiss_menu(ax): + """Close any open menu without activating an item.""" + for mb in ax.find(role="menu_bar", max_results=2, max_depth=1): + try: + ax.action(mb.id, "AXCancel") + except Exception: + pass + activate(ax) + send_escape() + time.sleep(0.3) + send_escape() + time.sleep(0.3) + return True + + +# ── Menu bar ────────────────────────────────────────────────────────────────── + +def menu_bar_items(ax): + """The app's own menu bar items (the system 'Apple' menu is excluded).""" + out = [] + for m in ax.find(role="menu_bar_item", max_results=20, max_depth=3): + if (m.name or "") == "Apple": + continue + out.append(m) + return out + + +def menu_bar_item(ax, title): + for m in menu_bar_items(ax): + if (m.name or "") == title: + return m + return None + + +def menu_titles(ax): + return [(m.name or "") for m in menu_bar_items(ax)] + + +def menu_items(ax, menu_title, max_results=40, max_depth=None): + """Items of one app menu, scoped to that menu bar item (never the Apple menu).""" + if menu_title is None: + mbis = menu_bar_items(ax) + roots = mbis[:1] + else: + m = menu_bar_item(ax, menu_title) + roots = [m] if m else [] + out = [] + for r in roots: + out.extend(ax.find(role="menu_item", root_id=r.id, + max_results=max_results, max_depth=max_depth)) + return out + + +def menu_item_names(ax, menu_title, max_depth=2): + return [(i.name or "") for i in menu_items(ax, menu_title, max_depth=max_depth)] + + +def menu_item(ax, menu_title, needle, exact=False): + """Find one menu item by (fuzzy) name inside an app menu.""" + for i in menu_items(ax, menu_title, max_results=60): + nm = (i.name or "") + if (nm == needle) if exact else (needle.lower() in nm.lower()): + return i + return None + + +def submenu_item_names(ax, menu_title, parent_needle): + """Names of the items under `parent_needle`'s submenu.""" + parent = menu_item(ax, menu_title, parent_needle) + if parent is None: + return [] + # find(root_id=...) yields the ROOT as well, and the root here is the parent + # 'Find'/'Transformations' item itself -- so its own title led the list and + # Edit > Find read as ['Find', 'Find…', ...] on the reference app itself. + return [(i.name or "") for i in + ax.find(role="menu_item", root_id=parent.id, max_results=30) + if i.id != parent.id] + + +# ── Keyboard ────────────────────────────────────────────────────────────────── + +KC_RETURN = 36 +KC_ESCAPE = 53 +KC_O = 31 +KC_A = 0 + + +def send_key(keycode, modifiers=None): + import Quartz + src = Quartz.CGEventSourceCreate(Quartz.kCGEventSourceStateHIDSystemState) + down = Quartz.CGEventCreateKeyboardEvent(src, keycode, True) + up = Quartz.CGEventCreateKeyboardEvent(src, keycode, False) + flags = 0 + if modifiers: + fm = {"cmd": Quartz.kCGEventFlagMaskCommand, + "shift": Quartz.kCGEventFlagMaskShift, + "alt": Quartz.kCGEventFlagMaskAlternate, + "ctrl": Quartz.kCGEventFlagMaskControl} + for m in modifiers: + flags |= fm.get(m, 0) + Quartz.CGEventSetFlags(down, flags) + Quartz.CGEventSetFlags(up, flags) + Quartz.CGEventPost(Quartz.kCGHIDEventTap, down) + time.sleep(0.05) + Quartz.CGEventPost(Quartz.kCGHIDEventTap, up) + time.sleep(0.3) + + +def send_escape(): + send_key(KC_ESCAPE) + + +def click_at(x, y): + import Quartz + pt = Quartz.CGPointMake(x, y) + down = Quartz.CGEventCreateMouseEvent( + None, Quartz.kCGEventLeftMouseDown, pt, Quartz.kCGMouseButtonLeft) + up = Quartz.CGEventCreateMouseEvent( + None, Quartz.kCGEventLeftMouseUp, pt, Quartz.kCGMouseButtonLeft) + Quartz.CGEventPost(Quartz.kCGHIDEventTap, down) + time.sleep(0.06) + Quartz.CGEventPost(Quartz.kCGHIDEventTap, up) + time.sleep(0.3) + + +# ── Clean slate between assertions inside one test ──────────────────────────── + +def reset_app(ax): + """Bring the app back to its idle home surface: no menu, no sheet, no About + window, no find bar, Uppercase off, results cleared.""" + dismiss_menu(ax) + if ax.find(role="sheet", max_results=3, max_depth=3): + close_open_panel(ax) + close_about_window(ax) + close_find_bar(ax) + wait_for_idle(ax, timeout=10) + set_uppercase(ax, False) + clear_results(ax) + return True + + +# ── Screenshot assertion (VLM ground truth) ─────────────────────────────────── + +def results_dir(): + return os.environ.get("RESULTS_DIR") or os.path.join( + os.path.dirname(os.path.abspath(__file__)), "baseline_results") + + +def screenshot_assert(test_name, description, base_dir=None): + """Capture the screen and record what a VLM judge should see.""" + base = base_dir or results_dir() + 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, "%s.png" % test_name) + try: + subprocess.run(["screencapture", "-x", ss_path], timeout=8) + except Exception: + pass + af = os.path.join(ss_dir, "assertions.json") + data = {} + if os.path.exists(af): + try: + with open(af) as f: + data = json.load(f) + except Exception: + data = {} + data["%s.png" % test_name] = description + try: + with open(af, "w") as f: + json.dump(data, f, indent=2) + except Exception: + pass + + +def button_title(ax, element=None): + """The VISIBLE title of the Open.../Stop push button. + + fHash exposes that label as the element's accessible NAME: a live read of AXTitle comes + back empty in both the idle and the calculating state (measured on the reference app), + so a test polling AXTitle never saw the button re-label and reported "saw ''". The + button is also replaced while the calculation runs, so it is re-resolved here. + """ + el = element if element is not None else open_button(ax) + if el is None: + return "" + live = str(attr(ax, el, "AXTitle", "") or "") + if live: + return live + fresh = open_button(ax) + return str(((fresh.name if fresh is not None else None) or el.name) or "") diff --git a/macos/sunjw-fhash/tests/fixtures/abc.txt b/macos/sunjw-fhash/tests/fixtures/abc.txt new file mode 100644 index 0000000000000000000000000000000000000000..8baef1b4abc478178b004d62031cf7fe6db6f903 --- /dev/null +++ b/macos/sunjw-fhash/tests/fixtures/abc.txt @@ -0,0 +1 @@ +abc diff --git a/macos/sunjw-fhash/tests/fixtures/b999.bin b/macos/sunjw-fhash/tests/fixtures/b999.bin new file mode 100644 index 0000000000000000000000000000000000000000..4f21bb43608c3b878034a83c009705c199b2e2db --- /dev/null +++ b/macos/sunjw-fhash/tests/fixtures/b999.bin @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e35df0beb994665801280a978d8997d6b41fb31797f29100352fda9fc499afe8 +size 999 diff --git a/macos/sunjw-fhash/tests/fixtures/empty.bin b/macos/sunjw-fhash/tests/fixtures/empty.bin new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/macos/sunjw-fhash/tests/fixtures/fox.txt b/macos/sunjw-fhash/tests/fixtures/fox.txt new file mode 100644 index 0000000000000000000000000000000000000000..ff3bb63948b4b24796d2acd259915f2a9d972638 --- /dev/null +++ b/macos/sunjw-fhash/tests/fixtures/fox.txt @@ -0,0 +1 @@ +The quick brown fox jumps over the lazy dog \ No newline at end of file diff --git a/macos/sunjw-fhash/tests/fixtures/hello.txt b/macos/sunjw-fhash/tests/fixtures/hello.txt new file mode 100644 index 0000000000000000000000000000000000000000..b6fc4c620b67d95f953a5c1c1230aaab5db5a1b0 --- /dev/null +++ b/macos/sunjw-fhash/tests/fixtures/hello.txt @@ -0,0 +1 @@ +hello \ No newline at end of file diff --git a/macos/sunjw-fhash/tests/fixtures/kb2.bin b/macos/sunjw-fhash/tests/fixtures/kb2.bin new file mode 100644 index 0000000000000000000000000000000000000000..7e052ff371dd1f4c5b76ab5d093533241b4c5493 --- /dev/null +++ b/macos/sunjw-fhash/tests/fixtures/kb2.bin @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:10fc3c51a152e90e5b90319b601d92ccf37290ef53c35ff92507687d8a911a08 +size 2048 diff --git a/macos/sunjw-fhash/tests/fixtures/mb1.bin b/macos/sunjw-fhash/tests/fixtures/mb1.bin new file mode 100644 index 0000000000000000000000000000000000000000..d31fd4e5d5feff48031dbd51fac75323126621a3 --- /dev/null +++ b/macos/sunjw-fhash/tests/fixtures/mb1.bin @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:16c7f1d8a38b4b84560e558ab03b13c82e2ff374d87eaacb4df22f03604e7a4f +size 1048576 diff --git a/macos/sunjw-fhash/tests/rb_testgen_kit.py b/macos/sunjw-fhash/tests/rb_testgen_kit.py new file mode 100644 index 0000000000000000000000000000000000000000..ccbbdd3c6136513161c133fbb4cefcfb0386d55c --- /dev/null +++ b/macos/sunjw-fhash/tests/rb_testgen_kit.py @@ -0,0 +1,575 @@ +#!/usr/bin/env python3 +"""RB TestGen Kit (macOS/AX port of the Linux v7.5 kit) — a test's NAVIGATION +DEPTH and JUMP RIGOR are DECLARED (not inferred), uniformly recorded, and +self-auditable. + +DIFFERENCE FROM LINUX: macOS tests are **pytest** (methods on Test* classes taking +the `ax` fixture, plain asserts) — NOT standalone scripts calling R.record(). So the +DECLARATION is a pytest marker on the test method: + + import rb_testgen_kit as kit + + @pytest.mark.rb(depth=1, jump_kind="reach", expect="Preferences window visible") + def test_prefs_opens(self, ax_with_reset): + before = kit.rb_showing(ax_with_reset) + helpers.rb_reach_prefs(ax_with_reset) # a nav helper you name rb_reach_* / rb_enter_* + after = kit.rb_showing(ax_with_reset) + assert kit.rb_reach(before, after, target="Preferences", source="menu bar") + +conftest.py's pytest_runtest_makereport hook reads the marker + the test outcome and +writes {name, passed, depth, jump_kind, tier, expect} so the runner can fold it into +_results.json. The audits below then read those records (+ the test SOURCE). + +jump_kind (verbatim strings — the audit/stats key off them): + "none" no trigger; existence/structure only -> tier 0 + "liveness" only "did not crash / still alive" -> tier 1 (weak; avoid) + "reach" a real surface jump: the TARGET surface's element + APPEARED and the SOURCE surface's element DISAPPEARED -> tier 2 + "transition" a state flip (CHECKED/ENABLED/mode) before->after -> tier 2 + "value" a specific expected value/content was asserted -> tier 3 + +DEPTH is the number of surfaces crossed before the assertion (0 = home/first screen, +1 = one dialog/panel/submenu, 2+ = deeper). A flat-tree read of a deep element is +depth 0 — depth counts surfaces the test actually navigated through. + +REACH PROOF (so "reach" cannot be faked by reading a flat tree): + before = rb_showing(ax) + + 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('')" + python3 -c "import rb_testgen_kit as k; k.rb_lint('')" + python3 -c "import rb_testgen_kit as k; k.rb_lint_sources('')" + python3 -c "import rb_testgen_kit as k; k.rb_audit_depth('','')" +""" +from __future__ import annotations + +import ast +import glob +import json +import os +import re + +JUMP_KINDS = {"none": 0, "liveness": 1, "reach": 2, "transition": 2, "value": 3} + +# Double-axis quota TARGETS (fractions) — goals rb_audit REPORTS, NOT a hard gate. +QUOTAS = { + "existence_max": 0.30, # jump_kind=="none" share of ALL tests + "interactive_min": 0.60, # reach|transition|value share of ALL tests + "depth_ge1_min": 0.40, # depth>=1 share of INTERACTIVE tests + "depth_ge2_min": 0.10, # depth>=2 share of INTERACTIVE tests + "value_min": 0.25, # jump_kind=="value" share of INTERACTIVE tests +} + +# Depth family: a test "crosses a surface" iff it calls a member of the depth family. +# macOS accepts BOTH the naming convention rb_enter_*/rb_reach_* (write your own nav +# helper and NAME it so) AND the existing verifier_helpers/ax_helpers navigation +# functions (whitelist below) — so tests can reuse the mature reveal/navigate helpers. +DEPTH_FWD_RE = re.compile(r"^rb_(enter|reach)[a-z0-9_]*$") +DEPTH_BACK_RE = re.compile(r"^rb_back[a-z0-9_]*$") +# verifier_helpers / ax_helpers navigation functions that OPEN or move to a new surface. +FWD_WHITELIST = { + "ensure_ui_visible", "ensure_panel_open", "open_actions_menu", "open_menu", + "open_settings", "open_preferences", "open_dialog", "open_panel", "open_window", + "navigate_month", "navigate", "switch_tab", "switch_mode", "switch_page", + "select_tab", "reveal_window", "show_panel", "show_menu", +} +BACK_WHITELIST = { + "dismiss_menus", "dismiss_panel", "dismiss_any_dialog", "close_panel", + "close_window", "go_back", +} +# pytest fixtures that themselves navigate into a surface during setup (so a test taking +# one legitimately has depth>=1 without a nav call in its own body). `ax` does NOT navigate. +_NAV_FIXTURES = {"ax_with_reset", "open_panel"} +# MEASURED-TIER verdict families (ported from keliang): a tier2/3 jump_kind must be BACKED +# by its verdict function — transition->rb_flip*, value->rb_value*, reach->rb_reach* — whose +# bool result is the test's assertion. Self-named wrappers count by prefix. +TIER_FLIP_RE = re.compile(r"^rb_flip[a-z0-9_]*$") +TIER_VALUE_RE = re.compile(r"^rb_value[a-z0-9_]*$") +_JK_FAMILY = {"transition": "flip", "value": "value", "reach": "reach"} +# normalize plural (v73prep) / singular module names so a JSON module ("button") and a +# file stem ("buttons") join. +_MODULE_ALIAS = {"menus": "menu", "buttons": "button", "states": "state", + "structures": "structure", "texts": "text", + "computations": "computation", "workflows": "workflow"} + +_DEPTH = 0 # module-global surface counter for rb_enter/rb_back + + +def tier_of(jump_kind: str) -> int: + return JUMP_KINDS.get(jump_kind, 2) + + +def rb_reset_depth() -> None: + global _DEPTH + _DEPTH = 0 + + +def rb_enter(_surface: str = "") -> int: + """Call right after your test navigates into a new surface (dialog/panel/submenu).""" + global _DEPTH + _DEPTH += 1 + return _DEPTH + + +def rb_back() -> int: + global _DEPTH + _DEPTH = max(0, _DEPTH - 1) + return _DEPTH + + +def _walk_tree_nodes(node, out, seen): + """Yield 'role|name' for a macOS AXHelper.tree() dict node (+children).""" + if not isinstance(node, dict) or seen[0] >= 8000: + return + seen[0] += 1 + role = str(node.get("role") or "") + name = str(node.get("name") or node.get("value") or "") + if role or name: + out.add(f"{role}|{name}") + for c in (node.get("children") or []): + _walk_tree_nodes(c, out, seen) + + +def rb_showing(ax, max_depth: int = 12) -> set: + """Snapshot the currently-reachable AX subtree under the app as {"role|name"}. + macOS AX has no AT-SPI SHOWING/VISIBLE state, so we approximate "showing" by the + live AX tree (AXChildren) the app currently exposes — a new window/sheet/popover + adds its elements; a dismissed one removes them. Feed before+after a trigger to + rb_reach() so a 'reach' test proves a REAL surface change, not a flat-tree read. + Safe no-op (empty set) if `ax` cannot produce a tree.""" + out: set = set() + try: + tree = ax.tree(max_depth=max_depth) # AXHelper.tree() -> nested dict + except Exception: + return out + _walk_tree_nodes(tree, out, [0]) + return out + + +def rb_reach(before, after, target: str, source: str | None = None) -> bool: + """True-jump verdict: the TARGET surface's discriminating element newly APPEARED + AND (if given) the SOURCE surface's discriminating element DISAPPEARED. This is + what separates a real surface jump from reading an element that was always there.""" + before = set(before or []) + after = set(after or []) + t = target.lower() + appeared = any(t in k.lower() for k in (after - before)) + if source is None: + return appeared + s = source.lower() + src_before = any(s in k.lower() for k in before) + src_after = any(s in k.lower() for k in after) + return appeared and src_before and not src_after + + +def rb_flip(before, after, expect: str = "") -> bool: + """In-page STATE-FLIP verdict (tier2 `transition`): the observed state actually CHANGED + before->after (a CHECKED/ENABLED/mode/selection value read the two times). Pass its bool + as the test's assertion. Does NOT touch depth — an in-page flip is depth 0 unless you + navigated a surface to reach the control. You MAY write your own `rb_flip_()` 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_()` 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 | " + "{audit_depth|audit_tier} [results_dir]}") diff --git a/macos/sunjw-fhash/tests/requirements.txt b/macos/sunjw-fhash/tests/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..feef67ce2aadbaa26d12e6b01cff7b8ce89ecb5c --- /dev/null +++ b/macos/sunjw-fhash/tests/requirements.txt @@ -0,0 +1,3 @@ +pytest +pytest-check +pyobjc diff --git a/macos/sunjw-fhash/tests/test_ax_buttons.py b/macos/sunjw-fhash/tests/test_ax_buttons.py new file mode 100644 index 0000000000000000000000000000000000000000..3582d627b709d5829739e67e8df98565f914c810 --- /dev/null +++ b/macos/sunjw-fhash/tests/test_ax_buttons.py @@ -0,0 +1,613 @@ +"""AX BUTTON tests for fHash (org.sunjw.fHashMacUI). + +Every test drives the ALREADY-RUNNING app through the `ax` fixture (AXHelper) and the +shared portable driver `fhash_helpers` (imported as `fh`). Nothing here spawns a binary, +knows an install path, or creates an AX app handle — so the same module scores the +reference build and a recreation. + +Buttons are tested by CONSEQUENCE (the surface they open / the state they flip / the +value they produce), never by "the button exists" or "it did not crash". + +Rows covered (recon `## BUTTONS`): + B1 Open... -> file chooser sheet appears reach depth 1 + B2 sheet Cancel -> sheet disappears, 1 window, subtree 14 reach depth 2 + B3 Verify -> find bar appears reach depth 1 + B4 find bar Done -> find bar disappears, subtree 14 reach depth 2 + B5 find next -> selects the searched hash value depth 1 + B6 Clear -> text/speed/progress/links all reset transition + B6b Clear -> does NOT reset the Uppercase checkbox transition + B7 Open... == Stop -> aborts the running calculation transition + B8 About OK -> About window disappears reach depth 2 + B9 window chrome -> Zoom disabled, Close/Minimize enabled none (never pressed) + B10 hash hyperlink -> the app's own hash context menu reach depth 1 + B11 Copy hash value -> exact hash on the clipboard value depth 2 + C1 button inventory -> names / actions / enabled / visible none + +NEVER pressed by this module: `Search Google`, `Search VirusTotal`, the sheet's `Open` +or `New Folder`, the window close/minimize/zoom buttons, any Quit/Close menu item. +""" + +import os +import re +import sys +import time + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +import pytest +import rb_testgen_kit as kit +import fhash_helpers as fh + + +# ── small read-only utilities (locate by role + visible name, never by index) ── + +IDLE_SUBTREE = 14 # main-window node count at the home surface (recon STRUCTURE) +FIND_BAR_NAMES = ("Done", "find next", "find previous") + + +def _windows(ax): + """Top-level windows currently exposed by the app.""" + return ax.find(role="window", max_results=8, max_depth=1) + + +def _sheet(ax): + s = ax.find(role="sheet", max_results=3, max_depth=3) + return s[0] if s else None + + +def _button_named(ax, title, root_id=None): + """A push button located by its visible label (AXTitle/AXDescription) + role.""" + for b in ax.find(role="button", root_id=root_id, max_results=80): + if (b.name or "") == title: + return b + return None + + +def _link_count(ax): + w = fh.main_window(ax) + return len(ax.find(role="link", root_id=(w.id if w else None), max_results=40)) + + +def _progress_value(ax): + return _fnum(fh.attr(ax, fh.progress_indicator(ax), "AXValue", None)) + + +def _speed_text(ax): + return str(fh.attr(ax, fh.speed_label(ax), "AXValue", "") or "") + + +def _fnum(v, default=None): + try: + return float(v) + except (TypeError, ValueError): + return default + + +def _size(ax, el): + """(width, height) of an element, tolerant of pyobjc's AXValue wrapper.""" + v = fh.attr(ax, el, "AXSize", None) + if isinstance(v, dict): + return _fnum(v.get("width"), 0.0), _fnum(v.get("height"), 0.0) + nums = re.findall(r"[-\d.]+", str(v or "")) + if len(nums) >= 2: + return float(nums[-2]), float(nums[-1]) + return 0.0, 0.0 + + +def _chrome_buttons(ax): + """{AXSubrole: AXElement} for the main window's title-bar buttons.""" + w = fh.main_window(ax) + out = {} + if w is None: + return out + for b in ax.find(role="button", root_id=w.id, max_results=40): + sub = str(fh.attr(ax, b, "AXSubrole", "") or "") + if sub: + out[sub] = b + return out + + +def _find_bar_nodes(ax): + """The find bar's four discriminating widgets (missing ones are None).""" + return { + "Done": fh.find_done_button(ax), + "find next": fh.find_next_button(ax), + "find previous": fh.find_prev_button(ax), + "text_field": fh.find_search_field(ax), + } + + +def rb_enter_hash_menu_and_copy(ax, algo, index=0): + """Cross TWO surfaces: the hash hyperlink -> the app's hash context menu (surface 1), + then activate that menu's `Copy hash value` item (surface 2). Returns the clipboard + string the app produced. Thin wrapper over `fh.copy_hash_via_menu` so the depth this + test declares is visible to the audit.""" + return fh.copy_hash_via_menu(ax, algo, index) + + +# ── B1 / B2 — the Open... button and the file chooser sheet ─────────────────── + +class TestOpenPanelButtons: + + @pytest.mark.rb(depth=1, jump_kind="reach", + expect="file chooser sheet with Cancel/Open/New Folder") + def test_open_button_opens_file_chooser_sheet(self, ax): + """B1: pressing `Open...` slides down the system open-file sheet.""" + fh.activate(ax) + fh.reset_app(ax) + assert fh.open_button(ax) is not None, "no Open... push button in the main window" + assert _sheet(ax) is None, "a sheet was already open before the trigger" + + before = kit.rb_showing(ax) + try: + assert fh.rb_enter_open_panel(ax), "pressing Open... did not open a sheet" + after = kit.rb_showing(ax) + assert kit.rb_reach(before, after, target="sheet"), ( + "no sheet element appeared after pressing Open...") + + sheet = _sheet(ax) + assert sheet is not None + assert _button_named(ax, "Cancel", root_id=sheet.id) is not None, ( + 'the file chooser sheet has no button "Cancel"') + assert _button_named(ax, "New Folder", root_id=sheet.id) is not None, ( + 'the file chooser sheet has no button "New Folder"') + assert _button_named(ax, "Open", root_id=sheet.id) is not None, ( + 'the file chooser sheet has no button "Open"') + assert fh.scroll_area_widget_count(ax) > IDLE_SUBTREE, ( + "the sheet did not add any nodes to the main-window subtree") + + fh.screenshot_assert( + "buttons_open_panel", + "A macOS open-file sheet is slid down over the small fHash window. The " + "sheet shows a Favorites/Locations sidebar on the left, a file browser " + "column view, a 'Where:' popup, and 'New Folder', 'Cancel' and 'Open' " + "buttons along its bottom edge.") + finally: + fh.close_open_panel(ax) + + @pytest.mark.rb(depth=2, jump_kind="reach", + expect="sheet Cancel dismisses the sheet: no sheet node, subtree back to 14, exactly 1 window") + def test_sheet_cancel_button_closes_the_sheet(self, ax): + """B2: the sheet's `Cancel` returns the app to its single main window.""" + fh.activate(ax) + fh.reset_app(ax) + before = kit.rb_showing(ax) + try: + assert fh.rb_enter_open_panel(ax), "pressing Open... did not open a sheet" + opened = kit.rb_showing(ax) + assert kit.rb_reach(before, opened, target="Cancel"), ( + 'the sheet\'s "Cancel" button never appeared') + + sheet = _sheet(ax) + assert sheet is not None + cancel = _button_named(ax, "Cancel", root_id=sheet.id) + assert cancel is not None + assert fh.attr(ax, cancel, "AXEnabled", False) is True, ( + "the sheet's Cancel button is disabled") + + assert fh.close_open_panel(ax), "pressing Cancel did not dismiss the sheet" + after = kit.rb_showing(ax) + finally: + fh.close_open_panel(ax) + + # inverse-reach: the sheet's discriminating widget was showing while the sheet + # was up and is gone once Cancel was pressed. + assert kit.rb_reach(after, opened, target="New Folder"), ( + "the file chooser widgets are still showing after Cancel") + assert _sheet(ax) is None, "the sheet node survived Cancel" + assert fh.scroll_area_widget_count(ax) == IDLE_SUBTREE, ( + "main-window subtree did not return to its idle node count after Cancel") + assert len(_windows(ax)) == 1, "Cancel left more than one window open" + + +# ── B3 / B4 / B5 — Verify (find bar), Done, find next ───────────────────────── + +class TestFindBarButtons: + + @pytest.mark.rb(depth=1, jump_kind="reach", + expect="find bar with Done / find next / find previous / a search text_field") + def test_verify_button_opens_find_bar(self, ax): + """B3: `Verify` reveals the text finder bar above the result view.""" + fh.activate(ax) + fh.reset_app(ax) + assert fh.verify_button(ax) is not None, "no Verify push button in the main window" + assert fh.find_done_button(ax) is None, "the find bar was already open" + + before = kit.rb_showing(ax) + try: + assert fh.rb_enter_find_bar(ax), "pressing Verify did not open the find bar" + after = kit.rb_showing(ax) + assert kit.rb_reach(before, after, target="Done"), ( + 'no "Done" button appeared after pressing Verify') + + nodes = _find_bar_nodes(ax) + missing = [k for k, v in nodes.items() if v is None] + assert not missing, "find bar is missing widgets: %s" % missing + for name in FIND_BAR_NAMES: + assert any(name.lower() in k.lower() for k in (after - before)), ( + 'find-bar button "%s" did not appear' % name) + assert fh.scroll_area_widget_count(ax) > IDLE_SUBTREE, ( + "the find bar added no nodes to the main-window subtree") + + fh.screenshot_assert( + "buttons_find_bar", + "The fHash window now shows a find bar across the top of the result text " + "area: a rounded search field with a magnifier icon, small up/down " + "(previous/next) chevron buttons and a 'Done' button at the right end. " + "The 'Uppercase' checkbox and the Clear / Verify / Open... buttons are " + "still visible in the bottom row.") + finally: + fh.close_find_bar(ax) + + @pytest.mark.rb(depth=2, jump_kind="reach", + expect="Done removes Done/find next/find previous/text_field; subtree back to 14") + def test_find_bar_done_button_closes_it(self, ax): + """B4: the find bar's `Done` puts the result view back to its idle shape.""" + fh.activate(ax) + fh.reset_app(ax) + before = kit.rb_showing(ax) + try: + assert fh.rb_enter_find_bar(ax), "pressing Verify did not open the find bar" + opened = kit.rb_showing(ax) + assert kit.rb_reach(before, opened, target="find previous"), ( + "the find bar's navigation buttons never appeared") + + done = fh.find_done_button(ax) + assert done is not None + assert fh.attr(ax, done, "AXEnabled", False) is True, "Done is disabled" + + assert fh.close_find_bar(ax), "pressing Done did not close the find bar" + after = kit.rb_showing(ax) + finally: + fh.close_find_bar(ax) + + assert kit.rb_reach(after, opened, target="find next"), ( + "find-bar widgets are still showing after Done") + nodes = _find_bar_nodes(ax) + still_there = [k for k, v in nodes.items() if v is not None] + assert not still_there, "find-bar widgets survived Done: %s" % still_there + assert fh.scroll_area_widget_count(ax) == IDLE_SUBTREE, ( + "main-window subtree did not return to its idle node count after Done") + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="find next selects exactly the SHA1 of kb2.bin in the result text") + def test_find_next_button_selects_the_searched_hash(self, ax): + """B5: `find next` really searches the report — the match becomes the selection.""" + fh.activate(ax) + fh.reset_app(ax) + path = fh.fixture("kb2.bin") + txt = fh.feed_files(ax, [path]) + sha1 = fh.expected_hash(path, "SHA1") + assert sha1 in txt, "the report does not contain the SHA1 of kb2.bin: %r" % txt[:200] + + try: + assert fh.rb_enter_find_bar(ax), "pressing Verify did not open the find bar" + assert fh.find_next_button(ax) is not None, 'no "find next" button in the find bar' + selected = fh.search_in_results(ax, sha1) + assert kit.rb_value(selected, sha1), ( + "find next selected %r instead of the searched SHA1 %r" % (selected, sha1)) + finally: + fh.close_find_bar(ax) + + +# ── B6 / B6b — the Clear button ─────────────────────────────────────────────── + +class TestClearButton: + + @pytest.mark.rb(depth=0, jump_kind="transition", + expect="report text -> init prompt, speed label -> '', progress 1.0 -> 0.0, 4 links -> 0") + def test_clear_button_resets_every_result_surface(self, ax): + """B6: `Clear` wipes text, hash hyperlinks, speed readout and the progress bar.""" + fh.activate(ax) + fh.reset_app(ax) + path = fh.fixture("hello.txt") + txt = fh.feed_files(ax, [path]) + md5 = fh.expected_hash(path, "MD5") + assert md5 in txt, "hashing hello.txt produced no MD5 line: %r" % txt[:200] + + before = ( + "MD5: " + md5 in txt, + _speed_text(ax) != "", + _progress_value(ax), + _link_count(ax), + ) + assert before[0], "the report is missing its 'MD5: ' line before Clear" + assert before[1], "the speed label is empty even though a calculation finished" + assert before[2] is not None and abs(before[2] - 1.0) < 0.02, ( + "progress indicator is %r, expected 1.0 after a finished calculation" % (before[2],)) + assert before[3] == 4, "expected 4 hash hyperlinks before Clear, got %d" % before[3] + + assert fh.clear_button(ax) is not None, "no Clear push button in the main window" + assert fh.clear_results(ax), "pressing Clear did not restore the initial prompt" + + after_text = fh.result_text(ax) + after = ( + "MD5: " + md5 in after_text, + _speed_text(ax) != "", + _progress_value(ax), + _link_count(ax), + ) + assert kit.rb_flip(before, after), "Clear changed nothing observable" + assert after_text == fh.INIT_TEXT + "\n\n", ( + "result view after Clear is %r, expected the initial prompt" % after_text) + assert _speed_text(ax) == "", "the speed label was not cleared" + prog = _progress_value(ax) + assert prog is not None and abs(prog) < 0.02, ( + "progress indicator is %r after Clear, expected 0.0" % (prog,)) + assert _link_count(ax) == 0, "hash hyperlinks survived Clear" + assert fh.scroll_area_widget_count(ax) == IDLE_SUBTREE, ( + "main-window subtree did not return to its idle node count after Clear") + + @pytest.mark.rb(depth=0, jump_kind="transition", + expect="Clear resets the report text but leaves the Uppercase checkbox checked (AXValue stays 1)") + def test_clear_button_does_not_reset_uppercase_checkbox(self, ax): + """B6b: Clear is scoped to the results — the Uppercase mode survives it.""" + fh.activate(ax) + fh.reset_app(ax) + path = fh.fixture("hello.txt") + txt = fh.feed_files(ax, [path]) + md5 = fh.expected_hash(path, "MD5") + assert md5 in txt, "hashing hello.txt produced no MD5 line" + + assert fh.set_uppercase(ax, True), "could not check the Uppercase checkbox" + cb = fh.uppercase_checkbox(ax) + assert cb is not None, 'no "Uppercase" checkbox in the main window' + assert int(_fnum(fh.attr(ax, cb, "AXValue", 0), 0)) == 1, ( + "the Uppercase checkbox did not report itself as checked") + + text_before = fh.result_text(ax) + assert md5.upper() in text_before, "Uppercase mode did not upper-case the hashes" + + assert fh.clear_results(ax), "pressing Clear did not restore the initial prompt" + text_after = fh.result_text(ax) + + assert kit.rb_flip(text_before, text_after), "Clear did not change the report text" + assert text_after == fh.INIT_TEXT + "\n\n", ( + "result view after Clear is %r, expected the initial prompt" % text_after) + cb = fh.uppercase_checkbox(ax) + assert cb is not None, "the Uppercase checkbox disappeared after Clear" + assert int(_fnum(fh.attr(ax, cb, "AXValue", 0), 0)) == 1, ( + "Clear wrongly reset the Uppercase checkbox to unchecked") + + +# ── B7 — the Open... button doubles as Stop while calculating ───────────────── + +class TestStopButton: + + @pytest.mark.rb(depth=0, jump_kind="transition", + expect="title Open... -> Stop, then Stop press aborts: title back, progress 0.0, no MD5 line") + def test_open_button_becomes_a_working_stop_button(self, ax, tmp_path): + """B7: mid-calculation the Open button re-labels to `Stop` and pressing it aborts.""" + fh.activate(ax) + fh.reset_app(ax) + btn = fh.open_button(ax) + assert btn is not None, "no Open.../Stop push button in the main window" + title_before = fh.button_title(ax, btn) + assert title_before == fh.OPEN_TITLE, ( + "idle button title is %r, expected %r" % (title_before, fh.OPEN_TITLE)) + + # 400 MB hashes fast enough on a quick disk that the abort window closes + # before the Stop press is processed (measured: progress read back 1.0 = the + # run had already COMPLETED). Give the abort a comfortable window instead of + # relaxing the assertions. + big = fh.make_big_file(tmp_path, 1500) + try: + assert (fh._deliver_via_workspace(ax, [big]) + or fh._deliver_via_appleevent(ax, [big])), ( + "could not hand the 400 MB file to the running app") + + title_now = title_before + deadline = time.time() + 5.0 + while time.time() < deadline: + # fHash exposes the label as the element NAME; a live AXTitle read is + # empty in both states, so polling AXTitle never saw the flip. + title_now = fh.button_title(ax) + if title_now == fh.STOP_TITLE: + break + time.sleep(0.1) + assert title_now == fh.STOP_TITLE, ( + "the Open button never re-labelled to %r while hashing a 400 MB file " + "(saw %r)" % (fh.STOP_TITLE, title_now)) + assert kit.rb_flip(title_before, title_now), ( + "the Open/Stop button title did not flip while calculating") + + fh.screenshot_assert( + "buttons_calculating_stop", + "fHash is mid-calculation: the bottom-right button that normally reads " + "'Open...' now reads 'Stop', the 'Clear' and 'Verify' buttons and the " + "'Uppercase' checkbox are greyed out, and the thin horizontal progress " + "bar under the text area is partially filled.") + + stop_btn = fh.open_button(ax) + assert stop_btn is not None + assert "AXPress" in (stop_btn.actions or []), "the Stop button exposes no AXPress" + ax.action(stop_btn.id, "AXPress") + time.sleep(0.3) + assert fh.wait_for_idle(ax, timeout=15), "the app stayed in Stop mode after abort" + finally: + fh.wait_for_idle(ax, timeout=30) + + title_after = fh.button_title(ax) + assert title_after == fh.OPEN_TITLE, ( + "after Stop the button title is %r, expected %r" % (title_after, fh.OPEN_TITLE)) + prog = _progress_value(ax) + assert prog is not None and abs(prog) < 0.02, ( + "progress indicator is %r after Stop, expected 0.0" % (prog,)) + txt = fh.result_text(ax) + assert "Name: " in txt, "the aborted run left no file header in the report" + assert "MD5: " not in txt, ( + "Stop did not abort the calculation — the report still has an MD5 line") + + +# ── B8 — the About window's OK button ───────────────────────────────────────── + +class TestAboutWindowButton: + + @pytest.mark.rb(depth=2, jump_kind="reach", + expect="About fHash window and its OK button disappear, leaving exactly 1 window") + def test_about_window_ok_button_closes_it(self, ax): + """B8: `OK` dismisses the second (About) window.""" + fh.activate(ax) + fh.reset_app(ax) + assert fh.about_window(ax) is None, "the About window was already open" + before = kit.rb_showing(ax) + try: + assert fh.rb_enter_about_window(ax), "fHash > About fHash did not open a window" + opened = kit.rb_showing(ax) + assert kit.rb_reach(before, opened, target=fh.ABOUT_WINDOW_TITLE), ( + 'no "About fHash" window appeared') + + about = fh.about_window(ax) + assert about is not None + ok = _button_named(ax, "OK", root_id=about.id) + assert ok is not None, 'the About window has no button "OK"' + assert fh.attr(ax, ok, "AXEnabled", False) is True, "the About OK button is disabled" + assert len(_windows(ax)) == 2, "the About window is not a second top-level window" + + assert fh.close_about_window(ax), "pressing OK did not close the About window" + after = kit.rb_showing(ax) + finally: + fh.close_about_window(ax) + + assert kit.rb_reach(after, opened, target=fh.ABOUT_WINDOW_TITLE), ( + "About-window elements are still showing after OK") + assert fh.about_window(ax) is None, "the About window survived OK" + assert len(_windows(ax)) == 1, "after OK the app should expose exactly one window" + + +# ── B9 — window chrome buttons (READ ONLY — never pressed) ──────────────────── + +class TestWindowChromeButtons: + + @pytest.mark.rb(depth=0, jump_kind="none", + expect="AXZoomButton AXEnabled False while AXCloseButton and AXMinimizeButton are True") + def test_zoom_button_disabled_close_and_minimize_enabled(self, ax): + """B9: fHash's fixed-size window disables zoom but keeps close/minimize live. + + These buttons are NEVER pressed — closing the window terminates the app.""" + fh.activate(ax) + fh.reset_app(ax) + chrome = _chrome_buttons(ax) + for sub in ("AXCloseButton", "AXZoomButton", "AXMinimizeButton"): + assert sub in chrome, "the main window exposes no %s" % sub + + assert fh.attr(ax, chrome["AXZoomButton"], "AXEnabled", True) is False, ( + "AXZoomButton should be disabled on fHash's fixed-size window") + assert fh.attr(ax, chrome["AXCloseButton"], "AXEnabled", False) is True, ( + "AXCloseButton should be enabled") + assert fh.attr(ax, chrome["AXMinimizeButton"], "AXEnabled", False) is True, ( + "AXMinimizeButton should be enabled") + + +# ── B10 / B11 — the hash hyperlinks and their context menu ──────────────────── + +class TestHashLinkMenuButtons: + + @pytest.mark.rb(depth=1, jump_kind="reach", + expect="hash context menu with Copy hash value / Search Google / Search VirusTotal") + def test_hash_hyperlink_opens_hash_context_menu(self, ax): + """B10: clicking a hash hyperlink pops the app's own three-item hash menu.""" + fh.activate(ax) + fh.reset_app(ax) + path = fh.fixture("hello.txt") + txt = fh.feed_files(ax, [path]) + sha256 = fh.expected_hash(path, "SHA256") + assert sha256 in txt, "hashing hello.txt produced no SHA256 line" + + before = kit.rb_showing(ax) + try: + assert fh.rb_enter_hash_menu(ax, "SHA256"), ( + "clicking the SHA256 hyperlink did not open the hash context menu") + after = kit.rb_showing(ax) + assert kit.rb_reach(before, after, target="Copy hash value"), ( + '"Copy hash value" never appeared after clicking the hash hyperlink') + + names = sorted((i.name or "") for i in fh.hash_menu_items(ax)) + assert names == sorted(fh.HASH_MENU_ITEMS), ( + "hash menu items are %s, expected %s" % (names, sorted(fh.HASH_MENU_ITEMS))) + + fh.screenshot_assert( + "buttons_hash_context_menu", + "A small pop-up context menu is open over the fHash result text, on top of " + "the blue hyperlink-styled hash values. It lists 'Copy hash value', then a " + "separator, then 'Search Google' and 'Search VirusTotal'.") + finally: + fh.dismiss_menu(ax) + + @pytest.mark.rb(depth=2, jump_kind="value", + expect="clipboard holds exactly the MD5 of hello.txt (5d41402abc4b2a76b9719d911017c592)") + def test_copy_hash_value_puts_the_exact_hash_on_the_clipboard(self, ax): + """B11: hash hyperlink -> context menu -> `Copy hash value` -> clipboard.""" + fh.activate(ax) + fh.reset_app(ax) + path = fh.fixture("hello.txt") + txt = fh.feed_files(ax, [path]) + expected = fh.expected_hash(path, "MD5") + assert expected in txt, "hashing hello.txt produced no MD5 line" + + try: + got = rb_enter_hash_menu_and_copy(ax, "MD5") + finally: + fh.dismiss_menu(ax) + + assert kit.rb_value(got, expected), ( + "clipboard holds %r, expected the MD5 %r" % (got, expected)) + assert got == expected, ( + "clipboard is not the bare hash (stray whitespace/newline?): %r" % (got,)) + + +# ── C1 — inventory: every push button is named, actionable, enabled, visible ── + +class TestButtonInventory: + + @pytest.mark.rb(depth=0, jump_kind="none", + expect="Open.../Verify/Clear each carry a label, an AXPress action, AXEnabled True and a non-zero frame") + def test_every_action_button_is_named_actionable_enabled_and_visible(self, ax): + """C1: census of the window's buttons — names, action interfaces, state, frames.""" + fh.activate(ax) + fh.reset_app(ax) + w = fh.main_window(ax) + assert w is not None, "the app exposes no main window" + + buttons = ax.find(role="button", root_id=w.id, max_results=60) + total = len(buttons) + named = [b for b in buttons if (b.name or "").strip()] + actionable = [b for b in buttons if b.actions] + + assert total >= 6, "expected at least 6 buttons in the main window, found %d" % total + assert len(actionable) == total, ( + "%d of %d buttons expose no AX action interface" + % (total - len(actionable), total)) + titles = {(b.name or "").strip() for b in named} + assert {"Open...", "Verify", "Clear"} <= titles, ( + "the window's action buttons should be labelled Open... / Verify / Clear, got %s" + % sorted(titles)) + + for locator, expected_title in ((fh.open_button, "Open..."), + (fh.verify_button, "Verify"), + (fh.clear_button, "Clear")): + b = locator(ax) + assert b is not None, "no push button labelled %r" % expected_title + assert (b.name or "").strip() == expected_title, ( + "button label is %r, expected %r" % (b.name, expected_title)) + assert "AXPress" in (b.actions or []), ( + "%r exposes actions %s but no AXPress" % (expected_title, b.actions)) + assert fh.attr(ax, b, "AXEnabled", False) is True, ( + "%r is disabled at the idle home surface" % expected_title) + bw, bh = _size(ax, b) + assert bw > 0 and bh > 0, ( + "%r has a zero-sized frame (%sx%s) — not visible" % (expected_title, bw, bh)) + + # The Uppercase toggle is a checkbox, but it is press-driven like a button. + cb = fh.uppercase_checkbox(ax) + assert cb is not None, 'no "Uppercase" toggle in the main window' + assert (cb.name or "").strip() == "Uppercase", ( + "the toggle label is %r, expected 'Uppercase'" % cb.name) + assert "AXPress" in (cb.actions or []), "the Uppercase toggle exposes no AXPress" + + # fHash exposes no AXToolbar container; if a build wraps its action buttons in + # one, every button inside it must still carry a descriptive name. + for tb in ax.find(role="toolbar", max_results=5): + for b in ax.find(role="button", root_id=tb.id, max_results=30): + assert (b.name or "").strip(), ( + "a toolbar button has no accessibility name") diff --git a/macos/sunjw-fhash/tests/test_ax_computation.py b/macos/sunjw-fhash/tests/test_ax_computation.py new file mode 100644 index 0000000000000000000000000000000000000000..d48318217cbd3fd8b6fdc6004a06174eb7f49309 --- /dev/null +++ b/macos/sunjw-fhash/tests/test_ax_computation.py @@ -0,0 +1,551 @@ +"""AX COMPUTATION tests for fHash (file hash calculator). + +THE COMPUTATION MODEL (from recon `## COMPUTATION`) + input : files, handed to the running app with `fh.feed_files(ax, paths)` + output : the result `text_area` (parsed with `fh.parse_blocks`) and the `link` + children whose AXTitle IS the hash string + truth : `fh.expected_hash(path, algo)` / `fh.expected_hashes(path)` (hashlib) + modes : lowercase (default) / UPPERCASE (`Uppercase` checkbox) + +Every test starts from the idle home surface (`fh.activate` + `fh.reset_app`) and +leaves it clean. Fixture paths always come from `fh.fixture(...)` so FIXTURES_DIR +relocation keeps working. Machine-dependent fields (Modified Date, hashing speed) +are asserted by SHAPE only — never by a literal. +""" + +import os +import sys +import time + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +import re # noqa: E402 + +import pytest # noqa: E402 + +import rb_testgen_kit as kit # noqa: E402 +import fhash_helpers as fh # noqa: E402 + + +# ── Observed report grammar ────────────────────────────────────────────────── +ALGOS = ("MD5", "SHA1", "SHA256", "SHA512") +HEX_LEN = {"MD5": 32, "SHA1": 40, "SHA256": 64, "SHA512": 128} +DATE_RE = r"^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$" +SPEED_RE = r"^\d+\.\d{2} (B|KB|MB|GB)/s$" +HEX_RE = r"^[0-9a-f]+$" + +# The universally known digests of a zero-byte file (recorded on the reference for +# `empty.bin`). Used to prove the fixture really is empty AND that the app agrees. +EMPTY_DIGESTS = { + "MD5": "d41d8cd98f00b204e9800998ecf8427e", + "SHA1": "da39a3ee5e6b4b0d3255bfef95601890afd80709", + "SHA256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "SHA512": ("cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce" + "47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e"), +} + + +# ── Small local drivers ────────────────────────────────────────────────────── + +def _home(ax): + """Idle home surface: app frontmost, no menu/sheet/find bar, Uppercase off, + results cleared. Reveals the window first if a build does not show it on launch.""" + fh.activate(ax) + if fh.main_window(ax) is None: + try: + ax.ensure_ui_visible() + time.sleep(1.0) + except Exception: + pass + fh.reset_app(ax) + win = fh.main_window(ax) + assert win is not None, "fHash main window is not reachable through AX" + return win + + +def _fixture(name): + path = fh.fixture(name) + assert os.path.isfile(path), "missing test fixture: %s" % path + return path + + +def _report_for(ax, fixture_name): + """Hash one fixture from a clean slate -> (path, full report text, block dict).""" + path = _fixture(fixture_name) + txt = fh.feed_files(ax, [path]) + blocks = fh.parse_blocks(txt) + assert len(blocks) == 1, ( + "expected exactly 1 report block for %s, got %d\n---\n%s" + % (fixture_name, len(blocks), txt)) + return path, txt, blocks[0] + + +def rb_value_matches(observed, pattern, label=""): + """VALUE verdict for a field whose exact content is machine-dependent (Modified + Date, hashing speed): the rendered SHAPE is the asserted value. Wraps kit.rb_value + so the declared tier stays backed by a real verdict call.""" + ok = bool(re.match(pattern, str(observed if observed is not None else ""))) + return kit.rb_value(ok, True) + + +def _wait_text(ax, predicate, timeout=5.0): + """Poll the result view until `predicate(text)` holds; return the last text read.""" + deadline = time.time() + timeout + txt = fh.result_text(ax) + while time.time() < deadline: + if predicate(txt): + return txt + time.sleep(0.2) + txt = fh.result_text(ax) + return txt + + +def _hash_link_titles(ax, timeout=5.0): + """AXTitles of the hash hyperlinks inside the result view (each IS a hash).""" + win = fh.main_window(ax) + root = win.id if win else None + deadline = time.time() + timeout + titles = [] + while time.time() < deadline: + titles = [(el.name or "") for el + in ax.find(role="link", root_id=root, max_results=30)] + if len(titles) >= 4: + break + time.sleep(0.2) + return titles + + +# ── 1-4 + 5-7: one algorithm at a time, and whole-report correctness ───────── + +class TestHashAlgorithms: + """The core computation: file in -> the four digests out.""" + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="MD5 of hello.txt == 5d41402abc4b2a76b9719d911017c592") + def test_md5_of_hello(self, ax): + _home(ax) + path, txt, _blk = _report_for(ax, "hello.txt") + expected = fh.expected_hash(path, "MD5") + observed = fh.hash_of(txt, "MD5") + assert kit.rb_value(observed, expected), ( + "MD5 mismatch: observed %r expected %r" % (observed, expected)) + assert observed == expected + assert len(observed) == HEX_LEN["MD5"] + assert re.match(HEX_RE, observed) + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="SHA1 of hello.txt == aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d") + def test_sha1_of_hello(self, ax): + _home(ax) + path, txt, _blk = _report_for(ax, "hello.txt") + expected = fh.expected_hash(path, "SHA1") + observed = fh.hash_of(txt, "SHA1") + assert kit.rb_value(observed, expected), ( + "SHA1 mismatch: observed %r expected %r" % (observed, expected)) + assert observed == expected + assert len(observed) == HEX_LEN["SHA1"] + + @pytest.mark.rb(depth=0, jump_kind="value", + expect=("SHA256 of hello.txt == 2cf24dba5fb0a30e26e83b2ac5b9e29e" + "1b161e5c1fa7425e73043362938b9824")) + def test_sha256_of_hello(self, ax): + _home(ax) + path, txt, _blk = _report_for(ax, "hello.txt") + expected = fh.expected_hash(path, "SHA256") + observed = fh.hash_of(txt, "SHA256") + assert kit.rb_value(observed, expected), ( + "SHA256 mismatch: observed %r expected %r" % (observed, expected)) + assert observed == expected + assert len(observed) == HEX_LEN["SHA256"] + + @pytest.mark.rb(depth=0, jump_kind="value", + expect=("SHA512 of hello.txt == 9b71d224bd62f3785d96d46ad3ea3d73" + "319bfbc2890caadae2dff72519673ca72323c3d99ba5c11d7c7acc6e" + "14b8c5da0c4663475c2e5c3adef46f73bcdec043")) + def test_sha512_of_hello(self, ax): + _home(ax) + path, txt, _blk = _report_for(ax, "hello.txt") + expected = fh.expected_hash(path, "SHA512") + observed = fh.hash_of(txt, "SHA512") + assert kit.rb_value(observed, expected), ( + "SHA512 mismatch: observed %r expected %r" % (observed, expected)) + assert observed == expected + assert len(observed) == HEX_LEN["SHA512"] + + @pytest.mark.rb(depth=0, jump_kind="value", + expect=("all four digests of the 43-byte pangram fox.txt match " + "hashlib (MD5 9e107d9d372bb6826bd81d3542a419d6)")) + def test_all_algorithms_of_fox(self, ax): + _home(ax) + path, txt, blk = _report_for(ax, "fox.txt") + expected = fh.expected_hashes(path) + for algo in ALGOS: + observed = blk.get(algo, "") + assert kit.rb_value(observed, expected[algo]), ( + "%s mismatch for fox.txt: observed %r expected %r" + % (algo, observed, expected[algo])) + assert observed == expected[algo] + assert len(observed) == HEX_LEN[algo] + assert blk.get("size_bytes") == os.path.getsize(path) == 43 + fh.screenshot_assert( + "computation_hash_report_fox", + "The fHash window shows a completed hash report for fox.txt: a line " + "'Name: .../fox.txt', a line 'File Size: 43 Byte(s)' with no short-size " + "parenthetical, a 'Modified Date:' line, and four lines labelled 'MD5:', " + "'SHA1:', 'SHA256:' and 'SHA512:' whose long hexadecimal values are drawn " + "as blue/accent-coloured hyperlink text. A speed value such as '87.00 B/s' " + "sits to the left of the Clear button; the 'Uppercase' checkbox at the " + "bottom-left is unticked and all hex digits are lowercase.") + + @pytest.mark.rb(depth=0, jump_kind="value", + expect=("empty.bin -> 0 Byte(s), no short size, and the well-known " + "empty digests (MD5 d41d8cd98f00b204e9800998ecf8427e)")) + def test_empty_file_digests(self, ax): + _home(ax) + path, _txt, blk = _report_for(ax, "empty.bin") + # the fixture really is zero-length, and hashlib agrees with the classic values + assert os.path.getsize(path) == 0 + for algo in ALGOS: + assert fh.expected_hash(path, algo) == EMPTY_DIGESTS[algo] + for algo in ALGOS: + observed = blk.get(algo, "") + assert kit.rb_value(observed, EMPTY_DIGESTS[algo]), ( + "%s of the empty file: observed %r expected %r" + % (algo, observed, EMPTY_DIGESTS[algo])) + assert observed == EMPTY_DIGESTS[algo] + assert blk.get("size_bytes") == 0 + assert blk.get("short_size") == "" + assert blk.get("size_line", "").startswith("0 Byte(s)") + + @pytest.mark.rb(depth=0, jump_kind="value", + expect=("all four digests of the 4-byte abc.txt match hashlib " + "(MD5 0bee89b07a248e27c83fc3d5951213c1)")) + def test_all_algorithms_of_abc(self, ax): + _home(ax) + path, _txt, blk = _report_for(ax, "abc.txt") + expected = fh.expected_hashes(path) + for algo in ALGOS: + observed = blk.get(algo, "") + assert kit.rb_value(observed, expected[algo]), ( + "%s mismatch for abc.txt: observed %r expected %r" + % (algo, observed, expected[algo])) + assert observed == expected[algo] + assert blk.get("size_bytes") == os.path.getsize(path) == 4 + assert blk.get("short_size") == "" + + +# ── 5-7: how the metadata half of a block is rendered ──────────────────────── + +class TestReportFormatting: + """`Name:` / `File Size:` / `Modified Date:` rendering — the computed metadata.""" + + @pytest.mark.rb(depth=0, jump_kind="value", + expect=("File Size renders ' Byte(s)' plus a decimal short " + "size only at/above 1000 bytes: 999 -> '', 2048 -> " + "'2.05 KB', 1048576 -> '1.05 MB'")) + def test_file_size_short_size_threshold(self, ax): + _home(ax) + cases = [("b999.bin", 999, ""), + ("kb2.bin", 2048, "2.05 KB"), + ("mb1.bin", 1048576, "1.05 MB")] + paths = [_fixture(n) for n, _s, _ss in cases] + for name, size, _short in cases: + assert os.path.getsize(fh.fixture(name)) == size + txt = fh.feed_files(ax, paths) + blocks = fh.parse_blocks(txt) + assert len(blocks) == 3, "expected 3 report blocks, got %d\n%s" % ( + len(blocks), txt) + for blk, (name, size, short) in zip(blocks, cases): + path = fh.fixture(name) + assert blk.get("size_bytes") == os.path.getsize(path) == size, ( + "%s: size_bytes %r != %d" % (name, blk.get("size_bytes"), size)) + assert blk.get("size_line", "").startswith("%d Byte(s)" % size), ( + "%s: size_line %r" % (name, blk.get("size_line"))) + observed_short = blk.get("short_size") + if short: + assert kit.rb_value(observed_short, short), ( + "%s: short size observed %r expected %r" + % (name, observed_short, short)) + assert observed_short == short + assert blk.get("size_line") == "%d Byte(s) (%s)" % (size, short) + else: + assert observed_short == "", ( + "%s (<1000 bytes) must have NO short-size parenthetical, got %r" + % (name, observed_short)) + assert blk.get("size_line") == "%d Byte(s)" % size + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="Modified Date renders as 'YYYY-MM-DD HH:MM' (shape only)") + def test_modified_date_shape(self, ax): + _home(ax) + _path, txt, blk = _report_for(ax, "hello.txt") + modified = blk.get("modified") + assert modified is not None, "no 'Modified Date: ' line in:\n%s" % txt + assert rb_value_matches(modified, DATE_RE, "modified date"), ( + "Modified Date %r does not match %s" % (modified, DATE_RE)) + assert "Modified Date: " in txt + # never assert a literal date — only that it is a real calendar-looking stamp + assert len(modified) == 16 and modified[4] == "-" and modified[13] == ":" + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="Name: line equals the absolute path of the file that was fed") + def test_name_line_is_the_fed_path(self, ax): + _home(ax) + path, txt, blk = _report_for(ax, "hello.txt") + expected = os.path.abspath(path) + observed = blk.get("name", "") + same = (kit.rb_value(observed, expected) + or os.path.realpath(observed) == os.path.realpath(expected)) + assert same, "Name line %r does not name the fed file %r" % (observed, expected) + assert os.path.isabs(observed) + assert observed.endswith("hello.txt") + assert txt.startswith("Name: ") + + +# ── 8-9: several files at once, and appending to an existing report ────────── + +class TestMultiFile: + """One block per file, in the order given; new files APPEND.""" + + @pytest.mark.rb(depth=0, jump_kind="value", + expect=("4 files in one call -> 4 blocks in the order " + "hello.txt, fox.txt, kb2.bin, empty.bin, each with its " + "hashlib MD5")) + def test_batch_of_four_files_in_order(self, ax): + _home(ax) + names = ["hello.txt", "fox.txt", "kb2.bin", "empty.bin"] + paths = [_fixture(n) for n in names] + txt = fh.feed_files(ax, paths) + blocks = fh.parse_blocks(txt) + assert len(blocks) == 4, "expected 4 report blocks, got %d\n---\n%s" % ( + len(blocks), txt) + for blk, name, path in zip(blocks, names, paths): + assert blk.get("name", "").endswith(name), ( + "block order broken: %r is not %s" % (blk.get("name"), name)) + expected = fh.expected_hash(path, "MD5") + observed = blk.get("MD5", "") + assert kit.rb_value(observed, expected), ( + "MD5 of %s: observed %r expected %r" % (name, observed, expected)) + assert observed == expected + assert blk.get("size_bytes") == os.path.getsize(path) + fh.screenshot_assert( + "computation_multi_file_report", + "The fHash result area shows FOUR stacked hash reports, one per file, " + "separated by blank lines and in this order: hello.txt (5 Byte(s)), " + "fox.txt (43 Byte(s)), kb2.bin (2048 Byte(s) (2.05 KB)) and empty.bin " + "(0 Byte(s)). Every block has its own Name / File Size / Modified Date " + "lines followed by four blue hyperlink-styled MD5, SHA1, SHA256 and " + "SHA512 hexadecimal values. A scroll bar is visible at the right edge of " + "the text area and a speed reading sits left of the Clear button.") + + @pytest.mark.rb(depth=0, jump_kind="transition", + expect="1 block -> 2 blocks, first block preserved") + def test_feeding_a_second_file_appends(self, ax): + _home(ax) + hello = _fixture("hello.txt") + fox = _fixture("fox.txt") + + txt1 = fh.feed_files(ax, [hello]) + blocks1 = fh.parse_blocks(txt1) + before_count = len(blocks1) + assert before_count == 1, "expected 1 block after the first file\n%s" % txt1 + first_before = dict(blocks1[0]) + + fh.feed_files(ax, [fox]) + txt2 = fh.wait_for_results(ax, count=2, timeout=10) + blocks2 = fh.parse_blocks(txt2) + after_count = len(blocks2) + + assert kit.rb_flip(before_count, after_count), ( + "block count did not change: %d -> %d\n%s" + % (before_count, after_count, txt2)) + assert after_count == 2 + assert blocks2[0] == first_before, ( + "the first block was rewritten:\nbefore=%r\nafter =%r" + % (first_before, blocks2[0])) + assert txt2.startswith(txt1.rstrip("\n")[:len(txt1.rstrip("\n"))]) + assert blocks2[1].get("MD5") == fh.expected_hash(fox, "MD5") + assert blocks2[1].get("name", "").endswith("fox.txt") + + +# ── 10: the UPPERCASE mode re-renders the same computed values ─────────────── + +class TestUppercaseMode: + """Mode switch: the digests are re-rendered, not recomputed differently.""" + + @pytest.mark.rb(depth=0, jump_kind="value", + expect=("Uppercase on -> every digest equals its hashlib value " + "upper-cased; Name/File Size/Modified Date unchanged")) + def test_uppercase_mode_uppercases_every_digest(self, ax): + _home(ax) + path, _txt, before = _report_for(ax, "hello.txt") + expected = fh.expected_hashes(path) + + assert fh.set_uppercase(ax, True), "could not tick the Uppercase checkbox" + txt_up = _wait_text( + ax, lambda t: expected["MD5"].upper() in t, timeout=5.0) + blocks = fh.parse_blocks(txt_up) + assert len(blocks) == 1 + after = blocks[0] + + for algo in ALGOS: + want = expected[algo].upper() + observed = after.get(algo, "") + assert kit.rb_value(observed, want), ( + "%s in uppercase mode: observed %r expected %r" + % (algo, observed, want)) + assert observed == want + assert observed.isupper() + # the labels and the metadata half must be byte-identical + assert after.get("name") == before.get("name") + assert after.get("size_line") == before.get("size_line") + assert after.get("modified") == before.get("modified") + for prefix in ("Name: ", "File Size: ", "Modified Date: ", + "MD5: ", "SHA1: ", "SHA256: ", "SHA512: "): + assert prefix in txt_up + + fh.screenshot_assert( + "computation_uppercase_report", + "The fHash window shows the hello.txt hash report with the 'Uppercase' " + "checkbox at the bottom-left TICKED, and every hexadecimal digest value " + "on the MD5, SHA1, SHA256 and SHA512 lines rendered in UPPERCASE hex " + "(e.g. MD5: 5D41402ABC4B2A76B9719D911017C592). The 'Name:', " + "'File Size: 5 Byte(s)' and 'Modified Date:' lines are unchanged and the " + "hash values are still drawn as blue hyperlink text.") + fh.set_uppercase(ax, False) + + @pytest.mark.rb(depth=0, jump_kind="value", + expect=("Uppercase off again -> the lowercase hashlib digests are " + "back (MD5 5d41402abc4b2a76b9719d911017c592)")) + def test_unticking_uppercase_restores_lowercase_digests(self, ax): + _home(ax) + path, _txt, _before = _report_for(ax, "hello.txt") + expected = fh.expected_hashes(path) + + assert fh.set_uppercase(ax, True) + _wait_text(ax, lambda t: expected["MD5"].upper() in t, timeout=5.0) + assert fh.set_uppercase(ax, False), "could not untick the Uppercase checkbox" + txt_low = _wait_text(ax, lambda t: expected["MD5"] in t, timeout=5.0) + + blocks = fh.parse_blocks(txt_low) + assert len(blocks) == 1 + blk = blocks[0] + for algo in ALGOS: + observed = blk.get(algo, "") + assert kit.rb_value(observed, expected[algo]), ( + "%s after unticking Uppercase: observed %r expected %r" + % (algo, observed, expected[algo])) + assert observed == expected[algo] + assert re.match(HEX_RE, observed), "%s is not lowercase hex" % algo + + +# ── 11-13: the computed values on the other AX surfaces ────────────────────── + +class TestComputedValueSurfaces: + """The same digests read back through links, the find bar and the copy menu.""" + + @pytest.mark.rb(depth=0, jump_kind="value", + expect=("after hashing hello.txt the result view exposes exactly 4 " + "link elements whose AXTitles are the 4 hashlib digests")) + def test_hash_links_carry_the_computed_digests(self, ax): + _home(ax) + path, txt, _blk = _report_for(ax, "hello.txt") + expected = fh.expected_hashes(path) + titles = _hash_link_titles(ax) + assert len(titles) == 4, ( + "expected exactly 4 hash link elements, got %d: %r" % (len(titles), titles)) + want = set(expected.values()) + got = set(t.strip() for t in titles) + assert kit.rb_value(sorted(got), sorted(want)), ( + "link AXTitles %r are not the four digests %r" % (sorted(got), sorted(want))) + assert got == want + for t in got: + assert t in txt + + @pytest.mark.rb(depth=1, jump_kind="value", + expect=("the Verify find bar selects the SHA256 of kb2.bin " + "(10fc3c51a152e90e5b90319b601d92ccf37290ef53c35ff92507687d" + "8a911a08) inside the report")) + def test_find_bar_locates_the_computed_sha256(self, ax): + _home(ax) + path, txt, _blk = _report_for(ax, "kb2.bin") + sha256 = fh.expected_hash(path, "SHA256") + assert fh.hash_of(txt, "SHA256") == sha256 + try: + # depth 1: Verify opens the text finder bar over the result view + assert fh.rb_enter_find_bar(ax), "pressing Verify did not open the find bar" + assert fh.find_search_field(ax) is not None + selected = fh.search_in_results(ax, sha256) + assert kit.rb_value(selected, sha256), ( + "find next selected %r, expected the SHA256 %r" % (selected, sha256)) + assert (selected or "").strip().lower() == sha256 + finally: + fh.close_find_bar(ax) + + @pytest.mark.rb(depth=2, jump_kind="value", + expect=("'Copy hash value' on the SHA512 link puts the 128-char " + "hashlib SHA512 of hello.txt on the clipboard")) + def test_copy_hash_value_yields_the_computed_sha512(self, ax): + _home(ax) + path, txt, _blk = _report_for(ax, "hello.txt") + sha512 = fh.expected_hash(path, "SHA512") + assert fh.hash_of(txt, "SHA512") == sha512 + + got = "" + try: + from AppKit import NSPasteboard + pb = NSPasteboard.generalPasteboard() + pb.clearContents() + # depth 1: clicking the SHA512 hyperlink opens the hash context menu + opened = fh.rb_enter_hash_menu(ax, "SHA512") + if opened: + # depth 2: activating "Copy hash value" inside that menu + item = None + for mi in fh.hash_menu_items(ax): + if (mi.name or "").lower().startswith("copy"): + item = mi + break + assert item is not None, "no 'Copy hash value' item in the hash menu" + ax.action(item.id, "AXPress") + time.sleep(0.9) + got = str(pb.stringForType_("public.utf8-plain-text") or "") + if not got: + fh.dismiss_menu(ax) + got = fh.copy_hash_via_menu(ax, "SHA512") + finally: + fh.dismiss_menu(ax) + + assert kit.rb_value(got, sha512), ( + "clipboard holds %r, expected the SHA512 %r" % (got, sha512)) + assert got == sha512 + assert len(got) == 128 + + +# ── 14: a bigger input — correctness plus the speed readout ────────────────── + +class TestLargeFile: + """1 MB input: the digests still match hashlib and a speed figure is rendered.""" + + @pytest.mark.rb(depth=0, jump_kind="value", + expect=("mb1.bin (1048576 bytes) -> all four hashlib digests " + "(MD5 e3bcc6c842b22a1d9b50464ba87d969a) and a speed label " + "shaped '. B|KB|MB|GB/s'")) + def test_one_megabyte_digests_and_speed_readout(self, ax): + _home(ax) + path, _txt, blk = _report_for(ax, "mb1.bin") + expected = fh.expected_hashes(path) + for algo in ALGOS: + observed = blk.get(algo, "") + assert kit.rb_value(observed, expected[algo]), ( + "%s of mb1.bin: observed %r expected %r" + % (algo, observed, expected[algo])) + assert observed == expected[algo] + assert len(observed) == HEX_LEN[algo] + assert blk.get("size_bytes") == os.path.getsize(path) == 1048576 + assert blk.get("short_size") == "1.05 MB" + + speed = str(fh.attr(ax, fh.speed_label(ax), "AXValue", "") or "") + assert speed != "", "the speed label stayed empty after hashing 1 MB" + # magnitude is machine-dependent — only the rendered SHAPE is asserted + assert rb_value_matches(speed, SPEED_RE, "speed"), ( + "speed label %r does not match %s" % (speed, SPEED_RE)) diff --git a/macos/sunjw-fhash/tests/test_ax_menus.py b/macos/sunjw-fhash/tests/test_ax_menus.py new file mode 100644 index 0000000000000000000000000000000000000000..10c3d73671bfcf39c4547e8a6a2905618dc0a213 --- /dev/null +++ b/macos/sunjw-fhash/tests/test_ax_menus.py @@ -0,0 +1,471 @@ +"""AX MENU tests for fHash (macOS). + +Golden model: recon.md `## MENUS` (+ `## AX_TREE`, `## HELPER API`, `## VISUAL`). +Every fact asserted here was observed on the running reference app. + +Coverage map (recon row -> test): + structure fh.menu_titles == ['fHash','File','Edit','Window','Help'] + exact + item names of the `fHash` and `File` menus, the `Edit ▸ Find` / + `Edit ▸ Transformations` submenus and `Help ▸ fHash Help` + M1 fHash ▸ About fHash -> About window reached (depth 1, reach) + M2 About ▸ OK -> About window gone (depth 2, reach) + M3 File ▸ Open… -> file-chooser sheet reached (depth 1, reach) + M4 sheet ▸ Cancel -> sheet gone (depth 2, reach) + M5 ⌘O keyboard equivalent -> the SAME sheet (depth 1, reach) + M6 Edit ▸ Select All -> AXSelectedText == the report (depth 1, value) + M7 Edit ▸ Copy -> clipboard == the report (depth 1, value) + M8 hash-link context menu -> the app's own 3-item menu (depth 1, reach) + M9 Copy hash value -> clipboard == that hash (depth 2, value) + M10 Window ▸ Bring All to Front-> safe no-op, window still main (depth 0, none) + T11/T12 disabled-state facts (`Settings…`, `Open Recent ▸ Clear Menu`) + +NEVER activated here (recon "Do NOT activate"): Quit fHash, Quit and Keep Windows, +File ▸ Close, File ▸ Close All, Help ▸ fHash Help, Search Google, Search VirusTotal, +the sheet's Open / New Folder, Window ▸ Minimize, text_area.AXShowMenu. +""" + +import os +import sys +import time + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +import pytest + +import rb_testgen_kit as kit +import fhash_helpers as fh + +APP_MENUS = ["fHash", "File", "Edit", "Window", "Help"] +FHASH_MENU_ITEMS = ["About fHash", "Settings…", "Services", + "Quit fHash", "Quit and Keep Windows"] +FILE_MENU_ITEMS = ["Open…", "Open Recent", "Close", "Close All"] +EDIT_FIND_ITEMS = ["Find…", "Find and Replace…", "Find Next", + "Find Previous", "Use Selection for Find", "Jump to Selection"] +EDIT_TRANSFORM_ITEMS = ["Make Upper Case", "Make Lower Case", "Capitalize"] +HASH_MENU_ITEMS = ["Copy hash value", "Search Google", "Search VirusTotal"] + + +# ── small local utilities (semantic locators only: role + visible name) ─────── + +def _clean(names): + """Real (non-separator) item names; ASCII '...' normalised to the '…' the app uses.""" + out = [] + for n in names: + n = (n or "").strip().replace("...", "…") + if n: + out.append(n) + return out + + +def _window_count(ax): + return len(ax.find(role="window", max_results=8, max_depth=1)) + + +def _names(elements): + return [(e.name or "") for e in elements] + + +def _submenu_item(ax, menu_title, parent_needle, item_needle): + """One item inside `menu_title ▸ parent_needle`'s submenu, by visible name.""" + parent = fh.menu_item(ax, menu_title, parent_needle) + if parent is None: + return None + for i in ax.find(role="menu_item", root_id=parent.id, max_results=30): + if i.id == parent.id: + continue + if item_needle.lower() in (i.name or "").lower(): + return i + return None + + +# ── navigation helpers (named rb_* so the depth audit can see the crossing) ─── + +def rb_enter_menu_item(ax, menu_title, item_name): + """Cross into `menu_title`'s menu surface and activate `item_name` (AXPress).""" + item = (fh.menu_item(ax, menu_title, item_name, exact=True) + or fh.menu_item(ax, menu_title, item_name)) + if item is None: + return False + ok = ax.action(item.id, "AXPress") + time.sleep(0.6) + return bool(ok) + + +def rb_reach_open_panel_shortcut(ax): + """⌘O keyboard equivalent -> the file-chooser sheet (same surface as File ▸ Open…).""" + fh.activate(ax) + fh.send_key(fh.KC_O, ["cmd"]) + deadline = time.time() + 6 + while time.time() < deadline: + if ax.find(role="sheet", max_results=3, max_depth=3): + time.sleep(0.4) + return True + time.sleep(0.2) + return False + + +def rb_enter_hash_menu_and_copy(ax, algo): + """Two surfaces: hash hyperlink -> the app's hash context menu -> 'Copy hash value'. + Returns the string the app put on the pasteboard.""" + from AppKit import NSPasteboard + NSPasteboard.generalPasteboard().clearContents() + return fh.copy_hash_via_menu(ax, algo) + + +# ── structure of the app's own menus ───────────────────────────────────────── + +class TestMenuStructure: + + @pytest.mark.rb( + depth=0, jump_kind="none", + expect="App menu bar (Apple excluded) is exactly ['fHash','File','Edit','Window','Help'] " + "and the fHash menu holds About fHash / Settings… / Services / Quit fHash / " + "Quit and Keep Windows") + def test_menu_bar_titles_and_app_menu_items(self, ax): + fh.activate(ax) + fh.reset_app(ax) + + assert fh.menu_titles(ax) == APP_MENUS, ( + "menu bar titles are %r" % (fh.menu_titles(ax),)) + + items = _clean(fh.menu_item_names(ax, "fHash")) + assert items == FHASH_MENU_ITEMS, "fHash menu items are %r" % (items,) + + # every real item must carry an activatable action interface + for it in fh.menu_items(ax, "fHash", max_depth=2): + if not (it.name or "").strip(): + continue + assert "AXPress" in it.actions, "%r has no AXPress" % (it.name,) + + @pytest.mark.rb( + depth=0, jump_kind="none", + expect="File menu = Open…/Open Recent/Close/Close All; Edit ▸ Find and " + "Edit ▸ Transformations expose their recorded submenu items; Help offers fHash Help") + def test_file_edit_submenus_and_help_menu_items(self, ax): + fh.activate(ax) + fh.reset_app(ax) + + file_items = _clean(fh.menu_item_names(ax, "File")) + assert file_items == FILE_MENU_ITEMS, "File menu items are %r" % (file_items,) + + find_items = _clean(fh.submenu_item_names(ax, "Edit", "Find")) + assert find_items == EDIT_FIND_ITEMS, "Edit ▸ Find items are %r" % (find_items,) + + trans_items = _clean(fh.submenu_item_names(ax, "Edit", "Transformations")) + assert trans_items == EDIT_TRANSFORM_ITEMS, ( + "Edit ▸ Transformations items are %r" % (trans_items,)) + + recent_items = _clean(fh.submenu_item_names(ax, "File", "Open Recent")) + assert "Clear Menu" in recent_items, ( + "File ▸ Open Recent items are %r" % (recent_items,)) + + help_items = _clean(fh.menu_item_names(ax, "Help")) + assert "fHash Help" in help_items, "Help menu items are %r" % (help_items,) + # never activated (external Help Viewer) — presence + action interface only + help_item = fh.menu_item(ax, "Help", "fHash Help") + assert help_item is not None + assert "AXPress" in help_item.actions + + @pytest.mark.rb( + depth=0, jump_kind="none", + expect="fHash ▸ Settings… exists but AXEnabled is False (the app has no preferences) " + "and File ▸ Open Recent ▸ Clear Menu is AXEnabled False on a fresh launch") + def test_settings_and_clear_menu_are_present_but_disabled(self, ax): + fh.activate(ax) + fh.reset_app(ax) + + settings = fh.menu_item(ax, "fHash", "Settings") + assert settings is not None, "fHash ▸ Settings… is missing" + assert bool(settings.enabled) is False, "Settings… should be disabled" + + clear_menu = _submenu_item(ax, "File", "Open Recent", "Clear Menu") + assert clear_menu is not None, "File ▸ Open Recent ▸ Clear Menu is missing" + assert bool(clear_menu.enabled) is False, "Clear Menu should be disabled" + + # contrast: the safe sibling entries in the same menus ARE enabled + open_item = fh.menu_item(ax, "File", "Open…") or fh.menu_item(ax, "File", "Open...") + assert open_item is not None and bool(open_item.enabled) is True + + +# ── M1 / M2 — the About window surface ─────────────────────────────────────── + +class TestAboutMenuSurface: + + @pytest.mark.rb( + depth=1, jump_kind="reach", + expect="fHash ▸ About fHash opens a second window titled 'About fHash' carrying " + "button 'OK' and link 'Hosted on GitHub'") + def test_about_menu_item_opens_about_window(self, ax): + fh.activate(ax) + fh.reset_app(ax) + try: + before = kit.rb_showing(ax) + assert fh.rb_enter_about_window(ax), "fHash ▸ About fHash opened no window" + after = kit.rb_showing(ax) + assert kit.rb_reach(before, after, target="About fHash"), ( + "no 'About fHash' node appeared in the AX tree") + + win = fh.about_window(ax) + assert win is not None + assert _window_count(ax) == 2, "About should be a SECOND window" + + buttons = _names(ax.find(role="button", root_id=win.id, max_results=20)) + assert "OK" in buttons, "About window buttons are %r" % (buttons,) + + named = [(e.role, (e.name or "")) + for e in ax.find(root_id=win.id, max_results=60)] + github = [r for r, n in named if n == "Hosted on GitHub"] + assert github, "About window has no 'Hosted on GitHub' element: %r" % (named,) + assert any(r in ("link", "label", "button") for r in github) + + fh.screenshot_assert( + "menus_about_window", + "A small 'About fHash' window sits in front of the main fHash window: a large " + "red/dark app icon showing the Chinese character 希 on the left, the text " + "'fHash: Files Hash Calculator' with a version number, 'Copyright (C) 2007- SUN " + "Junwen.' and three implementation-copyright lines, a blue 'Hosted on GitHub' " + "link at the bottom-left and a blue default 'OK' button at the bottom-right.") + finally: + fh.close_about_window(ax) + + @pytest.mark.rb( + depth=2, jump_kind="reach", + expect="pressing OK inside the About window removes every 'About fHash' node from the " + "AX tree and leaves exactly 1 window (the main window)") + def test_about_ok_button_closes_the_about_window(self, ax): + fh.activate(ax) + fh.reset_app(ax) + try: + assert fh.rb_enter_about_window(ax), "fHash ▸ About fHash opened no window" + before_close = kit.rb_showing(ax) + assert fh.about_window(ax) is not None + + assert fh.close_about_window(ax), "the About window's OK button did not close it" + after_close = kit.rb_showing(ax) + + # reverse reach: the About surface that WAS showing is gone again + assert kit.rb_reach(after_close, before_close, target="About fHash"), ( + "'About fHash' nodes did not disappear") + assert fh.about_window(ax) is None + assert _window_count(ax) == 1 + assert fh.main_window(ax) is not None + finally: + fh.close_about_window(ax) + + +# ── M3 / M4 / M5 — the file-chooser sheet surface ──────────────────────────── + +class TestOpenPanelMenuSurface: + + @pytest.mark.rb( + depth=1, jump_kind="reach", + expect="File ▸ Open… slides a sheet named 'open' over the main window, exposing " + "button 'Cancel' and button 'New Folder'") + def test_file_open_menu_item_opens_chooser_sheet(self, ax): + fh.activate(ax) + fh.reset_app(ax) + try: + before = kit.rb_showing(ax) + assert fh.rb_enter_open_panel_via_menu(ax), "File ▸ Open… produced no sheet" + after = kit.rb_showing(ax) + assert kit.rb_reach(before, after, target="sheet"), ( + "no sheet node appeared in the AX tree") + + sheets = ax.find(role="sheet", max_results=3, max_depth=3) + assert sheets, "the file chooser sheet is not in the tree" + buttons = _names(ax.find(role="button", root_id=sheets[0].id, max_results=60)) + assert "Cancel" in buttons, "sheet buttons are %r" % (buttons,) + assert "New Folder" in buttons, "sheet buttons are %r" % (buttons,) + assert _window_count(ax) == 1, "the sheet must attach to the main window" + + fh.screenshot_assert( + "menus_open_panel_sheet", + "A macOS open-file sheet is slid down over the small fHash window: a " + "Favorites/Locations sidebar on the left, a file browser column view in the " + "middle, a 'Where:' popup and 'New Folder', 'Cancel' and 'Open' buttons along " + "the bottom of the sheet.") + finally: + fh.close_open_panel(ax) + + @pytest.mark.rb( + depth=2, jump_kind="reach", + expect="Cancel inside the File ▸ Open… sheet removes the sheet from the AX tree and " + "returns the app to its single main window") + def test_open_sheet_cancel_button_closes_the_sheet(self, ax): + fh.activate(ax) + fh.reset_app(ax) + try: + assert fh.rb_enter_open_panel_via_menu(ax), "File ▸ Open… produced no sheet" + before_close = kit.rb_showing(ax) + assert ax.find(role="sheet", max_results=3, max_depth=3) + + assert fh.close_open_panel(ax), "Cancel did not dismiss the sheet" + after_close = kit.rb_showing(ax) + + assert kit.rb_reach(after_close, before_close, target="sheet"), ( + "the sheet nodes did not disappear") + assert not ax.find(role="sheet", max_results=3, max_depth=3) + assert _window_count(ax) == 1 + finally: + fh.close_open_panel(ax) + + @pytest.mark.rb( + depth=1, jump_kind="reach", + expect="the ⌘O keyboard equivalent of File ▸ Open… reaches the SAME chooser sheet " + "(sheet + button 'Cancel' appear)") + def test_command_o_shortcut_opens_the_same_chooser_sheet(self, ax): + fh.activate(ax) + fh.reset_app(ax) + try: + before = kit.rb_showing(ax) + assert rb_reach_open_panel_shortcut(ax), "⌘O produced no sheet" + after = kit.rb_showing(ax) + assert kit.rb_reach(before, after, target="sheet"), ( + "no sheet node appeared after ⌘O") + + sheets = ax.find(role="sheet", max_results=3, max_depth=3) + assert sheets + buttons = _names(ax.find(role="button", root_id=sheets[0].id, max_results=60)) + assert "Cancel" in buttons, "sheet buttons are %r" % (buttons,) + assert "New Folder" in buttons, "sheet buttons are %r" % (buttons,) + finally: + fh.close_open_panel(ax) + + +# ── M6 / M7 — Edit menu actions on the result report ───────────────────────── + +class TestEditMenuActions: + + @pytest.mark.rb( + depth=1, jump_kind="value", + expect="after hashing hello.txt, Edit ▸ Select All sets text_area.AXSelectedText to the " + "whole report, which contains 'MD5: 5d41402abc4b2a76b9719d911017c592'") + def test_edit_select_all_selects_the_whole_report(self, ax): + fh.activate(ax) + fh.reset_app(ax) + path = fh.fixture("hello.txt") + report = fh.feed_files(ax, [path]) + assert "SHA512:" in report, "hello.txt was not hashed: %r" % (report[:200],) + + assert rb_enter_menu_item(ax, "Edit", "Select All"), "Edit ▸ Select All did not fire" + time.sleep(0.4) + + selected = str(fh.attr(ax, fh.text_area(ax), "AXSelectedText", "") or "") + full = fh.result_text(ax) + assert kit.rb_value(selected, full), ( + "AXSelectedText (%d chars) != the report (%d chars)" % (len(selected), len(full))) + + md5 = fh.expected_hash(path, "MD5") + assert kit.rb_value(selected, "MD5: " + md5), ( + "the selection does not carry 'MD5: %s'" % md5) + assert selected.startswith("Name: ") + + @pytest.mark.rb( + depth=1, jump_kind="value", + expect="Edit ▸ Copy after Select All puts the whole hello.txt report on the pasteboard, " + "containing 'Name: ' and the MD5 5d41402abc4b2a76b9719d911017c592") + def test_edit_copy_puts_the_report_on_the_pasteboard(self, ax): + from AppKit import NSPasteboard + + fh.activate(ax) + fh.reset_app(ax) + path = fh.fixture("hello.txt") + report = fh.feed_files(ax, [path]) + assert "SHA512:" in report, "hello.txt was not hashed: %r" % (report[:200],) + + pb = NSPasteboard.generalPasteboard() + pb.clearContents() + assert not (pb.stringForType_("public.utf8-plain-text") or "") + + assert rb_enter_menu_item(ax, "Edit", "Select All"), "Edit ▸ Select All did not fire" + assert rb_enter_menu_item(ax, "Edit", "Copy"), "Edit ▸ Copy did not fire" + time.sleep(0.5) + + clip = str(pb.stringForType_("public.utf8-plain-text") or "") + md5 = fh.expected_hash(path, "MD5") + assert kit.rb_value(clip, md5), "clipboard %r lacks the MD5 %s" % (clip[:200], md5) + assert "MD5: " in clip + assert "Name: " in clip + + +# ── M8 / M9 — the app's own hash context menu ──────────────────────────────── + +class TestHashContextMenu: + + @pytest.mark.rb( + depth=1, jump_kind="reach", + expect="clicking the MD5 hyperlink of a hashed fox.txt pops the app's own context menu " + "with exactly 'Copy hash value', 'Search Google', 'Search VirusTotal'") + def test_hash_link_opens_the_apps_hash_context_menu(self, ax): + fh.activate(ax) + fh.reset_app(ax) + report = fh.feed_files(ax, [fh.fixture("fox.txt")]) + assert "SHA512:" in report, "fox.txt was not hashed: %r" % (report[:200],) + try: + before = kit.rb_showing(ax) + assert fh.rb_enter_hash_menu(ax, "MD5"), "the MD5 hyperlink opened no menu" + after = kit.rb_showing(ax) + assert kit.rb_reach(before, after, target="Copy hash value"), ( + "'Copy hash value' did not appear in the AX tree") + + names = _names(fh.hash_menu_items(ax)) + assert names == HASH_MENU_ITEMS, "hash menu items are %r" % (names,) + + fh.screenshot_assert( + "menus_hash_context_menu", + "A small pop-up menu is open over the result text of the fHash window listing " + "'Copy hash value', then a separator, then 'Search Google' and 'Search " + "VirusTotal'; behind it the text area shows the fox.txt report whose MD5/SHA1/" + "SHA256/SHA512 values are rendered as blue hyperlink text.") + finally: + fh.dismiss_menu(ax) + + @pytest.mark.rb( + depth=2, jump_kind="value", + expect="hash link ▸ Copy hash value writes exactly the SHA256 of fox.txt " + "(d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592) to the " + "pasteboard, with no surrounding whitespace") + def test_copy_hash_value_menu_item_copies_that_hash(self, ax): + fh.activate(ax) + fh.reset_app(ax) + path = fh.fixture("fox.txt") + report = fh.feed_files(ax, [path]) + assert "SHA512:" in report, "fox.txt was not hashed: %r" % (report[:200],) + try: + got = rb_enter_hash_menu_and_copy(ax, "SHA256") + expected = fh.expected_hash(path, "SHA256") + assert kit.rb_value(got, expected), "clipboard is %r, expected %r" % (got, expected) + assert got == got.strip(), "the copied hash carries surrounding whitespace: %r" % got + assert got == expected + finally: + fh.dismiss_menu(ax) + + +# ── M10 — Window menu safe no-op ───────────────────────────────────────────── + +class TestWindowMenu: + + @pytest.mark.rb( + depth=0, jump_kind="none", + expect="Window ▸ Bring All to Front is a safe no-op: afterwards there is still exactly " + "one window, it is the main window and its AXMain is True") + def test_window_bring_all_to_front_is_a_safe_no_op(self, ax): + fh.activate(ax) + fh.reset_app(ax) + + window_items = _clean(fh.menu_item_names(ax, "Window")) + assert "Bring All to Front" in window_items, "Window menu items are %r" % (window_items,) + assert "Arrange in Front" in window_items, "Window menu items are %r" % (window_items,) + assert "Minimize" in window_items # present, never activated + + item = fh.menu_item(ax, "Window", "Bring All to Front", exact=True) + assert item is not None + assert "AXPress" in item.actions + assert ax.action(item.id, "AXPress") + time.sleep(0.6) + + assert _window_count(ax) == 1, "Bring All to Front must not add/remove windows" + win = fh.main_window(ax) + assert win is not None, "the main window disappeared" + assert bool(fh.attr(ax, win, "AXMain", False)) is True, "the main window lost AXMain" + assert fh.result_text(ax).startswith(fh.INIT_TEXT) diff --git a/macos/sunjw-fhash/tests/test_ax_states.py b/macos/sunjw-fhash/tests/test_ax_states.py new file mode 100644 index 0000000000000000000000000000000000000000..a15c861873e82554cc7d549e8afde1a52ad85fc8 --- /dev/null +++ b/macos/sunjw-fhash/tests/test_ax_states.py @@ -0,0 +1,658 @@ +"""AX STATE tests for fHash (CHECKED / ENABLED / focus lane). + +Every assertion below was recorded from the running reference app (recon `## STATE`, +rows T1–T17). Each test declares its navigation depth + jump rigor with +`@pytest.mark.rb(...)`; transitions are backed by `kit.rb_flip(before, after)`. + +Locators are semantic (AXRole + visible AXTitle/AXDescription) and go through the +portable `fhash_helpers` driver, so the SAME file drives the reference and a +recreation. Nothing here spawns a binary or knows an install path. +""" + +import os +import sys +import time +import re + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +import pytest +import rb_testgen_kit as kit +import fhash_helpers as fh + + +SPEED_RE = re.compile(r"^\d+\.\d{2} (B|KB|MB|GB)/s$") + + +# ── small local readers (semantic, framework-agnostic) ──────────────────────── + +def _flag(ax, element, name, default=None): + """Read a boolean-ish AX attribute as a real bool (None when absent).""" + v = fh.attr(ax, element, name, default) + if v is None: + return None + if isinstance(v, bool): + return v + if isinstance(v, (int, float)): + return bool(v) + if isinstance(v, str): + return v.strip().lower() in ("1", "true", "yes") + return bool(v) + + +def _checkbox_value(ax): + """AXValue of the 'Uppercase' checkbox as an int (0/1), or None.""" + cb = fh.uppercase_checkbox(ax) + if cb is None: + return None + v = fh.attr(ax, cb, "AXValue", None) + try: + return int(v) + except (TypeError, ValueError): + return None + + +def _press_uppercase(ax): + cb = fh.uppercase_checkbox(ax) + assert cb is not None, "no 'Uppercase' checkbox in the main window" + ax.action(cb.id, "AXPress") + time.sleep(0.6) + + +def _open_stop_title(ax): + b = fh.open_button(ax) + # fHash exposes this label as the element NAME; a live AXTitle read is empty in both + # the idle and the calculating state, so reading AXTitle saw '' instead of 'Open...'. + return fh.button_title(ax, b) if b is not None else "" + + +def _progress_value(ax): + v = fh.attr(ax, fh.progress_indicator(ax), "AXValue", None) + try: + return float(v) + except (TypeError, ValueError): + return None + + +def _wait_progress(ax, pred, timeout=8.0): + deadline = time.time() + timeout + v = _progress_value(ax) + while time.time() < deadline: + v = _progress_value(ax) + if v is not None and pred(v): + return v + time.sleep(0.1) + return v + + +def _wait_md5(ax, expected, timeout=4.0): + """Poll the report until its first MD5 equals `expected` (returns what it saw).""" + deadline = time.time() + timeout + got = fh.hash_of(fh.result_text(ax), "MD5") + while time.time() < deadline: + got = fh.hash_of(fh.result_text(ax), "MD5") + if got == expected: + return got + time.sleep(0.15) + return got + + +def _window_button_by_subrole(ax, subrole): + """A window-frame button located by AXSubrole (close/zoom/minimize).""" + w = fh.main_window(ax) + if w is None: + return None + for b in ax.find(role="button", root_id=w.id, max_results=40): + if str(fh.attr(ax, b, "AXSubrole", "") or "") == subrole: + return b + return None + + +def _sheet_button(ax, title): + """A button of the open-panel sheet, matched by its visible title.""" + sheets = ax.find(role="sheet", max_results=3, max_depth=3) + if not sheets: + return None + for b in ax.find(role="button", root_id=sheets[0].id, max_results=80): + if (b.name or "") == title: + return b + return None + + +def _focused_signature(ax): + """{'role|name'} for every main-window widget currently reporting AXFocused True.""" + w = fh.main_window(ax) + if w is None: + return set() + try: + tree = ax.tree(root_id=w.id, max_depth=12) + except Exception: + return set() + out = set() + stack = [tree] + while stack: + node = stack.pop() + if not isinstance(node, dict): + continue + nid = node.get("id") + if nid: + try: + if bool(ax.get(nid, ["AXFocused"]).get("AXFocused")): + out.add("%s|%s" % (node.get("role") or "", node.get("name") or "")) + except Exception: + pass + for c in (node.get("children") or []): + stack.append(c) + return out + + +def _ensure_window(ax): + """Reveal the app's window if it is not already exposed (no-op for fHash, whose + main window is visible on launch — kept so a recreation that hides it still works).""" + w = fh.main_window(ax) + if w is None: + try: + ax.ensure_ui_visible() + except Exception: + pass + time.sleep(1.0) + w = fh.main_window(ax) + return w + + +def _start_big_calculation(ax, path, timeout=6.0): + """Hand a big file to the running app and wait until it reports calculating mode + (the Open... button's title flips to 'Stop'). True when that state was observed.""" + if not fh._deliver_via_workspace(ax, [path]): + fh._deliver_via_appleevent(ax, [path]) + deadline = time.time() + timeout + while time.time() < deadline: + if _open_stop_title(ax) == fh.STOP_TITLE: + return True + time.sleep(0.1) + return False + + +# ── T1 / T2 / T3 / T4 — the Uppercase checkbox ──────────────────────────────── + +class TestUppercaseCheckboxState: + + @pytest.mark.rb(depth=0, jump_kind="transition", + expect="checkbox 0→1 and hashes become upper case") + def test_uppercase_checkbox_flips_and_rerenders_report(self, ax): + fh.activate(ax) + _ensure_window(ax) + fh.reset_app(ax) + + path = fh.fixture("hello.txt") + fh.feed_files(ax, [path]) + lower = fh.expected_hash(path, "MD5") + assert fh.hash_of(fh.result_text(ax), "MD5") == lower, ( + "expected the lowercase MD5 of hello.txt in the fresh report") + + before = _checkbox_value(ax) + assert before == 0, "Uppercase must start unchecked (AXValue 0)" + + _press_uppercase(ax) + after = _checkbox_value(ax) + assert kit.rb_flip(before, after), ( + "Uppercase AXValue did not flip on AXPress (%r -> %r)" % (before, after)) + assert after == 1 + assert _wait_md5(ax, lower.upper()) == lower.upper(), ( + "checking Uppercase must re-render the existing hashes in UPPER case") + + fh.screenshot_assert( + "states_uppercase_checked", + "The fHash window shows the hash report for hello.txt and every hash value " + "on the MD5, SHA1, SHA256 and SHA512 lines is rendered in UPPERCASE " + "hexadecimal; the 'Uppercase' checkbox at the bottom-left of the window is " + "ticked. The 'Clear', 'Verify' and 'Open...' buttons stay enabled.") + + _press_uppercase(ax) + back = _checkbox_value(ax) + assert kit.rb_flip(after, back), ( + "Uppercase AXValue did not flip back (%r -> %r)" % (after, back)) + assert back == 0 + assert _wait_md5(ax, lower) == lower, ( + "unchecking Uppercase must restore the lowercase hashlib digests") + + @pytest.mark.rb(depth=0, jump_kind="transition", + expect="checkbox 0→1 while the result text stays the init prompt") + def test_uppercase_toggle_with_no_results_leaves_text_unchanged(self, ax): + fh.activate(ax) + _ensure_window(ax) + fh.reset_app(ax) + + assert fh.clear_results(ax), "Clear did not restore the initial prompt" + text_before = fh.result_text(ax) + assert fh.INIT_TEXT in text_before + + before = _checkbox_value(ax) + assert before == 0 + _press_uppercase(ax) + after = _checkbox_value(ax) + assert kit.rb_flip(before, after), ( + "Uppercase AXValue did not flip with no results present (%r -> %r)" + % (before, after)) + assert after == 1 + + time.sleep(0.4) + assert fh.result_text(ax) == text_before, ( + "toggling Uppercase with no results must not touch the result text") + + @pytest.mark.rb(depth=0, jump_kind="transition", + expect="Clear resets the report text but leaves Uppercase checked (1)") + def test_clear_does_not_reset_uppercase(self, ax): + fh.activate(ax) + _ensure_window(ax) + fh.reset_app(ax) + + assert fh.set_uppercase(ax, True), "could not check the Uppercase checkbox" + fh.feed_files(ax, [fh.fixture("hello.txt")]) + text_before = fh.result_text(ax) + assert "MD5:" in text_before + assert _checkbox_value(ax) == 1 + + assert fh.clear_results(ax), "Clear did not restore the initial prompt" + text_after = fh.result_text(ax) + assert kit.rb_flip(text_before, text_after), ( + "Clear did not change the result text") + assert fh.INIT_TEXT in text_after and "MD5:" not in text_after + assert _checkbox_value(ax) == 1, ( + "Clear must NOT reset the Uppercase checkbox") + + +# ── T5 / T6 / T7 — calculating mode disables the controls ───────────────────── + +class TestCalculatingModeState: + + @pytest.mark.rb(depth=0, jump_kind="transition", + expect="Open...→Stop and Clear/Verify/Uppercase become disabled") + def test_calculating_mode_disables_controls(self, ax, tmp_path): + fh.activate(ax) + _ensure_window(ax) + fh.reset_app(ax) + + big = fh.make_big_file(tmp_path, 400) + before_title = _open_stop_title(ax) + assert before_title == fh.OPEN_TITLE, ( + "idle title should be %r, got %r" % (fh.OPEN_TITLE, before_title)) + assert _flag(ax, fh.clear_button(ax), "AXEnabled") is True + assert _flag(ax, fh.verify_button(ax), "AXEnabled") is True + assert _flag(ax, fh.uppercase_checkbox(ax), "AXEnabled") is True + + try: + started = _start_big_calculation(ax, big) + after_title = _open_stop_title(ax) + assert started and after_title == fh.STOP_TITLE, ( + "the app never entered calculating mode (title %r)" % (after_title,)) + + clear_en = _flag(ax, fh.clear_button(ax), "AXEnabled") + verify_en = _flag(ax, fh.verify_button(ax), "AXEnabled") + upper_en = _flag(ax, fh.uppercase_checkbox(ax), "AXEnabled") + + fh.screenshot_assert( + "states_calculating_disabled", + "The fHash window is mid-calculation: the bottom-right button reads " + "'Stop' instead of 'Open...', the 'Clear' and 'Verify' buttons and the " + "'Uppercase' checkbox at the bottom-left are greyed out (disabled), and " + "the thin horizontal progress bar under the text area is partially " + "filled.") + + assert kit.rb_flip(before_title, after_title), ( + "the Open.../Stop button title did not flip (%r -> %r)" + % (before_title, after_title)) + assert clear_en is False, "Clear must be AXEnabled False while calculating" + assert verify_en is False, "Verify must be AXEnabled False while calculating" + assert upper_en is False, "Uppercase must be AXEnabled False while calculating" + finally: + fh.wait_for_idle(ax) + + @pytest.mark.rb(depth=0, jump_kind="transition", + expect="Stop→Open... and Clear/Verify/Uppercase are AXEnabled True again") + def test_controls_reenable_when_calculation_finishes(self, ax, tmp_path): + fh.activate(ax) + _ensure_window(ax) + fh.reset_app(ax) + + big = fh.make_big_file(tmp_path, 400) + try: + assert _start_big_calculation(ax, big), ( + "the app never entered calculating mode") + busy_title = _open_stop_title(ax) + assert busy_title == fh.STOP_TITLE + + assert fh.wait_for_idle(ax, timeout=25), ( + "the calculation never returned to the idle state") + idle_title = _open_stop_title(ax) + assert kit.rb_flip(busy_title, idle_title), ( + "the button title did not flip back (%r -> %r)" + % (busy_title, idle_title)) + assert idle_title == fh.OPEN_TITLE + assert _flag(ax, fh.clear_button(ax), "AXEnabled") is True + assert _flag(ax, fh.verify_button(ax), "AXEnabled") is True + assert _flag(ax, fh.uppercase_checkbox(ax), "AXEnabled") is True + finally: + fh.wait_for_idle(ax) + + +# ── T8 / T9 — the progress indicator ────────────────────────────────────────── + +class TestProgressIndicatorState: + + @pytest.mark.rb(depth=0, jump_kind="transition", + expect="progress 0.0 → 1.0 after hashing, back to 0.0 after Clear") + def test_progress_zero_to_one_and_back(self, ax): + fh.activate(ax) + _ensure_window(ax) + fh.reset_app(ax) + + prog = fh.progress_indicator(ax) + assert prog is not None, "no progress indicator in the main window" + assert float(fh.attr(ax, prog, "AXMinValue", -1)) == 0.0 + assert float(fh.attr(ax, prog, "AXMaxValue", -1)) == 1.0 + + before = _progress_value(ax) + assert before == 0.0, "progress must be 0.0 at idle, got %r" % (before,) + + fh.feed_files(ax, [fh.fixture("hello.txt")]) + after = _wait_progress(ax, lambda v: v >= 0.999, timeout=8.0) + assert kit.rb_flip(before, after), ( + "progress did not move after hashing (%r -> %r)" % (before, after)) + assert after is not None and abs(after - 1.0) < 1e-6, ( + "progress should read 1.0 once hashing finished, got %r" % (after,)) + + assert fh.clear_results(ax), "Clear did not restore the initial prompt" + reset = _wait_progress(ax, lambda v: v <= 1e-6, timeout=5.0) + assert reset is not None and abs(reset) < 1e-6, ( + "Clear should reset the progress indicator to 0.0, got %r" % (reset,)) + + @pytest.mark.rb(depth=0, jump_kind="transition", + expect="progress advances strictly between 0.0 and 1.0 while the button reads Stop") + def test_progress_moves_mid_calculation(self, ax, tmp_path): + fh.activate(ax) + _ensure_window(ax) + fh.reset_app(ax) + + big = fh.make_big_file(tmp_path, 400) + idle = _progress_value(ax) + assert idle == 0.0 + + samples = [] + try: + assert _start_big_calculation(ax, big), ( + "the app never entered calculating mode") + deadline = time.time() + 10.0 + while time.time() < deadline: + v = _progress_value(ax) + if _open_stop_title(ax) != fh.STOP_TITLE: + break + if v is not None: + samples.append(v) + time.sleep(0.05) + finally: + fh.wait_for_idle(ax) + + assert samples, "captured no progress samples while the app reported 'Stop'" + peak = max(samples) + distinct = set(samples) + moved = kit.rb_flip(idle, peak) or len(distinct) > 1 + assert moved, "progress never moved during the calculation (samples=%r)" % ( + sorted(distinct)[:8],) + assert (0.0 < peak < 1.0) or len(distinct) > 1, ( + "mid-calculation progress should be strictly between 0.0 and 1.0 or vary; " + "samples=%r" % (sorted(distinct)[:8],)) + + +# ── T10 / T11 / T12 — menu item enabled-ness ────────────────────────────────── + +class TestMenuItemEnabledState: + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="Edit>Copy AXEnabled False→True") + def test_edit_copy_enables_after_select_all(self, ax): + fh.activate(ax) + _ensure_window(ax) + fh.reset_app(ax) + + def rb_enter_edit_menu_selection(): + """Cross into the Edit menu and activate 'Select All' (depth+1).""" + item = fh.menu_item(ax, "Edit", "Select All", exact=True) + assert item is not None, "no 'Select All' item in the Edit menu" + assert item.enabled is True, "'Select All' should be enabled with results shown" + ax.action(item.id, "AXPress") + time.sleep(0.8) + return True + + try: + fh.feed_files(ax, [fh.fixture("hello.txt")]) + assert "MD5:" in fh.result_text(ax) + + copy_before = fh.menu_item(ax, "Edit", "Copy", exact=True) + assert copy_before is not None, "no 'Copy' item in the Edit menu" + before = copy_before.enabled + assert before is False, ( + "Edit > Copy should start AXEnabled False (nothing selected)") + + assert rb_enter_edit_menu_selection() + + copy_after = fh.menu_item(ax, "Edit", "Copy", exact=True) + assert copy_after is not None + after = copy_after.enabled + assert kit.rb_flip(before, after), ( + "Edit > Copy AXEnabled did not flip after Select All (%r -> %r)" + % (before, after)) + assert after is True + finally: + fh.dismiss_menu(ax) + + @pytest.mark.rb(depth=0, jump_kind="none", + expect="fHash>Settings… and File>Open Recent>Clear Menu are AXEnabled False") + def test_permanently_disabled_menu_items(self, ax): + fh.activate(ax) + _ensure_window(ax) + fh.reset_app(ax) + + settings = fh.menu_item(ax, "fHash", "Settings") + assert settings is not None, "no 'Settings…' item in the fHash application menu" + assert settings.enabled is False, ( + "fHash > Settings… must be present but disabled (the app has no preferences)") + + clear_menu = fh.menu_item(ax, "File", "Clear Menu") + assert clear_menu is not None, ( + "no 'Clear Menu' item under File > Open Recent") + assert clear_menu.enabled is False, ( + "File > Open Recent > Clear Menu must be disabled on a fresh launch") + + +# ── T13 / T14 — window frame + window flags ─────────────────────────────────── + +class TestWindowState: + + @pytest.mark.rb(depth=0, jump_kind="none", + expect="AXZoomButton AXEnabled False; AXCloseButton and AXMinimizeButton True") + def test_window_frame_button_states(self, ax): + fh.activate(ax) + _ensure_window(ax) + fh.reset_app(ax) + + zoom = _window_button_by_subrole(ax, "AXZoomButton") + close = _window_button_by_subrole(ax, "AXCloseButton") + minimize = _window_button_by_subrole(ax, "AXMinimizeButton") + + assert zoom is not None, "the main window exposes no AXZoomButton" + assert close is not None, "the main window exposes no AXCloseButton" + assert minimize is not None, "the main window exposes no AXMinimizeButton" + + # Read-only: these are never pressed (pressing close would terminate the app). + assert _flag(ax, zoom, "AXEnabled") is False, ( + "the zoom button must be disabled (the window is not resizable)") + assert _flag(ax, close, "AXEnabled") is True + assert _flag(ax, minimize, "AXEnabled") is True + + @pytest.mark.rb(depth=0, jump_kind="none", + expect="main window AXMain True, not minimized/fullscreen/modal, AXDefaultButton set") + def test_main_window_flags(self, ax): + fh.activate(ax) + _ensure_window(ax) + fh.reset_app(ax) + + win = fh.main_window(ax) + assert win is not None, "the app exposes no main window" + + assert _flag(ax, win, "AXMain", False) is True, "the main window must be AXMain" + assert _flag(ax, win, "AXMinimized", False) is False + assert _flag(ax, win, "AXFullScreen", False) is False + assert _flag(ax, win, "AXModal", False) is False + assert fh.attr(ax, win, "AXDefaultButton", None) is not None, ( + "the main window must expose a default button (Open...)") + assert str(fh.attr(ax, win, "AXSubrole", "")) == "AXStandardWindow" + + +# ── T15 — the speed label lifecycle ─────────────────────────────────────────── + +class TestSpeedLabelState: + + @pytest.mark.rb(depth=0, jump_kind="transition", + expect="speed label '' → matches N.NN /s → '' after Clear") + def test_speed_label_lifecycle(self, ax): + fh.activate(ax) + _ensure_window(ax) + fh.reset_app(ax) + + label = fh.speed_label(ax) + assert label is not None, "no speed label in the main window" + before = str(fh.attr(ax, label, "AXValue", "") or "") + assert before == "", "the speed label must be empty at idle, got %r" % (before,) + + fh.feed_files(ax, [fh.fixture("mb1.bin")]) + during = "" + deadline = time.time() + 6.0 + while time.time() < deadline: + during = str(fh.attr(ax, fh.speed_label(ax), "AXValue", "") or "") + if during: + break + time.sleep(0.15) + + assert kit.rb_flip(before, during), ( + "the speed label did not change after hashing (%r -> %r)" % (before, during)) + assert SPEED_RE.match(during), ( + "speed label %r does not match '^\\d+\\.\\d{2} (B|KB|MB|GB)/s$'" % (during,)) + + assert fh.clear_results(ax), "Clear did not restore the initial prompt" + after = "" + deadline = time.time() + 4.0 + while time.time() < deadline: + after = str(fh.attr(ax, fh.speed_label(ax), "AXValue", "") or "") + if after == "": + break + time.sleep(0.15) + assert after == "", "Clear must blank the speed label, got %r" % (after,) + + +# ── T16 + focus — the find (Verify) bar ─────────────────────────────────────── + +class TestFindBarState: + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="Done/find next/find previous absent→AXEnabled True; search field settable") + def test_find_bar_widget_states(self, ax): + fh.activate(ax) + _ensure_window(ax) + fh.reset_app(ax) + + before = (_flag(ax, fh.find_done_button(ax), "AXEnabled"), + _flag(ax, fh.find_next_button(ax), "AXEnabled"), + _flag(ax, fh.find_prev_button(ax), "AXEnabled")) + assert before == (None, None, None), ( + "the find bar must not exist before Verify is pressed, saw %r" % (before,)) + + try: + assert fh.rb_enter_find_bar(ax), "pressing Verify did not open the find bar" + + done = fh.find_done_button(ax) + nxt = fh.find_next_button(ax) + prev = fh.find_prev_button(ax) + assert done is not None, "no 'Done' button in the find bar" + assert nxt is not None, "no 'find next' button in the find bar" + assert prev is not None, "no 'find previous' button in the find bar" + + after = (_flag(ax, done, "AXEnabled"), + _flag(ax, nxt, "AXEnabled"), + _flag(ax, prev, "AXEnabled")) + assert kit.rb_flip(before, after), ( + "find bar enabled-state did not change (%r -> %r)" % (before, after)) + assert after == (True, True, True), ( + "Done / find next / find previous must all be AXEnabled True, got %r" + % (after,)) + + field = fh.find_search_field(ax) + assert field is not None, "no search text field in the find bar" + assert ax.set_value(field.id, "5d41402a"), ( + "the find bar's search field did not accept AXValue") + time.sleep(0.4) + assert str(fh.attr(ax, field, "AXValue", "") or "") == "5d41402a", ( + "the search field did not read back the value that was set") + + fh.screenshot_assert( + "states_find_bar_widgets", + "A search bar is shown at the top of the fHash result text area: a " + "rounded search field containing the text '5d41402a', small up and down " + "chevron buttons (find previous / find next) and an enabled 'Done' " + "button on its right. The 'Uppercase' checkbox and the 'Clear', " + "'Verify', 'Open...' buttons are still visible along the bottom row.") + finally: + fh.close_find_bar(ax) + + @pytest.mark.rb(depth=0, jump_kind="transition", + expect="keyboard focus moves onto the find bar's search field when it opens") + def test_focus_moves_to_find_bar_search_field(self, ax): + fh.activate(ax) + _ensure_window(ax) + fh.reset_app(ax) + + before = _focused_signature(ax) + try: + assert fh.rb_enter_find_bar(ax), "pressing Verify did not open the find bar" + field = fh.find_search_field(ax) + assert field is not None, "no search text field in the find bar" + + time.sleep(0.4) + after = _focused_signature(ax) + field_focused = _flag(ax, field, "AXFocused", False) is True + + assert kit.rb_flip(before, after) or field_focused, ( + "opening the find bar did not move keyboard focus " + "(focused before=%r, after=%r, field AXFocused=%r)" + % (sorted(before), sorted(after), field_focused)) + finally: + fh.close_find_bar(ax) + + +# ── T17 — the file chooser sheet's button states ────────────────────────────── + +class TestOpenPanelState: + + @pytest.mark.rb(depth=1, jump_kind="none", + expect="open panel's 'Open' button AXEnabled False while 'Cancel' is True") + def test_open_panel_open_button_starts_disabled(self, ax): + fh.activate(ax) + _ensure_window(ax) + fh.reset_app(ax) + + try: + assert fh.rb_enter_open_panel(ax), ( + "pressing 'Open...' did not present the file chooser sheet") + + open_btn = _sheet_button(ax, "Open") + cancel_btn = _sheet_button(ax, "Cancel") + assert open_btn is not None, "no 'Open' button in the file chooser sheet" + assert cancel_btn is not None, "no 'Cancel' button in the file chooser sheet" + + # Never pressed — only their state is read. + assert _flag(ax, open_btn, "AXEnabled") is False, ( + "the sheet's 'Open' button must be disabled while nothing is selected") + assert _flag(ax, cancel_btn, "AXEnabled") is True, ( + "the sheet's 'Cancel' button must be enabled") + finally: + fh.close_open_panel(ax) diff --git a/macos/sunjw-fhash/tests/test_ax_structure.py b/macos/sunjw-fhash/tests/test_ax_structure.py new file mode 100644 index 0000000000000000000000000000000000000000..468c145b8bf5fe04dec1bf025c5a1f2999e69125 --- /dev/null +++ b/macos/sunjw-fhash/tests/test_ax_structure.py @@ -0,0 +1,564 @@ +"""AX STRUCTURE tests for fHash (org.sunjw.fHashMacUI). + +Every fact asserted here was recorded from the running reference app in recon.md +(`## AX_TREE`, `## STRUCTURE`, `## VISUAL`). The module owns two things: + + * a small existence GATE (<=30% of the suite): the single main window, its named + children, the app menu-bar titles, the window buttons by AXSubrole — plus the + role-diversity / interactive-widget-count assertions folded into those gates. + * SHAPE DELTAS S1..S8: every assertion is a before/after node-count or window-count + change proven with kit.rb_flip / kit.rb_reach, and every surface we enter is + entered through an fh.rb_enter_* navigation helper (so the depth audit sees it). + +Main-window subtree node counts (fh.scroll_area_widget_count) observed on the +reference and stable across repeats: 14 idle / 21 with the find bar / 24 after one +hashed file / >100 with the file-chooser sheet open. +""" + +import os +import sys +import time # noqa: F401 (kept: shared import preamble for the fHash suite) +from collections import Counter + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +import pytest +import rb_testgen_kit as kit +import fhash_helpers as fh + + +# ── Observed reference constants (recon ## STRUCTURE) ──────────────────────── +IDLE_NODES = 14 # main-window subtree, home surface +FIND_BAR_NODES = 21 # after pressing Verify +ONE_FILE_NODES = 24 # after hashing one file +SHEET_NODES_MIN = 100 # open panel: 123 on the reference, sidebar-dependent +ABOUT_NODES = 12 # the About fHash window subtree, read AFTER it settles + # (it reads 11 for the first ~0.4 s, then an unnamed AXGroup + # appears and it stays at 12 -- the frozen 11 was an + # unsettled snapshot and failed on the reference itself) +MENU_TITLES = ["fHash", "File", "Edit", "Window", "Help"] +IDLE_ROLES = {"window", "progress", "button", "label", "checkbox", + "scroll_area", "text_area"} +HASH_ROLES = {"link", "scroll_bar", "value_indicator"} +HASH_LENGTHS = {32, 40, 64, 128} # MD5 / SHA1 / SHA256 / SHA512 hex digests + + +# ── Local tree readers (built on the ax fixture's own tree() API) ──────────── + +def _flatten(ax, root_id, max_depth=12): + """Flatten the AX subtree under `root_id` into [{role, name, actions}, ...]. + + Uses the AXHelper handed to the test by the `ax` fixture — no AX app handles + are created here, so the same code drives the reference and a recreation. + """ + try: + tree = ax.tree(root_id=root_id, max_depth=max_depth) + except Exception: + return [] + out = [] + + def _walk(node): + if not isinstance(node, dict): + return + out.append({ + "role": str(node.get("role") or ""), + "name": str(node.get("name") or ""), + "actions": list(node.get("actions") or []), + }) + for child in (node.get("children") or []): + _walk(child) + + _walk(tree) + return out + + +def _flatten_settled(ax, root_id, max_depth=12, timeout=6.0, interval=0.3): + """`_flatten`, but only after the subtree has stopped growing. + + A window enters the AX tree BEFORE it is fully built. Measured on the reference app: + the idle main window reads 13 nodes for the first ~0.5 s and then settles at 14, and + the About window reads 11 then settles at 12 (an unnamed AXGroup materialises in both + cases). A snapshot taken immediately therefore failed five of these tests on the + reference itself, intermittently. Poll until two consecutive reads agree; this only + decides WHEN the subtree is read, never what is asserted about it. + """ + last = _flatten(ax, root_id, max_depth) + deadline = time.time() + timeout + while time.time() < deadline: + time.sleep(interval) + cur = _flatten(ax, root_id, max_depth) + if len(cur) == len(last): + return cur + last = cur + return last + + +def _main_nodes(ax): + """Flattened main-window subtree (same scope as fh.scroll_area_widget_count).""" + win = fh.main_window(ax) + assert win is not None, "no main window exposed by the application in AX" + return _flatten_settled(ax, win.id) + + +def _roles(nodes): + return Counter(n["role"] for n in nodes) + + +def _names_of_role(nodes, role): + return {n["name"] for n in nodes if n["role"] == role} + + +def _windows(ax): + return ax.find(role="window", max_results=8, max_depth=1) + + +def _sheets(ax): + return ax.find(role="sheet", max_results=3, max_depth=3) + + +# ── GATE: the surfaces/widgets that must simply exist (jump_kind="none") ───── + +class TestStructureGate: + """Existence gate — kept to 3 tests; role diversity + interactive widget + counts are folded in rather than filed as extra weak tests.""" + + @pytest.mark.rb(depth=0, jump_kind="none") + def test_gate_main_window_and_named_children(self, ax): + """One AXStandardWindow "Window" holding Open.../Verify/Clear/Uppercase, + one progress, one label, one scroll_area with exactly one text_area.""" + fh.activate(ax) + fh.reset_app(ax) + + wins = _windows(ax) + assert len(wins) == 1, ( + "expected exactly one top-level window at idle, got %d: %r" + % (len(wins), [w.name for w in wins])) + + win = fh.main_window(ax) + assert win is not None, "fHash exposes no main window through AX" + assert fh.attr(ax, win, "AXTitle", "") == "Window", ( + "main window AXTitle should be 'Window', got %r" + % fh.attr(ax, win, "AXTitle", "")) + assert fh.attr(ax, win, "AXSubrole", "") == "AXStandardWindow", ( + "main window AXSubrole should be 'AXStandardWindow', got %r" + % fh.attr(ax, win, "AXSubrole", "")) + assert bool(fh.attr(ax, win, "AXMain", False)) is True, \ + "main window AXMain should be True" + + nodes = _main_nodes(ax) + counts = _roles(nodes) + assert len(nodes) == IDLE_NODES, ( + "idle main-window subtree should hold %d nodes, got %d (%r)" + % (IDLE_NODES, len(nodes), dict(counts))) + + # named children, located by role + visible label (never by index) + btn_names = _names_of_role(nodes, "button") + for title in ("Open...", "Verify", "Clear"): + assert title in btn_names, ( + "missing button %r in the main window; buttons found: %r" + % (title, sorted(btn_names))) + assert fh.open_button(ax) is not None, "Open... button not reachable" + assert fh.verify_button(ax) is not None, "Verify button not reachable" + assert fh.clear_button(ax) is not None, "Clear button not reachable" + + assert "Uppercase" in _names_of_role(nodes, "checkbox"), ( + "missing checkbox 'Uppercase'; checkboxes found: %r" + % sorted(_names_of_role(nodes, "checkbox"))) + assert counts.get("progress", 0) == 1, \ + "expected exactly one progress indicator, got %d" % counts.get("progress", 0) + assert counts.get("label", 0) == 1, \ + "expected exactly one label (the speed field), got %d" % counts.get("label", 0) + assert counts.get("scroll_area", 0) == 1, \ + "expected exactly one scroll_area, got %d" % counts.get("scroll_area", 0) + + scroll_areas = ax.find(role="scroll_area", root_id=win.id, max_results=5) + assert len(scroll_areas) == 1, \ + "expected one scroll_area under the window, got %d" % len(scroll_areas) + inner = ax.find(role="text_area", root_id=scroll_areas[0].id, max_results=5) + assert len(inner) == 1, ( + "the scroll_area should hold exactly one text_area, got %d" % len(inner)) + + # role diversity (recon idle census has 8 distinct roles) + assert IDLE_ROLES.issubset(set(counts)), ( + "missing structural roles %r; roles present: %r" + % (sorted(IDLE_ROLES - set(counts)), dict(counts))) + assert len(counts) >= 7, ( + "main window should expose >=7 distinct AX roles, got %d (%r)" + % (len(counts), dict(counts))) + assert counts.get("button", 0) == 6, ( + "idle window should expose 6 buttons (3 app + 3 window buttons), got %d" + % counts.get("button", 0)) + + fh.screenshot_assert( + "structure_main_window_idle", + "The fHash main window is on screen: a large text area fills the top and " + "shows the placeholder text 'Drag files here or click open to start " + "calculate.', a thin horizontal progress bar sits directly under it, and " + "the bottom row has an 'Uppercase' checkbox on the left with three buttons " + "on the right labelled 'Clear', 'Verify' and 'Open...' (Open... is drawn as " + "the highlighted default button).") + + @pytest.mark.rb(depth=0, jump_kind="none") + def test_gate_menu_bar_titles(self, ax): + """The app menu bar exposes exactly fHash/File/Edit/Window/Help (Apple excluded) + and every one of those menus is populated.""" + fh.activate(ax) + fh.reset_app(ax) + + bars = ax.find(role="menu_bar", max_results=2, max_depth=1) + assert len(bars) >= 1, "the application exposes no AXMenuBar" + + titles = fh.menu_titles(ax) + assert titles == MENU_TITLES, ( + "app menu-bar titles should be %r, got %r" % (MENU_TITLES, titles)) + + for title in MENU_TITLES: + assert fh.menu_bar_item(ax, title) is not None, \ + "menu bar item %r not reachable" % title + items = fh.menu_item_names(ax, title, max_depth=2) + assert len(items) >= 1, "menu %r exposes no menu items" % title + + @pytest.mark.rb(depth=0, jump_kind="none") + def test_gate_window_buttons_and_interactive_widgets(self, ax): + """Window buttons by AXSubrole (close enabled / zoom DISABLED / minimize + enabled), AXDefaultButton set, and the interactive-widget census.""" + fh.activate(ax) + fh.reset_app(ax) + + win = fh.main_window(ax) + assert win is not None, "no main window exposed by the application in AX" + + subroles = {} + for btn in ax.find(role="button", root_id=win.id, max_results=30): + sub = fh.attr(ax, btn, "AXSubrole", "") or "" + if sub: + subroles[sub] = bool(fh.attr(ax, btn, "AXEnabled", True)) + + for sub in ("AXCloseButton", "AXZoomButton", "AXMinimizeButton"): + assert sub in subroles, ( + "window button %s missing; subroles found: %r" % (sub, sorted(subroles))) + assert subroles["AXCloseButton"] is True, "AXCloseButton should be enabled" + assert subroles["AXMinimizeButton"] is True, "AXMinimizeButton should be enabled" + assert subroles["AXZoomButton"] is False, ( + "AXZoomButton should be DISABLED on the fixed-size fHash window") + + default_btn = fh.attr(ax, win, "AXDefaultButton", None) + assert default_btn is not None, "the main window has no AXDefaultButton" + + # interactive widget census: 6 buttons + the Uppercase checkbox are pressable, + # and the text area / scroll area add their own actions on top. + nodes = _main_nodes(ax) + pressable = [n for n in nodes if "AXPress" in n["actions"]] + assert len(pressable) >= 7, ( + "expected >=7 AXPress-able widgets in the main window, got %d (%r)" + % (len(pressable), sorted(n["role"] + "|" + n["name"] for n in pressable))) + with_actions = [n for n in nodes if n["actions"]] + assert len(with_actions) >= 9, ( + "expected >=9 widgets exposing at least one AX action, got %d" + % len(with_actions)) + for title in ("Open...", "Verify", "Clear", "Uppercase"): + assert any(n["name"] == title and "AXPress" in n["actions"] for n in nodes), \ + "widget %r is missing or does not expose AXPress" % title + + +# ── SHAPE DELTAS S1..S8 (reach / transition, all with a mandatory expect=) ─── + +class TestStructureShapeDeltas: + """Every test proves a tree-shape change with exact before/after node counts and + restores the home surface afterwards.""" + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="S1+S2: Verify grows the main-window subtree 14 -> 21 " + "(text_field + group + 'find previous'/'find next'/'Done' " + "buttons appear); Done restores it to 14") + def test_find_bar_adds_and_removes_widgets(self, ax): + fh.activate(ax) + fh.reset_app(ax) + + before = fh.scroll_area_widget_count(ax) + assert before == IDLE_NODES, ( + "idle main-window subtree should be %d nodes, got %d" % (IDLE_NODES, before)) + assert fh.find_done_button(ax) is None, "the find bar is already open at idle" + + assert fh.rb_enter_find_bar(ax), "pressing Verify did not open the find bar" + after = fh.scroll_area_widget_count(ax) + + assert kit.rb_flip(before, after, + expect="find-bar widgets added to the main window"), \ + "the main-window subtree did not change when the find bar opened (%d)" % after + assert after == FIND_BAR_NODES, ( + "find bar open: expected %d nodes, got %d" % (FIND_BAR_NODES, after)) + + nodes = _main_nodes(ax) + btn_names = _names_of_role(nodes, "button") + for title in ("Done", "find next", "find previous"): + assert title in btn_names, ( + "find bar button %r missing; buttons: %r" % (title, sorted(btn_names))) + assert _roles(nodes).get("text_field", 0) >= 1, \ + "the find bar exposes no search text_field" + assert fh.find_search_field(ax) is not None, "find search field not reachable" + + fh.screenshot_assert( + "structure_find_bar", + "The fHash main window now shows the text finder bar across the top of the " + "result text area: a rounded search field on the left, small up/down " + "(previous/next) chevron buttons next to it and a 'Done' button at the right " + "end; the placeholder text 'Drag files here or click open to start calculate.' " + "is still visible below the bar and the 'Uppercase' checkbox with the Clear / " + "Verify / Open... buttons remain along the bottom.") + + assert fh.close_find_bar(ax), "pressing Done did not close the find bar" + restored = fh.scroll_area_widget_count(ax) + assert restored == IDLE_NODES, ( + "after Done the subtree should be back to %d nodes, got %d" + % (IDLE_NODES, restored)) + assert fh.find_done_button(ax) is None, "the find bar survived Done" + + @pytest.mark.rb(depth=0, jump_kind="transition", + expect="S3+S4: hashing hello.txt grows the main-window subtree " + "14 -> 24 and adds exactly 4 role='link' nodes (the hash " + "strings); Clear takes it back to 14 nodes and 0 links") + def test_hash_results_add_link_nodes(self, ax): + fh.activate(ax) + fh.reset_app(ax) + + before_nodes = _main_nodes(ax) + before = len(before_nodes) + assert before == IDLE_NODES, ( + "idle main-window subtree should be %d nodes, got %d" % (IDLE_NODES, before)) + assert _roles(before_nodes).get("link", 0) == 0, \ + "hash hyperlinks are present before anything was hashed" + + txt = fh.feed_files(ax, [fh.fixture("hello.txt")]) + assert "SHA512:" in txt, ( + "the app produced no complete report block for hello.txt; text=%r" % txt[:200]) + + after_nodes = _main_nodes(ax) + after = len(after_nodes) + assert kit.rb_flip(before, after, + expect="hash links + scroller nodes added to the window"), \ + "the main-window subtree did not change after hashing a file (%d)" % after + assert after == ONE_FILE_NODES, ( + "after hashing one file the subtree should be %d nodes, got %d (%r)" + % (ONE_FILE_NODES, after, dict(_roles(after_nodes)))) + + links = [n for n in after_nodes if n["role"] == "link"] + assert len(links) == 4, ( + "expected exactly 4 hash hyperlinks (MD5/SHA1/SHA256/SHA512), got %d: %r" + % (len(links), [n["name"] for n in links])) + assert {len(n["name"]) for n in links} == HASH_LENGTHS, ( + "the 4 link titles should be the 32/40/64/128-char hash strings, got %r" + % sorted(len(n["name"]) for n in links)) + + assert fh.clear_results(ax), "Clear did not restore the initial prompt" + restored_nodes = _main_nodes(ax) + assert len(restored_nodes) == IDLE_NODES, ( + "after Clear the subtree should be back to %d nodes, got %d" + % (IDLE_NODES, len(restored_nodes))) + assert _roles(restored_nodes).get("link", 0) == 0, \ + "hash hyperlinks survived Clear" + + @pytest.mark.rb(depth=0, jump_kind="transition", + expect="role census: idle window has no link/scroll_bar/" + "value_indicator; after hashing hello.txt all three appear " + "(link x4) and they disappear again on Clear") + def test_role_census_gains_link_scrollbar_indicator(self, ax): + fh.activate(ax) + fh.reset_app(ax) + + idle_counts = _roles(_main_nodes(ax)) + assert sum(idle_counts.values()) == IDLE_NODES, ( + "idle main-window subtree should be %d nodes, got %d" + % (IDLE_NODES, sum(idle_counts.values()))) + for role in sorted(HASH_ROLES): + assert idle_counts.get(role, 0) == 0, ( + "role %r should be absent at idle, found %d" % (role, idle_counts[role])) + + txt = fh.feed_files(ax, [fh.fixture("hello.txt")]) + assert "SHA512:" in txt, "no complete report block was produced for hello.txt" + + after_counts = _roles(_main_nodes(ax)) + assert kit.rb_flip(set(idle_counts), set(after_counts), + expect="link/scroll_bar/value_indicator roles appear"), \ + "the role census did not change after hashing (%r)" % dict(after_counts) + assert HASH_ROLES.issubset(set(after_counts)), ( + "missing roles %r after hashing; census: %r" + % (sorted(HASH_ROLES - set(after_counts)), dict(after_counts))) + assert after_counts.get("link", 0) == 4, \ + "expected 4 link nodes after hashing, got %d" % after_counts.get("link", 0) + assert after_counts.get("scroll_bar", 0) >= 1, "no scroll_bar after hashing" + assert after_counts.get("value_indicator", 0) >= 1, \ + "no value_indicator after hashing" + assert after_counts.get("button", 0) >= idle_counts.get("button", 0), \ + "the window lost buttons after hashing" + assert sum(after_counts.values()) == ONE_FILE_NODES, ( + "after hashing one file the subtree should be %d nodes, got %d" + % (ONE_FILE_NODES, sum(after_counts.values()))) + + assert fh.clear_results(ax), "Clear did not restore the initial prompt" + cleared = _roles(_main_nodes(ax)) + assert not (HASH_ROLES & set(cleared)), ( + "roles %r survived Clear" % sorted(HASH_ROLES & set(cleared))) + assert sum(cleared.values()) == IDLE_NODES, ( + "after Clear the subtree should be back to %d nodes, got %d" + % (IDLE_NODES, sum(cleared.values()))) + + @pytest.mark.rb(depth=1, jump_kind="reach", + expect="S5: pressing Open... makes a sheet named 'open' appear as a " + "child of the main window (Cancel / Open / New Folder buttons " + "+ sidebar), main-window subtree 14 -> >100 nodes") + def test_open_panel_sheet_reach(self, ax): + fh.activate(ax) + fh.reset_app(ax) + + assert not _sheets(ax), "a sheet is already present on the home surface" + idle = fh.scroll_area_widget_count(ax) + assert idle == IDLE_NODES, ( + "idle main-window subtree should be %d nodes, got %d" % (IDLE_NODES, idle)) + + before = kit.rb_showing(ax) + assert fh.rb_enter_open_panel(ax), \ + "pressing Open... did not bring up the file-chooser sheet" + after = kit.rb_showing(ax) + assert kit.rb_reach(before, after, target="sheet"), \ + "no sheet element appeared in the app's AX tree after pressing Open..." + + sheets = _sheets(ax) + assert len(sheets) == 1, "expected exactly one sheet, got %d" % len(sheets) + sheet_nodes = _flatten(ax, sheets[0].id) + btn_names = _names_of_role(sheet_nodes, "button") + for title in ("Cancel", "Open", "New Folder"): + assert title in btn_names, ( + "file-chooser sheet is missing button %r; buttons: %r" + % (title, sorted(n for n in btn_names if n))) + assert any(n["role"] in ("browser", "outline") for n in sheet_nodes), ( + "the sheet exposes neither a browser (column view) nor an outline (sidebar); " + "roles: %r" % dict(_roles(sheet_nodes))) + assert any("sidebar" in n["name"].lower() for n in sheet_nodes) or \ + any(n["role"] == "outline" for n in sheet_nodes), \ + "the file-chooser sheet exposes no sidebar" + + opened = fh.scroll_area_widget_count(ax) + assert opened > SHEET_NODES_MIN, ( + "with the open panel up the main-window subtree should exceed %d nodes, got %d" + % (SHEET_NODES_MIN, opened)) + assert len(_windows(ax)) == 1, \ + "the file chooser should be a sheet on the main window, not a new window" + + fh.screenshot_assert( + "structure_open_panel_sheet", + "A macOS open-file sheet has slid down over the fHash window: a " + "Favorites/Locations sidebar runs down the left side, a file browser column " + "view fills the middle, and 'New Folder', 'Cancel' and 'Open' buttons sit " + "along the bottom edge of the sheet; the fHash window is visible behind it.") + + assert fh.close_open_panel(ax), "the file-chooser sheet could not be cancelled" + + @pytest.mark.rb(depth=2, jump_kind="transition", + expect="S6: Cancel on the open sheet removes it — main-window " + "subtree drops from >100 back to exactly 14 nodes, still " + "exactly one window") + def test_open_panel_cancel_restores_shape(self, ax): + fh.activate(ax) + fh.reset_app(ax) + + idle = fh.scroll_area_widget_count(ax) + assert idle == IDLE_NODES, ( + "idle main-window subtree should be %d nodes, got %d" % (IDLE_NODES, idle)) + + assert fh.rb_enter_open_panel(ax), \ + "pressing Open... did not bring up the file-chooser sheet" + opened = fh.scroll_area_widget_count(ax) + assert opened > SHEET_NODES_MIN, ( + "with the open panel up the main-window subtree should exceed %d nodes, got %d" + % (SHEET_NODES_MIN, opened)) + + assert fh.close_open_panel(ax), "Cancel did not dismiss the file-chooser sheet" + closed = fh.scroll_area_widget_count(ax) + assert kit.rb_flip(opened, closed, + expect="sheet subtree removed from the main window"), \ + "the main-window subtree did not shrink after Cancel (%d)" % closed + assert closed == IDLE_NODES, ( + "after Cancel the subtree should be back to %d nodes, got %d" + % (IDLE_NODES, closed)) + assert not _sheets(ax), "the file-chooser sheet survived Cancel" + assert len(_windows(ax)) == 1, \ + "expected exactly one window after cancelling the sheet" + + @pytest.mark.rb(depth=1, jump_kind="reach", + expect="S7: fHash > About fHash opens a SECOND top-level window " + "titled 'About fHash' (11 nodes, button 'OK', link " + "'Hosted on GitHub'); window count 1 -> 2") + def test_about_window_reach(self, ax): + fh.activate(ax) + fh.reset_app(ax) + + assert len(_windows(ax)) == 1, "expected exactly one window on the home surface" + assert fh.about_window(ax) is None, "the About window is already open" + + before = kit.rb_showing(ax) + assert fh.rb_enter_about_window(ax), \ + "fHash > About fHash did not open the About window" + after = kit.rb_showing(ax) + assert kit.rb_reach(before, after, target="About fHash"), \ + "no 'About fHash' window element appeared in the app's AX tree" + + about = fh.about_window(ax) + assert about is not None, "the About window is not reachable" + assert (about.name or "") == "About fHash", ( + "the second window should be titled 'About fHash', got %r" % about.name) + assert len(_windows(ax)) == 2, ( + "expected 2 top-level windows with About open, got %d" % len(_windows(ax))) + + nodes = _flatten_settled(ax, about.id) + assert len(nodes) == ABOUT_NODES, ( + "the About window subtree should hold %d nodes, got %d (%r)" + % (ABOUT_NODES, len(nodes), dict(_roles(nodes)))) + assert "OK" in _names_of_role(nodes, "button"), ( + "the About window has no 'OK' button; buttons: %r" + % sorted(_names_of_role(nodes, "button"))) + assert any(n["role"] == "link" and n["name"] == "Hosted on GitHub" + for n in nodes), ( + "the About window has no link 'Hosted on GitHub'; links: %r" + % sorted(_names_of_role(nodes, "link"))) + assert _roles(nodes).get("image", 0) >= 1, \ + "the About window shows no app icon (image element)" + + fh.screenshot_assert( + "structure_about_window", + "A small 'About fHash' window is in front of the main fHash window: a large " + "red/dark app icon showing the Chinese character 希 on the left, the text " + "'fHash: Files Hash Calculator' with a version number, 'Copyright (C) 2007- " + "SUN Junwen.' and three implementation-copyright lines to its right, a blue " + "'Hosted on GitHub' link at the bottom-left and a blue default 'OK' button at " + "the bottom-right.") + + assert fh.close_about_window(ax), "the About window could not be closed" + + @pytest.mark.rb(depth=2, jump_kind="transition", + expect="S8: pressing OK in the About window closes it — top-level " + "window count 2 -> 1, main window still AXMain with 14 nodes") + def test_about_window_ok_restores_single_window(self, ax): + fh.activate(ax) + fh.reset_app(ax) + + assert fh.rb_enter_about_window(ax), \ + "fHash > About fHash did not open the About window" + with_about = len(_windows(ax)) + assert with_about == 2, ( + "expected 2 top-level windows with About open, got %d" % with_about) + + assert fh.close_about_window(ax), "pressing OK did not close the About window" + after = len(_windows(ax)) + assert kit.rb_flip(with_about, after, + expect="About window removed from the window list"), \ + "the window count did not change after pressing OK (%d)" % after + assert after == 1, "expected exactly 1 window after OK, got %d" % after + assert fh.about_window(ax) is None, "the About window survived OK" + + win = fh.main_window(ax) + assert win is not None, "the main window disappeared with the About window" + assert bool(fh.attr(ax, win, "AXMain", False)) is True, \ + "the main window is no longer AXMain after closing About" + assert fh.scroll_area_widget_count(ax) == IDLE_NODES, ( + "the main-window subtree should be back to %d nodes" % IDLE_NODES) diff --git a/macos/sunjw-fhash/tests/test_ax_text.py b/macos/sunjw-fhash/tests/test_ax_text.py new file mode 100644 index 0000000000000000000000000000000000000000..ef52f9ef079f71cea2841c98a274420f4b7245af --- /dev/null +++ b/macos/sunjw-fhash/tests/test_ax_text.py @@ -0,0 +1,614 @@ +"""AX TEXT tests for fHash (macOS). + +Every exact string asserted here was recorded from the running reference app in +recon.md `## TEXT` (plus `## AX_TREE` for the widget map and `## VISUAL` for the +screenshot descriptions). Nothing is read from the app source. + +Rules honoured by every test below: + * starts with `fh.activate(ax)` + `fh.reset_app(ax)` (clean idle home surface); + * any surface it opens (About window / menu) is closed again in `finally:`; + * machine/build dependent text (version number, Modified Date value, speed + magnitude) is NEVER asserted literally — only its shape; + * widgets are located by role + visible title through `fhash_helpers`, never by + child index or internal identifier. +""" + +import os +import sys +import time + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +import re # noqa: E402 + +import pytest # noqa: E402 + +import rb_testgen_kit as kit # noqa: E402 +import fhash_helpers as fh # noqa: E402 + +# ── Observed constants (recon ## TEXT) ─────────────────────────────────────── +INIT_VALUE = fh.INIT_TEXT + "\n\n" # X1 — exact AXValue of the result view +MAIN_WINDOW_TITLE = "Window" # X5 +ABOUT_TITLE = "About fHash" # X6 +GITHUB_TEXT = "Hosted on GitHub" # X8 +GITHUB_URL = "https://github.com/sunjw/fhash" +MENU_TITLES = ["fHash", "File", "Edit", "Window", "Help"] # X9 +REPORT_PREFIXES = ["Name: ", "File Size: ", "Modified Date: ", + "MD5: ", "SHA1: ", "SHA256: ", "SHA512: "] # X10 +SIZE_UNIT_WORD = "Byte(s)" +# X7 — About copyright block. The version string that follows +# "fHash: Files Hash Calculator " is build dependent and is never asserted. +ABOUT_SUBSTRINGS = [ + "fHash: Files Hash Calculator", + "Copyright (C) 2007- SUN Junwen.", + "MD5 implementation copyright (C) RSA Data Security, Inc.", + "SHA256 implementation copyright (C) Niels Moller", + "SHA512 implementation copyright (C) Aaron D. Gifford", +] +# X16 — speed label shape only (magnitude is machine dependent). +SPEED_RE = re.compile(r"^\d+\.\d{2} (B|KB|MB|GB)/s$") + + +# ── small local utilities (no AX element is ever str()'d) ──────────────────── + +def _home_window(ax): + """The always-present main window. + + recon `### REVEAL_STEPS` says fHash is a regular Dock app whose window is up + immediately, so this is normally a plain lookup. The guarded reveal keeps the + test honest for a recreation that needs one extra beat/reveal path. + """ + win = fh.main_window(ax) + if win is None: + try: + ax.ensure_ui_visible() + time.sleep(1.0) + except Exception: + pass + win = fh.main_window(ax) + assert win is not None, "no main window reachable through AX" + return win + + +def _fixture(name): + p = fh.fixture(name) + assert os.path.exists(p), "test fixture missing: %s" % p + return p + + +def _line(text, prefix): + """The first line of `text` starting with `prefix` ('' when absent).""" + for ln in (text or "").splitlines(): + if ln.startswith(prefix): + return ln + return "" + + +def _wait_until(pred, timeout=5.0, interval=0.2): + deadline = time.time() + timeout + while time.time() < deadline: + try: + if pred(): + return True + except Exception: + pass + time.sleep(interval) + try: + return bool(pred()) + except Exception: + return False + + +def _texts_in(ax, win, max_results=60): + """Every readable AXValue/AXTitle string inside a window subtree.""" + out = [] + for el in ax.find(root_id=win.id, max_results=max_results): + for a in ("AXValue", "AXTitle", "AXDescription"): + t = fh.attr(ax, el, a, "") + if isinstance(t, str) and t.strip(): + out.append(t) + return out + + +def rb_value_speed_shape(observed): + """VALUE verdict wrapper (X16): the speed label renders ` /s`.""" + return bool(SPEED_RE.match(str(observed or ""))) + + +def rb_value_report_prefixes(text, prefixes): + """VALUE verdict wrapper (X10): `text` contains `prefixes` as line starts, in order.""" + idx = 0 + for ln in (text or "").splitlines(): + if idx < len(prefixes) and ln.startswith(prefixes[idx]): + idx += 1 + return idx == len(prefixes) + + +def rb_enter_select_all(ax): + """Navigate Edit ▸ Select All (recon M6) — makes the whole report the + text view's AXSelectedText. Named rb_enter_* so the depth audit sees the nav.""" + item = (fh.menu_item(ax, "Edit", "Select All", exact=True) + or fh.menu_item(ax, "Edit", "Select All")) + if item is None: + return False + ax.action(item.id, "AXPress") + time.sleep(0.6) + return True + + +# ── X1, X2, X3, X4, X5 — static text of the home surface ───────────────────── + +class TestHomeSurfaceText: + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="result text view reads 'Drag files here or click open to " + "start calculate.\\n\\n' and the speed label reads ''") + def test_result_area_and_speed_label_initial_text(self, ax): + fh.activate(ax) + fh.reset_app(ax) + _home_window(ax) + + ta = fh.text_area(ax) + assert ta is not None, "result text_area not found in the main window" + txt = str(fh.attr(ax, ta, "AXValue", "") or "") + assert kit.rb_value(txt, INIT_VALUE), ( + "idle result text is %r, expected %r" % (txt, INIT_VALUE)) + assert txt == INIT_VALUE, "idle result text %r != %r" % (txt, INIT_VALUE) + # character count of the read value matches the string it reports + assert len(txt) == len(INIT_VALUE) == len(fh.INIT_TEXT) + 2 + + lbl = fh.speed_label(ax) + assert lbl is not None, "speed label (AXStaticText) not found" + speed = fh.attr(ax, lbl, "AXValue", None) + speed = "" if speed is None else str(speed) + assert kit.rb_value(speed, ""), "idle speed label is %r, expected ''" % speed + assert speed == "", "idle speed label is %r, expected ''" % speed + + fh.screenshot_assert( + "text_home_idle_prompt", + "The fHash window is idle: the large text area filling the top of the " + "window shows exactly one line of prompt text reading 'Drag files here " + "or click open to start calculate.' and nothing else; a thin empty " + "progress bar sits under it; the bottom row has an unticked 'Uppercase' " + "checkbox on the left, no speed value text next to it, and the three " + "buttons 'Clear', 'Verify' and 'Open...' on the right.") + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="button titles 'Open...', 'Verify', 'Clear'; checkbox " + "title 'Uppercase'; window AXTitle 'Window'") + def test_control_titles_and_window_title(self, ax): + fh.activate(ax) + fh.reset_app(ax) + win = _home_window(ax) + + wtitle = str(fh.attr(ax, win, "AXTitle", "") or "") + assert kit.rb_value(wtitle, MAIN_WINDOW_TITLE), ( + "main window AXTitle is %r, expected %r" % (wtitle, MAIN_WINDOW_TITLE)) + assert wtitle == MAIN_WINDOW_TITLE + + observed = {} + for getter, expected in ((fh.open_button, "Open..."), + (fh.verify_button, "Verify"), + (fh.clear_button, "Clear")): + el = getter(ax) + assert el is not None, "button %r not found in the main window" % expected + title = str(fh.attr(ax, el, "AXTitle", "") or "") + observed[expected] = title + assert kit.rb_value(title, expected), ( + "button title is %r, expected %r" % (title, expected)) + assert title == expected + + cb = fh.uppercase_checkbox(ax) + assert cb is not None, "Uppercase checkbox not found" + cb_title = str(fh.attr(ax, cb, "AXTitle", "") or "") + assert kit.rb_value(cb_title, "Uppercase"), ( + "checkbox title is %r, expected 'Uppercase'" % cb_title) + assert cb_title == "Uppercase" + + # census: every labelled control on the home surface carries readable text + labelled = list(observed.values()) + [cb_title, wtitle] + assert all(t.strip() for t in labelled), ( + "some home-surface control has empty text: %r" % (labelled,)) + assert len(labelled) == 5 + + +# ── X6, X7, X8 — About window text (depth 1) ───────────────────────────────── + +class TestAboutWindowText: + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="About window titled 'About fHash' whose copyright label " + "contains 'fHash: Files Hash Calculator' and " + "'Copyright (C) 2007- SUN Junwen.'") + def test_about_window_title_and_copyright_lines(self, ax): + fh.activate(ax) + fh.reset_app(ax) + _home_window(ax) + try: + assert fh.rb_enter_about_window(ax), "fHash ▸ About fHash did not open" + win = fh.about_window(ax) + assert win is not None, "About window not reachable after opening it" + + title = str(fh.attr(ax, win, "AXTitle", "") or "") + assert kit.rb_value(title, ABOUT_TITLE), ( + "About window AXTitle is %r, expected %r" % (title, ABOUT_TITLE)) + assert title == ABOUT_TITLE + + texts = _texts_in(ax, win) + blob = "\n".join(texts) + for needle in ABOUT_SUBSTRINGS: + assert kit.rb_value(blob, needle), ( + "About text is missing %r; text read was: %r" % (needle, texts)) + + # the copyright block is one static-text label (recon S7) + copyright_label = "" + for t in texts: + if "Copyright (C) 2007- SUN Junwen." in t and len(t) > len(copyright_label): + copyright_label = t + assert copyright_label, ( + "no single About label carries the copyright block; read: %r" % (texts,)) + assert kit.rb_value(copyright_label, "fHash: Files Hash Calculator") + + fh.screenshot_assert( + "text_about_window", + "A small window titled 'About fHash' is in front of the main fHash " + "window. It shows a large dark red app icon bearing the Chinese " + "character 希 on the left, and to its right the text lines " + "'fHash: Files Hash Calculator' followed by a version number, " + "'Copyright (C) 2007- SUN Junwen.' and three implementation " + "copyright lines mentioning RSA Data Security, Niels Moller and " + "Aaron D. Gifford; a blue 'Hosted on GitHub' hyperlink sits at the " + "bottom-left and a blue default 'OK' button at the bottom-right.") + finally: + fh.close_about_window(ax) + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="About window exposes the text 'Hosted on GitHub' and a " + "link whose AXURL is https://github.com/sunjw/fhash") + def test_about_github_link_text_and_url(self, ax): + fh.activate(ax) + fh.reset_app(ax) + _home_window(ax) + try: + assert fh.rb_enter_about_window(ax), "fHash ▸ About fHash did not open" + win = fh.about_window(ax) + assert win is not None, "About window not reachable after opening it" + + texts = _texts_in(ax, win) + assert kit.rb_value("\n".join(texts), GITHUB_TEXT), ( + "About window does not expose the text %r; read: %r" + % (GITHUB_TEXT, texts)) + + links = ax.find(role="link", root_id=win.id, max_results=10) + if not links: + links = ax.find(role="link", name=GITHUB_TEXT, max_results=10) + assert links, "no role=link element inside the About window" + + urls = [] + for ln in links: + u = fh.attr(ax, ln, "AXURL", "") + if u: + urls.append(str(u)) + assert urls, "the About window link exposes no AXURL" + matching = [u for u in urls if kit.rb_value(u, GITHUB_URL)] + assert matching, "link AXURL(s) %r do not contain %r" % (urls, GITHUB_URL) + assert kit.rb_value(matching[0], GITHUB_URL) + # the link is never pressed — it would open a browser (recon ## UNREACHED) + finally: + fh.close_about_window(ax) + + +# ── X9 — menu bar titles ───────────────────────────────────────────────────── + +class TestMenuBarText: + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="app menu bar titles are ['fHash','File','Edit','Window','Help']") + def test_menu_bar_titles(self, ax): + fh.activate(ax) + fh.reset_app(ax) + _home_window(ax) + + titles = fh.menu_titles(ax) + assert kit.rb_value(titles, MENU_TITLES), ( + "menu bar titles are %r, expected %r" % (titles, MENU_TITLES)) + assert titles == MENU_TITLES + assert all(t.strip() for t in titles), "a menu bar item has an empty title" + + +# ── X10 – X16, X18 — the report text ───────────────────────────────────────── + +class TestReportText: + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="report lines start with Name:/File Size:/Modified Date:/" + "MD5:/SHA1:/SHA256:/SHA512: and the size line says 'Byte(s)'") + def test_report_line_prefixes(self, ax): + fh.activate(ax) + fh.reset_app(ax) + _home_window(ax) + + p = _fixture("hello.txt") + txt = fh.feed_files(ax, [p]) + assert txt and txt != INIT_VALUE, "feeding hello.txt produced no report text" + + assert rb_value_report_prefixes(txt, REPORT_PREFIXES), ( + "report does not carry the 7 line prefixes in order; text was: %r" % txt) + for prefix in REPORT_PREFIXES: + assert kit.rb_value(txt, prefix), "report is missing a %r line" % prefix + + size_line = _line(txt, "File Size: ") + assert kit.rb_value(size_line, SIZE_UNIT_WORD), ( + "size line %r does not use the unit word %r" % (size_line, SIZE_UNIT_WORD)) + + # the Modified Date value is machine dependent: only its shape is asserted + modified = _line(txt, "Modified Date: ")[len("Modified Date: "):] + assert re.match(r"^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$", modified), ( + "Modified Date %r does not match YYYY-MM-DD HH:MM" % modified) + + fh.screenshot_assert( + "text_report_hello_txt", + "The fHash text area now shows a seven-line report for hello.txt: " + "'Name: ' with the full file path, 'File Size: 5 Byte(s)', " + "'Modified Date: ' with a date and time, then the four lines 'MD5:', " + "'SHA1:', 'SHA256:' and 'SHA512:' whose long hexadecimal values are " + "rendered as blue/accent-coloured hyperlink text; a speed value such as " + "'87.00 B/s' appears in the bottom row left of the 'Clear' button and " + "the progress bar under the text area is full.") + + @pytest.mark.rb(depth=0, jump_kind="transition", + expect="init prompt → 7-line report for hello.txt") + def test_feeding_file_replaces_prompt_with_report(self, ax): + fh.activate(ax) + fh.reset_app(ax) + _home_window(ax) + + p = _fixture("hello.txt") + before = fh.result_text(ax) + assert before.rstrip("\n") == fh.INIT_TEXT, ( + "idle text before feeding is %r, expected the init prompt" % before) + + after = fh.feed_files(ax, [p]) + assert kit.rb_flip(before, after, + expect="init prompt replaced by the hello.txt report"), ( + "result text did not change when hello.txt was fed (%r)" % after) + + expected_md5_line = "MD5: " + fh.expected_hash(p, "MD5") + assert kit.rb_value(after, expected_md5_line), ( + "report does not contain %r; text was %r" % (expected_md5_line, after)) + assert fh.INIT_TEXT not in after, ( + "the init prompt is still shown next to the report: %r" % after) + + blocks = fh.parse_blocks(after) + assert len(blocks) == 1, "expected exactly 1 report block, got %d" % len(blocks) + assert blocks[0].get("size_bytes") == 5, ( + "File Size line reports %r bytes, expected 5" % blocks[0].get("size_bytes")) + + @pytest.mark.rb(depth=0, jump_kind="transition", + expect="report → exactly 'Drag files here or click open to start " + "calculate.\\n\\n' after Clear") + def test_clear_restores_init_prompt_exactly(self, ax): + fh.activate(ax) + fh.reset_app(ax) + _home_window(ax) + + p = _fixture("hello.txt") + before = fh.feed_files(ax, [p]) + assert kit.rb_value(before, "MD5: "), ( + "no report on screen before pressing Clear: %r" % before) + + assert fh.clear_results(ax), "Clear did not bring the init prompt back" + after = fh.result_text(ax) + assert kit.rb_flip(before, after, expect="report cleared back to the prompt"), ( + "Clear left the text unchanged: %r" % after) + assert kit.rb_value(after, INIT_VALUE) + assert after == INIT_VALUE, "after Clear the text is %r, expected %r" % ( + after, INIT_VALUE) + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="Uppercase rewrites 'MD5: ' to upper case while the " + "Name/File Size/Modified Date lines stay byte-identical") + def test_uppercase_rewrites_only_hash_characters(self, ax): + fh.activate(ax) + fh.reset_app(ax) + _home_window(ax) + + p = _fixture("hello.txt") + txt = fh.feed_files(ax, [p]) + low = fh.expected_hash(p, "MD5") + name_line = _line(txt, "Name: ") + size_line = _line(txt, "File Size: ") + date_line = _line(txt, "Modified Date: ") + assert name_line and size_line and date_line, ( + "report is incomplete before toggling Uppercase: %r" % txt) + assert kit.rb_value(_line(txt, "MD5: "), "MD5: " + low) + + assert fh.set_uppercase(ax, True), "could not tick the Uppercase checkbox" + upper_line = "MD5: " + low.upper() + _wait_until(lambda: _line(fh.result_text(ax), "MD5: ") == upper_line, timeout=4.0) + up_txt = fh.result_text(ax) + + assert kit.rb_value(_line(up_txt, "MD5: "), upper_line), ( + "MD5 line is %r, expected %r" % (_line(up_txt, "MD5: "), upper_line)) + assert _line(up_txt, "Name: ") == name_line, "the Name line changed with Uppercase" + assert _line(up_txt, "File Size: ") == size_line, ( + "the File Size line changed with Uppercase") + assert _line(up_txt, "Modified Date: ") == date_line, ( + "the Modified Date line changed with Uppercase") + + assert fh.set_uppercase(ax, False), "could not untick the Uppercase checkbox" + lower_line = "MD5: " + low + _wait_until(lambda: _line(fh.result_text(ax), "MD5: ") == lower_line, timeout=4.0) + back_txt = fh.result_text(ax) + assert kit.rb_value(_line(back_txt, "MD5: "), lower_line), ( + "MD5 line is %r after unticking, expected %r" + % (_line(back_txt, "MD5: "), lower_line)) + assert _line(back_txt, "Name: ") == name_line + + @pytest.mark.rb(depth=0, jump_kind="transition", + expect="1 report block → 2 report blocks, the first block preserved") + def test_second_file_appends_second_block(self, ax): + fh.activate(ax) + fh.reset_app(ax) + _home_window(ax) + + first = _fixture("hello.txt") + second = _fixture("fox.txt") + + txt1 = fh.feed_files(ax, [first]) + blocks1 = fh.parse_blocks(txt1) + assert len(blocks1) == 1, "expected 1 block after the first file" + + txt2 = fh.feed_files(ax, [second]) + blocks2 = fh.parse_blocks(txt2) + assert kit.rb_flip(len(blocks1), len(blocks2), + expect="a second report block was appended"), ( + "feeding a second file did not append a block (still %d)" % len(blocks2)) + assert len(blocks2) == 2, "expected 2 blocks, got %d" % len(blocks2) + + assert blocks2[0] == blocks1[0], ( + "the first report block changed when the second file was added") + assert kit.rb_value(blocks2[0].get("MD5", ""), fh.expected_hash(first, "MD5")) + assert kit.rb_value(blocks2[1].get("MD5", ""), fh.expected_hash(second, "MD5")) + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="speed label text matches '. B|KB|MB|GB/s' after " + "hashing mb1.bin") + def test_speed_label_shape_after_hashing_mb1(self, ax): + fh.activate(ax) + fh.reset_app(ax) + _home_window(ax) + + lbl = fh.speed_label(ax) + assert lbl is not None, "speed label not found" + assert str(fh.attr(ax, lbl, "AXValue", "") or "") == "", ( + "speed label is not empty at idle") + + p = _fixture("mb1.bin") + fh.feed_files(ax, [p]) + _wait_until(lambda: rb_value_speed_shape( + fh.attr(ax, fh.speed_label(ax), "AXValue", "")), timeout=5.0) + + speed = str(fh.attr(ax, fh.speed_label(ax), "AXValue", "") or "") + # only the SHAPE is asserted — the magnitude is machine dependent + assert rb_value_speed_shape(speed), ( + "speed label reads %r, expected '. B|KB|MB|GB/s'" % speed) + assert kit.rb_value(speed[-2:], "/s") + + @pytest.mark.rb(depth=0, jump_kind="transition", + expect="Stop mid-calculation leaves Name:/File Size:/Modified Date: " + "with no MD5: line") + def test_stop_leaves_partial_report_text(self, ax, tmp_path): + fh.activate(ax) + fh.reset_app(ax) + _home_window(ax) + + before = fh.result_text(ax) + big = fh.make_big_file(tmp_path, 1500) # 400 MB hashes faster than the Stop-title poll on a quick + # disk (measured: the title flip was never observed); give the abort a + # comfortable window instead of relaxing the assertions. + if not fh._deliver_via_workspace(ax, [big]): + fh._deliver_via_appleevent(ax, [big]) + + stop_btn = None + deadline = time.time() + 12.0 + while time.time() < deadline: + b = fh.open_button(ax) + if b is not None and str(fh.attr(ax, b, "AXTitle", "") or "") == fh.STOP_TITLE: + stop_btn = b + break + time.sleep(0.05) + assert stop_btn is not None, ( + "the Open... button never showed the 'Stop' title while hashing 400 MB") + + ax.action(stop_btn.id, "AXPress") + fh.wait_for_idle(ax, timeout=20) + time.sleep(0.5) + after = fh.result_text(ax) + + assert kit.rb_flip(before, after, + expect="init prompt replaced by a partial report"), ( + "stopping mid-calculation left the text unchanged: %r" % after) + assert kit.rb_value(after, "Name: "), "partial report has no Name: line: %r" % after + assert kit.rb_value(after, "File Size: "), ( + "partial report has no File Size: line: %r" % after) + assert "MD5: " not in after, ( + "a stopped calculation still produced an MD5: line: %r" % after) + + +# ── X17 — Edit ▸ Select All exposes the report as selected text (depth 1) ──── + +class TestSelectedText: + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="text_area AXSelectedText equals the whole report and " + "starts with a 'Name: ' line") + def test_select_all_exposes_whole_report(self, ax): + fh.activate(ax) + fh.reset_app(ax) + _home_window(ax) + + p = _fixture("hello.txt") + txt = fh.feed_files(ax, [p]) + assert kit.rb_value(txt, "MD5: "), "no report to select: %r" % txt + + ta = fh.text_area(ax) + assert ta is not None, "result text_area not found" + assert str(fh.attr(ax, ta, "AXSelectedText", "") or "") == "", ( + "the result view already has a selection before Select All") + + try: + assert rb_enter_select_all(ax), "Edit ▸ Select All is not reachable" + _wait_until( + lambda: str(fh.attr(ax, fh.text_area(ax), "AXSelectedText", "") or ""), + timeout=4.0) + sel = str(fh.attr(ax, fh.text_area(ax), "AXSelectedText", "") or "") + full = fh.result_text(ax) + + assert kit.rb_value(sel, "Name: "), ( + "selected text does not contain a 'Name: ' line: %r" % sel) + assert kit.rb_value(sel, full), ( + "selected text (%d chars) is not the whole report (%d chars)" + % (len(sel), len(full))) + assert sel == full, ( + "AXSelectedText != the report text (%d vs %d chars)" % (len(sel), len(full))) + assert kit.rb_value(sel, "MD5: " + fh.expected_hash(p, "MD5")) + finally: + fh.dismiss_menu(ax) + + +# ── X19 — the hash text is really laid out in the view ─────────────────────── + +class TestTextGeometry: + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="text_area exposes AXBoundsForRange and the MD5 hash range " + "has a rect with positive width and height") + def test_text_area_bounds_for_hash_range(self, ax): + fh.activate(ax) + fh.reset_app(ax) + _home_window(ax) + + p = _fixture("hello.txt") + txt = fh.feed_files(ax, [p]) + assert kit.rb_value(txt, "MD5: "), "no report rendered: %r" % txt + + ta = fh.text_area(ax) + assert ta is not None, "result text_area not found" + pnames = list(ax.parameterized_attribute_names(ta.id) or []) + assert kit.rb_value(pnames, "AXBoundsForRange"), ( + "the result text view does not expose AXBoundsForRange; it exposes %r" + % (pnames,)) + + box = fh.hash_link_bounds(ax, "MD5") + assert box is not None, ( + "AXBoundsForRange returned no rect for the MD5 hash range") + x, y, w, h = box + assert w > 0 and h > 0, ( + "MD5 hash range rect has non-positive size: w=%s h=%s" % (w, h)) + # the rect must sit inside the text view's own frame + size = fh.attr(ax, ta, "AXSize", None) + if isinstance(size, dict): + assert w <= float(size.get("width", w)) + 1.0, ( + "hash rect (w=%s) is wider than the text view (%s)" % (w, size)) + assert kit.rb_value(w > 0 and h > 0, True) diff --git a/macos/sunjw-fhash/tests/testcase_counts.json b/macos/sunjw-fhash/tests/testcase_counts.json new file mode 100644 index 0000000000000000000000000000000000000000..a32a28e9957d62cf7941f6150c3024816037b364 --- /dev/null +++ b/macos/sunjw-fhash/tests/testcase_counts.json @@ -0,0 +1,39 @@ +{ + "ax_total": 83, + "vlm_total": 16, + "ax_by_lane": { + "test_ax_buttons.py": 13, + "test_ax_computation.py": 18, + "test_ax_menus.py": 13, + "test_ax_states.py": 15, + "test_ax_structure.py": 10, + "test_ax_text.py": 14 + }, + "vlm_by_dir": { + "buttons": 3, + "computation": 2, + "menus": 3, + "states": 3, + "structure": 2, + "text": 3 + }, + "vlm_names": [ + "buttons_calculating_stop.png", + "buttons_hash_context_menu.png", + "buttons_open_panel.png", + "computation_hash_report_fox.png", + "computation_uppercase_report.png", + "menus_about_window.png", + "menus_hash_context_menu.png", + "menus_open_panel_sheet.png", + "states_calculating_disabled.png", + "states_find_bar_widgets.png", + "states_uppercase_checked.png", + "structure_about_window.png", + "structure_main_window_idle.png", + "text_about_window.png", + "text_home_idle_prompt.png", + "text_report_hello_txt.png" + ], + "frozen_at": "stage2_finalize" +} \ No newline at end of file diff --git a/macos/sunjw-fhash/tests/verifier_helpers.py b/macos/sunjw-fhash/tests/verifier_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..ce369cdae8db3a7427890d1636f8f5a3201dbef1 --- /dev/null +++ b/macos/sunjw-fhash/tests/verifier_helpers.py @@ -0,0 +1,753 @@ +""" +verifier_helpers.py — High-level AX testing patterns for macOS app verification. + +v6 core library. Encodes all robust testing patterns as reusable functions +so verifier agents call high-level APIs instead of building from scratch. + +Depends on: ax_helpers.py (AXHelper class) +""" + +import datetime +import os +import re +import signal +import subprocess +import time +from collections import Counter + +# --------------------------------------------------------------------------- +# Key codes (macOS virtual key codes) +# --------------------------------------------------------------------------- +KC_LEFT_ARROW = 123 +KC_RIGHT_ARROW = 124 +KC_UP_ARROW = 126 +KC_DOWN_ARROW = 125 +KC_SPACE = 49 +KC_RETURN = 36 +KC_TAB = 48 +KC_ESCAPE = 53 +KC_Q = 12 +KC_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": , "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)" + ) diff --git a/macos/sunjw-fhash/vlm_assertions.json b/macos/sunjw-fhash/vlm_assertions.json new file mode 100644 index 0000000000000000000000000000000000000000..ad6404ddef7071982de6d7cb89e8b6a820854ce7 --- /dev/null +++ b/macos/sunjw-fhash/vlm_assertions.json @@ -0,0 +1,231 @@ +{ + "schema_version": 2, + "instance_id": "macos/sunjw-fhash", + "grading": { + "mode": "deferred", + "model": null, + "scored_separately": true + }, + "totals": { + "assertions": 16, + "with_verdict": 0, + "calibrated": 0, + "usable": null, + "scored_records": 0, + "unbacked_records": 0 + }, + "assertions": [ + { + "id": "buttons_open_panel.png", + "screenshot": "buttons_open_panel.png", + "assertion": "A macOS open-file sheet is slid down over the small fHash window. The sheet shows a Favorites/Locations sidebar on the left, a file browser column view, a 'Where:' popup, and 'New Folder', 'Cancel' and 'Open' buttons along its bottom edge.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "buttons_open_panel.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "buttons_calculating_stop.png", + "screenshot": "buttons_calculating_stop.png", + "assertion": "fHash is mid-calculation: the bottom-right button that normally reads 'Open...' now reads 'Stop', the 'Clear' and 'Verify' buttons and the 'Uppercase' checkbox are greyed out, and the thin horizontal progress bar under the text area is partially filled.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "buttons_calculating_stop.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "buttons_hash_context_menu.png", + "screenshot": "buttons_hash_context_menu.png", + "assertion": "A small pop-up context menu is open over the fHash result text, on top of the blue hyperlink-styled hash values. It lists 'Copy hash value', then a separator, then 'Search Google' and 'Search VirusTotal'.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "buttons_hash_context_menu.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "computation_hash_report_fox.png", + "screenshot": "computation_hash_report_fox.png", + "assertion": "The fHash window shows a completed hash report for fox.txt: a line 'Name: .../fox.txt', a line 'File Size: 43 Byte(s)' with no short-size parenthetical, a 'Modified Date:' line, and four lines labelled 'MD5:', 'SHA1:', 'SHA256:' and 'SHA512:' whose long hexadecimal values are drawn as blue/accent-coloured hyperlink text. A speed value such as '87.00 B/s' sits to the left of the Clear button; the 'Uppercase' checkbox at the bottom-left is unticked and all hex digits are lowercase.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "computation_hash_report_fox.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "computation_uppercase_report.png", + "screenshot": "computation_uppercase_report.png", + "assertion": "The fHash window shows the hello.txt hash report with the 'Uppercase' checkbox at the bottom-left TICKED, and every hexadecimal digest value on the MD5, SHA1, SHA256 and SHA512 lines rendered in UPPERCASE hex (e.g. MD5: 5D41402ABC4B2A76B9719D911017C592). The 'Name:', 'File Size: 5 Byte(s)' and 'Modified Date:' lines are unchanged and the hash values are still drawn as blue hyperlink text.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "computation_uppercase_report.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "menus_about_window.png", + "screenshot": "menus_about_window.png", + "assertion": "A small 'About fHash' window sits in front of the main fHash window: a large red/dark app icon showing the Chinese character 希 on the left, the text 'fHash: Files Hash Calculator' with a version number, 'Copyright (C) 2007- SUN Junwen.' and three implementation-copyright lines, a blue 'Hosted on GitHub' link at the bottom-left and a blue default 'OK' button at the bottom-right.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "menus_about_window.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "menus_open_panel_sheet.png", + "screenshot": "menus_open_panel_sheet.png", + "assertion": "A macOS open-file sheet is slid down over the small fHash window: a Favorites/Locations sidebar on the left, a file browser column view in the middle, a 'Where:' popup and 'New Folder', 'Cancel' and 'Open' buttons along the bottom of the sheet.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "menus_open_panel_sheet.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "menus_hash_context_menu.png", + "screenshot": "menus_hash_context_menu.png", + "assertion": "A small pop-up menu is open over the result text of the fHash window listing 'Copy hash value', then a separator, then 'Search Google' and 'Search VirusTotal'; behind it the text area shows the fox.txt report whose MD5/SHA1/SHA256/SHA512 values are rendered as blue hyperlink text.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "menus_hash_context_menu.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "states_uppercase_checked.png", + "screenshot": "states_uppercase_checked.png", + "assertion": "The fHash window shows the hash report for hello.txt and every hash value on the MD5, SHA1, SHA256 and SHA512 lines is rendered in UPPERCASE hexadecimal; the 'Uppercase' checkbox at the bottom-left of the window is ticked. The 'Clear', 'Verify' and 'Open...' buttons stay enabled.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "states_uppercase_checked.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "states_calculating_disabled.png", + "screenshot": "states_calculating_disabled.png", + "assertion": "The fHash window is mid-calculation: the bottom-right button reads 'Stop' instead of 'Open...', the 'Clear' and 'Verify' buttons and the 'Uppercase' checkbox at the bottom-left are greyed out (disabled), and the thin horizontal progress bar under the text area is partially filled.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "states_calculating_disabled.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "states_find_bar_widgets.png", + "screenshot": "states_find_bar_widgets.png", + "assertion": "A search bar is shown at the top of the fHash result text area: a rounded search field containing the text '5d41402a', small up and down chevron buttons (find previous / find next) and an enabled 'Done' button on its right. The 'Uppercase' checkbox and the 'Clear', 'Verify', 'Open...' buttons are still visible along the bottom row.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "states_find_bar_widgets.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "structure_main_window_idle.png", + "screenshot": "structure_main_window_idle.png", + "assertion": "The fHash main window is on screen: a large text area fills the top and shows the placeholder text 'Drag files here or click open to start calculate.', a thin horizontal progress bar sits directly under it, and the bottom row has an 'Uppercase' checkbox on the left with three buttons on the right labelled 'Clear', 'Verify' and 'Open...' (Open... is drawn as the highlighted default button).", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "structure_main_window_idle.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "structure_about_window.png", + "screenshot": "structure_about_window.png", + "assertion": "A small 'About fHash' window is in front of the main fHash window: a large red/dark app icon showing the Chinese character 希 on the left, the text 'fHash: Files Hash Calculator' with a version number, 'Copyright (C) 2007- SUN Junwen.' and three implementation-copyright lines to its right, a blue 'Hosted on GitHub' link at the bottom-left and a blue default 'OK' button at the bottom-right.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "structure_about_window.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "text_home_idle_prompt.png", + "screenshot": "text_home_idle_prompt.png", + "assertion": "The fHash window is idle: the large text area filling the top of the window shows exactly one line of prompt text reading 'Drag files here or click open to start calculate.' and nothing else; a thin empty progress bar sits under it; the bottom row has an unticked 'Uppercase' checkbox on the left, no speed value text next to it, and the three buttons 'Clear', 'Verify' and 'Open...' on the right.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "text_home_idle_prompt.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "text_about_window.png", + "screenshot": "text_about_window.png", + "assertion": "A small window titled 'About fHash' is in front of the main fHash window. It shows a large dark red app icon bearing the Chinese character 希 on the left, and to its right the text lines 'fHash: Files Hash Calculator' followed by a version number, 'Copyright (C) 2007- SUN Junwen.' and three implementation copyright lines mentioning RSA Data Security, Niels Moller and Aaron D. Gifford; a blue 'Hosted on GitHub' hyperlink sits at the bottom-left and a blue default 'OK' button at the bottom-right.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "text_about_window.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "text_report_hello_txt.png", + "screenshot": "text_report_hello_txt.png", + "assertion": "The fHash text area now shows a seven-line report for hello.txt: 'Name: ' with the full file path, 'File Size: 5 Byte(s)', 'Modified Date: ' with a date and time, then the four lines 'MD5:', 'SHA1:', 'SHA256:' and 'SHA512:' whose long hexadecimal values are rendered as blue/accent-coloured hyperlink text; a speed value such as '87.00 B/s' appears in the bottom row left of the 'Clear' button and the progress bar under the text area is full.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "text_report_hello_txt.png", + "rigor": null, + "verdict": null, + "calibration": null + } + ], + "merged_from_files": 6, + "source_shapes": { + "dict_str": 16 + } +} \ No newline at end of file diff --git a/macos/sveinbjornt-katsearch/License.txt b/macos/sveinbjornt-katsearch/License.txt new file mode 100644 index 0000000000000000000000000000000000000000..e999bbf2e29c098b50677f33892103f917e5944b --- /dev/null +++ b/macos/sveinbjornt-katsearch/License.txt @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2018-2020, Sveinbjorn Thordarson +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/macos/sveinbjornt-katsearch/instance.json b/macos/sveinbjornt-katsearch/instance.json new file mode 100644 index 0000000000000000000000000000000000000000..239f39f5ec23f8aa031ba9ae9f90ce6981d8ad0f --- /dev/null +++ b/macos/sveinbjornt-katsearch/instance.json @@ -0,0 +1,10 @@ +{ + "schema_version": 1, + "instance_id": "macos/sveinbjornt-katsearch", + "platform": "macos", + "repo": "https://github.com/sveinbjornt/KatSearch", + "commit": "25d0019b0442d39b7115dc9668fa4b24415d47f2", + "patches": [], + "package": null, + "license": null +} \ No newline at end of file diff --git a/macos/sveinbjornt-katsearch/reference/build.sh b/macos/sveinbjornt-katsearch/reference/build.sh new file mode 100644 index 0000000000000000000000000000000000000000..edff0bbc1594fbfad6cbe98249adf24fbf2759a0 --- /dev/null +++ b/macos/sveinbjornt-katsearch/reference/build.sh @@ -0,0 +1,85 @@ +#!/usr/bin/env bash +# +# build.sh — reproducible, self-contained build for KatSearch (macOS). +# +# KatSearch is a pure Objective-C / Cocoa macOS app built with Xcode. +# All third-party frameworks (Sparkle, MASShortcut, MASPreferences) ship +# prebuilt inside Frameworks/, and the `searchfs` CLI ships prebuilt inside +# KatSearch/Resources/ — every one of these is tracked in git, so a fresh +# clone already contains them. There are therefore NO brew/pod/npm packages +# to install; the only requirement is the Xcode toolchain (assumed present in +# the build environment — we verify it but never try to install Xcode itself). +# +# The one adjustment vs. the stock Makefile is MACOSX_DEPLOYMENT_TARGET: the +# project targets 10.10, but Xcode 14.3+ removed libarclite, so linking an ARC +# binary with a <10.13 target fails ("SDK does not contain 'libarclite'"). +# Raising the target to 10.13 via a build-setting override fixes the link +# without modifying any source file. Code signing is disabled per pipeline +# requirements. + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd "$SCRIPT_DIR" + +APP_NAME="KatSearch" +XCODE_PROJ="$SCRIPT_DIR/KatSearch.xcodeproj" +BUILD_DIR="$SCRIPT_DIR/products" +APP_OUTPUT_DIR="${APP_OUTPUT_DIR:-$SCRIPT_DIR}" +DEPLOYMENT_TARGET="10.13" + +# --------------------------------------------------------------------------- +# 1. Dependencies / toolchain check +# --------------------------------------------------------------------------- +# No package-manager dependencies. Verify the Xcode toolchain is available. +if ! command -v xcodebuild >/dev/null 2>&1; then + echo "ERROR: xcodebuild not found. Install Xcode and select it with" >&2 + echo " 'sudo xcode-select -s /Applications/Xcode.app'." >&2 + exit 1 +fi +if ! xcode-select -p >/dev/null 2>&1; then + echo "ERROR: no active Xcode/CLT developer directory (xcode-select -p failed)." >&2 + exit 1 +fi +echo "==> Using $(xcodebuild -version | head -1) at $(xcode-select -p)" + +# --------------------------------------------------------------------------- +# 2. Build +# --------------------------------------------------------------------------- +# Fresh output directory so re-runs are idempotent. (We do NOT pre-create +# BUILD_DIR: with CONFIGURATION_BUILD_DIR set, xcodebuild's `clean` action +# refuses to delete a directory it did not create.) +rm -rf "$BUILD_DIR" + +echo "==> Building $APP_NAME (Release, x86_64, deployment target $DEPLOYMENT_TARGET)..." +xcodebuild -parallelizeTargets \ + -project "$XCODE_PROJ" \ + -target "$APP_NAME" \ + -configuration "Release" \ + CONFIGURATION_BUILD_DIR="$BUILD_DIR" \ + MACOSX_DEPLOYMENT_TARGET="$DEPLOYMENT_TARGET" \ + CODE_SIGN_IDENTITY="" \ + CODE_SIGNING_ALLOWED=NO \ + CODE_SIGNING_REQUIRED=NO \ + clean build + +APP_BUNDLE="$BUILD_DIR/$APP_NAME.app" +if [[ ! -d "$APP_BUNDLE" ]]; then + echo "ERROR: build did not produce $APP_BUNDLE" >&2 + exit 1 +fi + +# --------------------------------------------------------------------------- +# 3. Publish the .app to APP_OUTPUT_DIR (defaults to the repo root) +# --------------------------------------------------------------------------- +mkdir -p "$APP_OUTPUT_DIR" +APP_OUTPUT_DIR="$(cd "$APP_OUTPUT_DIR" && pwd)" +if [[ "$APP_OUTPUT_DIR" != "$BUILD_DIR" ]]; then + rm -rf "$APP_OUTPUT_DIR/$APP_NAME.app" + cp -R "$APP_BUNDLE" "$APP_OUTPUT_DIR/$APP_NAME.app" +fi + +echo "" +echo "==> BUILD SUCCEEDED" +echo " App bundle: $APP_BUNDLE" +echo " Published copy: $APP_OUTPUT_DIR/$APP_NAME.app" diff --git a/macos/sveinbjornt-katsearch/reference/launch.sh b/macos/sveinbjornt-katsearch/reference/launch.sh new file mode 100644 index 0000000000000000000000000000000000000000..cb9651daa9f33ba5878c2348ab7548f3de4fb2fe --- /dev/null +++ b/macos/sveinbjornt-katsearch/reference/launch.sh @@ -0,0 +1,39 @@ +#!/usr/bin/env bash +# +# launch.sh — start the built KatSearch app. +# +# KatSearch is an LSUIElement app: it runs as a menu-bar / background agent +# (no Dock icon, no window at launch — use its status-bar item / global +# hotkey). All third-party frameworks are embedded in Contents/Frameworks +# with @rpath / @executable_path linkage, so NO DYLD_* variables are needed. + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +APP_NAME="KatSearch" + +# Search candidate locations (in priority order) relative to this script. +CANDIDATES=() +[[ -n "${APP_OUTPUT_DIR:-}" ]] && CANDIDATES+=("$APP_OUTPUT_DIR/$APP_NAME.app") +CANDIDATES+=( + "$SCRIPT_DIR/$APP_NAME.app" + "$SCRIPT_DIR/products/$APP_NAME.app" +) + +APP_PATH="" +for c in "${CANDIDATES[@]}"; do + if [[ -d "$c" ]]; then APP_PATH="$c"; break; fi +done + +if [[ -z "$APP_PATH" ]]; then + echo "ERROR: could not locate $APP_NAME.app. Run 'bash build.sh' first." >&2 + exit 1 +fi + +echo "==> Launching $APP_PATH" +# -W waits until the app terminates; pass through any extra CLI args. +if [[ $# -gt 0 ]]; then + exec open -W "$APP_PATH" --args "$@" +else + exec open -W "$APP_PATH" +fi diff --git a/macos/sveinbjornt-katsearch/tests/ax_helpers.py b/macos/sveinbjornt-katsearch/tests/ax_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..2418d7b8c75891c2d08906848d6a36517cb98135 --- /dev/null +++ b/macos/sveinbjornt-katsearch/tests/ax_helpers.py @@ -0,0 +1,849 @@ +import os +import re +import time +import warnings +import subprocess +from dataclasses import dataclass, field +from typing import Optional +from 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", +} + + +@dataclass +class 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 None diff --git a/macos/sveinbjornt-katsearch/tests/conftest.py b/macos/sveinbjornt-katsearch/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..21a9b7debd04c0633d77a60d8269102790a13e84 --- /dev/null +++ b/macos/sveinbjornt-katsearch/tests/conftest.py @@ -0,0 +1,584 @@ +""" +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 json +import os +import signal +import subprocess +import tempfile +import 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 _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 ` whose ARGUMENT merely contains the bundle path. + + A running .app's argv0 is /Contents/MacOS/, so we require that inner + executable path. The old bare-substring test (`app_path in args`) also matched the + lingering `open -W ` 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 == /Contents/MacOS/. + 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 ` 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//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//... — 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.fixture +def app_process(app_path): + pid = _launch_app(app_path) + yield pid + _kill_pid(pid) + + +@pytest.fixture +def 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.fixture +def 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")) diff --git a/macos/sveinbjornt-katsearch/tests/ks_helpers.py b/macos/sveinbjornt-katsearch/tests/ks_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..f164b0d0456dbe1e28678da889d5bba4171eb802 --- /dev/null +++ b/macos/sveinbjornt-katsearch/tests/ks_helpers.py @@ -0,0 +1,822 @@ +"""ks_helpers.py — KatSearch AX navigation + observation helpers. + +Shared by every test_ax_*.py module. Everything here drives the app that the `ax` +fixture is already attached to — no spawning, no hardcoded install path, no +`defaults write` — so the SAME test drives the reference app AND a recreation. + +Naming convention matters for the RB depth audit: + * `rb_enter_*` / `rb_reach_*` -> counted as a real navigation (surface crossing) + * `open_menu` / `open_preferences` / `select_tab` / `open_window` / `show_menu` + -> whitelisted navigation helper names +Keep those names when adding helpers. +""" + +import json +import os +import re +import subprocess +import time + +# --------------------------------------------------------------------------- +# Screenshot assertion (VLM ground truth) +# --------------------------------------------------------------------------- + + +def results_dir(): + return os.environ.get("RESULTS_DIR") or os.path.join( + os.path.dirname(os.path.abspath(__file__)), "baseline_results") + + +def screenshot_assert(test_name, description, base_dir=None): + """Capture the screen and record what a VLM judge should see.""" + base = base_dir or results_dir() + 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, "%s.png" % test_name) + try: + subprocess.run(["screencapture", "-x", ss_path], timeout=6) + except Exception: + pass + af = os.path.join(ss_dir, "assertions.json") + data = {} + try: + if os.path.exists(af): + with open(af) as f: + data = json.load(f) + except Exception: + data = {} + data["%s.png" % test_name] = description + try: + with open(af, "w") as f: + json.dump(data, f, indent=2) + except Exception: + pass + + +# --------------------------------------------------------------------------- +# Low level utilities +# --------------------------------------------------------------------------- + +def send_escape(times=1): + """Dismiss an open menu / sheet. Uses osascript (no absolute paths).""" + for _ in range(times): + try: + subprocess.run( + ["osascript", "-e", 'tell application "System Events" to key code 53'], + capture_output=True, timeout=6) + except Exception: + pass + time.sleep(0.35) + + +close_menus = send_escape + + +def wait_until(fn, timeout=8.0, interval=0.3): + """Poll fn() until it returns something truthy. Returns the value or None.""" + end = time.time() + timeout + val = None + while time.time() < end: + try: + val = fn() + except Exception: + val = None + if val: + return val + time.sleep(interval) + return val or None + + +def texts_under(ax, root_id, limit=300): + """All non-empty AXValue/AXTitle strings under an element.""" + out = [] + try: + for e in ax._walk_tree(root_id, limit): + for s in (e.value, e.name): + if isinstance(s, str) and s.strip(): + out.append(s.strip()) + except Exception: + pass + return out + + +def elements_under(ax, root_id, limit=400): + try: + return list(ax._walk_tree(root_id, limit)) + except Exception: + return [] + + +# --------------------------------------------------------------------------- +# Window lookup (content based — window titles are not unique in KatSearch) +# --------------------------------------------------------------------------- + +def app_windows(ax): + return ax.find(role="window", max_results=12) + + +def window_titles(ax): + return [w.name or "" for w in app_windows(ax)] + + +def find_window_with(ax, *needles, **kw): + """First window whose visible text contains ANY of `needles` (case-insensitive).""" + limit = kw.get("limit", 300) + lowered = [n.lower() for n in needles] + for w in app_windows(ax): + blob = "  ".join([w.name or ""] + texts_under(ax, w.id, limit)).lower() + if any(n in blob for n in lowered): + return w + return None + + +def intro_window(ax): + """The first-run intro/welcome window.""" + return find_window_with(ax, "welcome to katsearch", "interface mode") + + +def search_window(ax): + """A search window: has a Search push button plus the item-type/match popups.""" + for w in app_windows(ax): + els = elements_under(ax, w.id, 400) + has_btn = any(e.role == "button" and (e.name or "") == "Search" for e in els) + npop = sum(1 for e in els if e.role == "popup") + has_table = any(e.role == "table" for e in els) + if has_btn and npop >= 2 and has_table: + return w + # fallback: any window with a table and >=2 popups + for w in app_windows(ax): + els = elements_under(ax, w.id, 400) + if sum(1 for e in els if e.role == "popup") >= 2 and any( + e.role == "table" for e in els): + return w + return None + + +def prefs_window(ax): + """The preferences/settings window (toolbar with General/Search/Advanced/Tool).""" + for w in app_windows(ax): + if "preference" in (w.name or "").lower() or "setting" in (w.name or "").lower(): + return w + return find_window_with(ax, "Restore Defaults", "Interface Mode", "Keyboard Shortcut") + + +def about_window(ax): + """The About panel.""" + for w in app_windows(ax): + blob = " ".join(texts_under(ax, w.id, 120)) + if re.search(r"\bversion\b", blob, re.I) and "welcome to katsearch" not in blob.lower(): + return w + return None + + +# --------------------------------------------------------------------------- +# Snapshot for reach proofs — role|label set that also captures placeholders, +# window titles and sheet/menu surfaces (kit.rb_showing misses placeholders). +# --------------------------------------------------------------------------- + +def ks_showing(ax): + """{"role|label"} snapshot of everything the app currently exposes via AX.""" + keys = set() + try: + import rb_testgen_kit as kit + keys |= set(kit.rb_showing(ax)) + except Exception: + pass + try: + for w in app_windows(ax): + keys.add("window|%s" % (w.name or "")) + for e in elements_under(ax, w.id, 400): + label = e.name or (e.value if isinstance(e.value, str) else "") or "" + keys.add("%s|%s" % (e.role, label)) + if e.role in ("text_field", "text_area"): + ph = ax.get(e.id, ["AXPlaceholderValue"]).get("AXPlaceholderValue") + if ph: + keys.add("placeholder|%s" % ph) + except Exception: + pass + try: + for s in ax.find(role="sheet", max_results=4): + keys.add("sheet|%s" % (s.name or "")) + for e in elements_under(ax, s.id, 200): + label = e.name or (e.value if isinstance(e.value, str) else "") or "" + keys.add("%s|%s" % (e.role, label)) + except Exception: + pass + return keys + + +# --------------------------------------------------------------------------- +# Menu bar navigation +# --------------------------------------------------------------------------- + +APP_MENUS = ["KatSearch", "File", "Edit", "View", "Action", "Window", "Help"] + + +def menu_bar_items(ax): + """The app's own menu bar items (the Apple menu is excluded).""" + out = [] + for m in ax.find(role="menu_bar_item", max_results=20): + if (m.name or "") in ("Apple", ""): + continue + out.append(m) + return out + + +def menu_bar_item(ax, name): + for m in ax.find(role="menu_bar_item", max_results=20): + if (m.name or "").strip().lower() == name.strip().lower(): + return m + for m in ax.find(role="menu_bar_item", max_results=20): + if name.strip().lower() in (m.name or "").strip().lower(): + return m + return None + + +def menu_items(ax, menu_name, max_results=60): + """Items of an app menu, WITHOUT activating the menu bar.""" + m = menu_bar_item(ax, menu_name) + if m is None: + return [] + return ax.find(role="menu_item", root_id=m.id, max_results=max_results) + + +def open_menu(ax, menu_name, max_results=60): + """NAVIGATION: drop the named menu down and return its items.""" + m = menu_bar_item(ax, menu_name) + if m is None: + return [] + ax.action(m.id, "AXPress") + time.sleep(0.6) + items = ax.find(role="menu_item", root_id=m.id, max_results=max_results) + return items + + +def find_item(items, name): + """Exact-then-substring match over a list of AX elements.""" + n = (name or "").strip().lower() + for it in items: + if (it.name or "").strip().lower() == n: + return it + for it in items: + if n and n in (it.name or "").strip().lower(): + return it + return None + + +def item_names(items): + return [(i.name or "") for i in items if (i.name or "").strip()] + + +def pick_menu_item(ax, menu_name, item_name, settle=0.9): + """Activate menu > item. Returns True when the item was found and pressed.""" + it = find_item(menu_items(ax, menu_name), item_name) + if it is None: + it = find_item(open_menu(ax, menu_name), item_name) + if it is None: + close_menus() + return False + ok = ax.action(it.id, "AXPress") + time.sleep(settle) + return bool(ok) or True + + +def menu_mark(ax, menu_name, item_name): + """AXMenuItemMarkChar of a menu item ('✓' when checked, None when not).""" + it = find_item(menu_items(ax, menu_name), item_name) + if it is None: + return None + try: + return ax.get(it.id, ["AXMenuItemMarkChar"]).get("AXMenuItemMarkChar") + except Exception: + return None + + +def menu_item_enabled(ax, menu_name, item_name): + it = find_item(menu_items(ax, menu_name), item_name) + return None if it is None else bool(it.enabled) + + +def mark_of(ax, item): + try: + return ax.get(item.id, ["AXMenuItemMarkChar"]).get("AXMenuItemMarkChar") + except Exception: + return None + + +# --------------------------------------------------------------------------- +# NAVIGATION: intro window +# --------------------------------------------------------------------------- + +def intro_button(ax, *names): + w = intro_window(ax) + if w is None: + return None + btns = ax.find(role="button", root_id=w.id, max_results=15) + for n in names: + b = find_item(btns, n) + if b is not None: + return b + return None + + +def select_application_mode(ax): + """Click the 'Application' interface-mode thumbnail so the app stays a regular + (menu-bar) app after the intro finishes. Best effort — returns True on click.""" + w = intro_window(ax) + if w is None: + return False + imgs = ax.find(role="image", root_id=w.id, max_results=10) + cand = None + for i in imgs: + n = (i.name or "").lower() + if "application" in n or n == "app icon": + cand = i + break + if cand is None and imgs: + cand = imgs[0] + if cand is None: + return False + try: + return bool(ax.click_element_cg(cand.id)) + except Exception: + return False + + +def rb_enter_intro_page2(ax): + """NAVIGATION: intro page 1 -> page 2 (Continue →). Returns True on success.""" + b = intro_button(ax, "Continue →", "Continue") + if b is None: + return False + ax.action(b.id, "AXPress") + time.sleep(1.2) + return intro_button(ax, "Start using KatSearch", "Start") is not None + + +def rb_back_intro_page1(ax): + """Intro page 2 -> page 1 (the ← back button).""" + b = intro_button(ax, "←", "Back") + if b is None: + return False + ax.action(b.id, "AXPress") + time.sleep(1.2) + return intro_button(ax, "Continue →", "Continue") is not None + + +def rb_reach_search_window_via_intro(ax): + """NAVIGATION: run the whole intro wizard (select Application mode -> + Continue → -> Start using KatSearch) so the intro closes and the first + search window opens. Returns the search window element (or None).""" + select_application_mode(ax) + time.sleep(0.4) + rb_enter_intro_page2(ax) + b = intro_button(ax, "Start using KatSearch", "Start") + if b is None: + return None + ax.action(b.id, "AXPress") + return wait_until(lambda: search_window(ax), timeout=8.0) + + +# --------------------------------------------------------------------------- +# NAVIGATION: search window +# --------------------------------------------------------------------------- + +def rb_enter_search_window(ax): + """NAVIGATION: File > New Search Window. Returns the search window element.""" + w = search_window(ax) + if w is not None: + return w + if not pick_menu_item(ax, "File", "New Search Window", settle=1.2): + # fall back to the intro wizard, then to Cmd-N + w = rb_reach_search_window_via_intro(ax) + if w is not None: + return w + try: + subprocess.run(["osascript", "-e", + 'tell application "System Events" to keystroke "n" using command down'], + capture_output=True, timeout=6) + except Exception: + pass + return wait_until(lambda: search_window(ax), timeout=8.0) + + +def sw(ax): + """The search window, opening one if needed.""" + return rb_enter_search_window(ax) + + +def sw_popups(ax, w=None): + """[item-type popup, match-criterion popup, search-target popup].""" + w = w or search_window(ax) + if w is None: + return [] + return ax.find(role="popup", root_id=w.id, max_results=6) + + +def popup_value(ax, popup): + try: + v = ax.get(popup.id, ["AXValue"]).get("AXValue") + except Exception: + v = None + return v if isinstance(v, str) else (popup.value if isinstance(popup.value, str) else "") + + +def popup_items(ax, popup, max_results=25): + """Open a pop-up button's menu and return its items (menu stays open).""" + ax.action(popup.id, "AXPress") + time.sleep(0.8) + return ax.find(role="menu_item", root_id=popup.id, max_results=max_results) + + +def switch_mode(ax, popup, title): + """NAVIGATION-ish: select `title` in a pop-up button. Returns True on success.""" + items = popup_items(ax, popup) + t = find_item(items, title) + if t is None: + close_menus() + return False + ax.action(t.id, "AXPick") + time.sleep(0.8) + return popup_value(ax, popup).strip().lower() == title.strip().lower() + + +def set_item_type(ax, title, w=None): + ps = sw_popups(ax, w) + return bool(ps) and switch_mode(ax, ps[0], title) + + +def set_match_criterion(ax, title, w=None): + ps = sw_popups(ax, w) + return len(ps) > 1 and switch_mode(ax, ps[1], title) + + +def search_field(ax, w=None): + """The main search text field (NOT the filter search field).""" + w = w or search_window(ax) + if w is None: + return None + best = None + for t in ax.find(role="text_field", root_id=w.id, max_results=8): + try: + attrs = ax.get(t.id, ["AXPlaceholderValue", "AXSubrole"]) + except Exception: + attrs = {} + ph = (attrs.get("AXPlaceholderValue") or "") + sub = (attrs.get("AXSubrole") or "") + if "filter" in ph.lower() or "SearchField" in sub: + continue + best = best or t + return best + + +def filter_field(ax, w=None): + """The results filter field (placeholder 'Filter...'), or None when hidden.""" + w = w or search_window(ax) + if w is None: + return None + for t in ax.find(role="text_field", root_id=w.id, max_results=8): + try: + attrs = ax.get(t.id, ["AXPlaceholderValue", "AXSubrole"]) + except Exception: + attrs = {} + if "filter" in (attrs.get("AXPlaceholderValue") or "").lower(): + return t + if "SearchField" in (attrs.get("AXSubrole") or ""): + return t + return None + + +def set_text(ax, field, value): + if field is None: + return False + ax.set_value(field.id, value) + time.sleep(0.5) + try: + return ax.get(field.id, ["AXValue"]).get("AXValue") == value + except Exception: + return False + + +def set_search_text(ax, value, w=None): + return set_text(ax, search_field(ax, w), value) + + +def sw_button(ax, name, w=None): + w = w or search_window(ax) + if w is None: + return None + return find_item(ax.find(role="button", root_id=w.id, max_results=25), name) + + +def role_description(ax, el): + try: + return ax.get(el.id, ["AXRoleDescription"]).get("AXRoleDescription") or "" + except Exception: + return "" + + +def sort_headers(ax, w=None): + """Names of the visible results-table column headers, left to right.""" + w = w or search_window(ax) + if w is None: + return [] + out = [] + for b in ax.find(role="button", root_id=w.id, max_results=30): + if "sort" in role_description(ax, b).lower() and (b.name or "").strip(): + out.append(b.name) + return out + + +STATUS_RE = re.compile(r"^(Found|Showing|Searching)", re.I) + + +def status_text(ax, w=None): + """The results status line ('Searching...', 'Found N items', 'Showing X of Y items').""" + w = w or search_window(ax) + if w is None: + return None + for e in ax.find(role="label", root_id=w.id, max_results=20): + v = e.value if isinstance(e.value, str) else None + if v and STATUS_RE.match(v.strip()): + return v.strip() + return None + + +def result_rows(ax, w=None, max_rows=200): + w = w or search_window(ax) + if w is None: + return [] + return ax.find(role="row", root_id=w.id, max_results=max_rows) + + +def row_cell_texts(ax, row): + return [c.value for c in elements_under(ax, row.id, 20) + if c.role == "label" and isinstance(c.value, str) and c.value.strip()] + + +def row_names(ax, w=None, max_rows=200): + """The Name-column text of every results row.""" + out = [] + for r in result_rows(ax, w, max_rows): + cells = row_cell_texts(ax, r) + if cells: + out.append(cells[0]) + return out + + +def row_kinds(ax, w=None, max_rows=200): + out = [] + for r in result_rows(ax, w, max_rows): + cells = row_cell_texts(ax, r) + out.append(cells[1] if len(cells) > 1 else None) + return out + + +def run_search(ax, term=None, w=None, first_result_timeout=12.0, settle=1.2, stop=True): + """Type `term` (optional), press Search, wait for the first streamed results, + then press Stop so the test stays inside its time budget. + Returns the status-line text after stopping.""" + w = w or search_window(ax) + if w is None: + return None + if term is not None: + set_search_text(ax, term, w) + b = sw_button(ax, "Search", w) + if b is None: + return None + ax.action(b.id, "AXPress") + wait_until(lambda: result_rows(ax, w, 2), timeout=first_result_timeout) + time.sleep(settle) + if stop: + s = sw_button(ax, "Stop", w) + if s is not None: + ax.action(s.id, "AXPress") + time.sleep(0.9) + return status_text(ax, w) + + +def stop_search(ax, w=None): + s = sw_button(ax, "Stop", w) + if s is None: + return False + ax.action(s.id, "AXPress") + time.sleep(0.9) + return True + + +def select_first_row(ax, w=None): + """Select the first results row (AXSelected). Returns True on success.""" + rows = result_rows(ax, w, 5) + if not rows: + return False + try: + import ApplicationServices as AS + AS.AXUIElementSetAttributeValue(ax._get_ref(rows[0].id), "AXSelected", True) + except Exception: + try: + ax.click_element_cg(rows[0].id) + except Exception: + return False + time.sleep(0.9) + try: + return bool(ax.get(rows[0].id, ["AXSelected"]).get("AXSelected")) + except Exception: + return False + + +def path_bar(ax, w=None): + """The path bar (NSPathControl) shown under the results when a row is selected.""" + w = w or search_window(ax) + if w is None: + return None + for l in ax.find(role="list", root_id=w.id, max_results=6): + if "path" in (l.name or "").lower(): + return l + ls = ax.find(role="list", root_id=w.id, max_results=6) + return ls[0] if ls else None + + +# --------------------------------------------------------------------------- +# NAVIGATION: sub-surfaces of the search window +# --------------------------------------------------------------------------- + +def rb_enter_options_menu(ax, w=None): + """NAVIGATION: open the advanced search-options menu (the 'action' gear button). + Returns its menu items (the menu is left open).""" + w = w or search_window(ax) + if w is None: + return [] + btn = sw_button(ax, "action", w) + if btn is None: + for b in ax.find(role="button", root_id=w.id, max_results=25): + if "option" in (ax.get(b.id, ["AXHelp"]).get("AXHelp") or "").lower(): + btn = b + break + if btn is None: + return [] + ax.action(btn.id, "AXShowMenu") + time.sleep(1.0) + return ax.find(role="menu_item", root_id=btn.id, max_results=20) + + +def toggle_search_option(ax, title, w=None): + """Open the options menu and pick `title`. Returns True when it was picked.""" + items = rb_enter_options_menu(ax, w) + t = find_item(items, title) + if t is None: + close_menus() + return False + ax.action(t.id, "AXPick") + time.sleep(0.9) + return True + + +def search_option_mark(ax, title, w=None): + """Mark char of a search-option menu item; leaves the menu closed.""" + items = rb_enter_options_menu(ax, w) + t = find_item(items, title) + m = mark_of(ax, t) if t is not None else None + close_menus() + return m + + +def rb_enter_column_menu(ax, w=None): + """NAVIGATION: open the results-table header contextual menu (columns menu).""" + w = w or search_window(ax) + if w is None: + return [] + target = None + for g in ax.find(role="group", root_id=w.id, max_results=20): + if "AXShowMenu" in (g.actions or []): + target = g + break + if target is None: + return [] + ax.action(target.id, "AXShowMenu") + time.sleep(1.1) + return ax.find(role="menu_item", root_id=target.id, max_results=25) + + +def rb_enter_row_context_menu(ax, w=None): + """NAVIGATION: open the contextual menu of the results table (needs a selection + for the item actions to be enabled).""" + w = w or search_window(ax) + if w is None: + return [] + tbls = ax.find(role="table", root_id=w.id, max_results=3) + if not tbls: + return [] + ax.action(tbls[0].id, "AXShowMenu") + time.sleep(1.2) + return ax.find(role="menu_item", root_id=tbls[0].id, max_results=30) + + +def rb_enter_save_sheet(ax, w=None): + """NAVIGATION: File > Save… -> the save sheet. Returns the sheet element.""" + pick_menu_item(ax, "File", "Save…", settle=1.6) + return wait_until(lambda: (ax.find(role="sheet", max_results=3) or [None])[0], + timeout=6.0) + + +def sheet_field_values(ax, sheet): + out = [] + for e in elements_under(ax, sheet.id, 300): + if e.role in ("text_field", "combobox") and isinstance(e.value, str) and e.value.strip(): + out.append(e.value.strip()) + return out + + +# --------------------------------------------------------------------------- +# NAVIGATION: preferences window +# --------------------------------------------------------------------------- + +PREFS_TABS = ["General", "Search", "Advanced", "Tool"] + + +def open_preferences(ax): + """NAVIGATION: KatSearch > Settings… -> the preferences window.""" + w = prefs_window(ax) + if w is not None: + return w + if not pick_menu_item(ax, "KatSearch", "Settings…", settle=1.4): + pick_menu_item(ax, "KatSearch", "Preferences…", settle=1.4) + return wait_until(lambda: prefs_window(ax), timeout=8.0) + + +def prefs_tab_buttons(ax, w=None): + w = w or prefs_window(ax) + if w is None: + return [] + out = [] + tbs = ax.find(role="toolbar", root_id=w.id, max_results=3) + root = tbs[0].id if tbs else w.id + for b in ax.find(role="button", root_id=root, max_results=20): + if (b.name or "").strip(): + out.append(b) + return out + + +def select_tab(ax, label, w=None): + """NAVIGATION: switch preference pane (General/Search/Advanced/Tool).""" + w = w or open_preferences(ax) + if w is None: + return False + b = find_item(prefs_tab_buttons(ax, w), label) + if b is None: + return False + ax.action(b.id, "AXPress") + time.sleep(1.2) + return True + + +def prefs_checkboxes(ax, w=None): + w = w or prefs_window(ax) + if w is None: + return [] + return ax.find(role="checkbox", root_id=w.id, max_results=20) + + +def checkbox_named(ax, name, root=None): + root = root or prefs_window(ax) + if root is None: + return None + return find_item(ax.find(role="checkbox", root_id=root.id, max_results=25), name) + + +def checkbox_value(ax, cb): + if cb is None: + return None + try: + v = ax.get(cb.id, ["AXValue"]).get("AXValue") + except Exception: + return None + try: + return int(v) + except Exception: + return v + + +def toggle_checkbox(ax, cb): + if cb is None: + return False + ax.action(cb.id, "AXPress") + time.sleep(0.7) + return True + + +def prefs_texts(ax, w=None): + w = w or prefs_window(ax) + return [] if w is None else texts_under(ax, w.id, 300) + + +# --------------------------------------------------------------------------- +# NAVIGATION: about panel +# --------------------------------------------------------------------------- + +def open_window_about(ax): + """NAVIGATION: KatSearch > About KatSearch -> the About panel.""" + pick_menu_item(ax, "KatSearch", "About KatSearch", settle=1.6) + return wait_until(lambda: about_window(ax), timeout=6.0) diff --git a/macos/sveinbjornt-katsearch/tests/rb_testgen_kit.py b/macos/sveinbjornt-katsearch/tests/rb_testgen_kit.py new file mode 100644 index 0000000000000000000000000000000000000000..ccbbdd3c6136513161c133fbb4cefcfb0386d55c --- /dev/null +++ b/macos/sveinbjornt-katsearch/tests/rb_testgen_kit.py @@ -0,0 +1,575 @@ +#!/usr/bin/env python3 +"""RB TestGen Kit (macOS/AX port of the Linux v7.5 kit) — a test's NAVIGATION +DEPTH and JUMP RIGOR are DECLARED (not inferred), uniformly recorded, and +self-auditable. + +DIFFERENCE FROM LINUX: macOS tests are **pytest** (methods on Test* classes taking +the `ax` fixture, plain asserts) — NOT standalone scripts calling R.record(). So the +DECLARATION is a pytest marker on the test method: + + import rb_testgen_kit as kit + + @pytest.mark.rb(depth=1, jump_kind="reach", expect="Preferences window visible") + def test_prefs_opens(self, ax_with_reset): + before = kit.rb_showing(ax_with_reset) + helpers.rb_reach_prefs(ax_with_reset) # a nav helper you name rb_reach_* / rb_enter_* + after = kit.rb_showing(ax_with_reset) + assert kit.rb_reach(before, after, target="Preferences", source="menu bar") + +conftest.py's pytest_runtest_makereport hook reads the marker + the test outcome and +writes {name, passed, depth, jump_kind, tier, expect} so the runner can fold it into +_results.json. The audits below then read those records (+ the test SOURCE). + +jump_kind (verbatim strings — the audit/stats key off them): + "none" no trigger; existence/structure only -> tier 0 + "liveness" only "did not crash / still alive" -> tier 1 (weak; avoid) + "reach" a real surface jump: the TARGET surface's element + APPEARED and the SOURCE surface's element DISAPPEARED -> tier 2 + "transition" a state flip (CHECKED/ENABLED/mode) before->after -> tier 2 + "value" a specific expected value/content was asserted -> tier 3 + +DEPTH is the number of surfaces crossed before the assertion (0 = home/first screen, +1 = one dialog/panel/submenu, 2+ = deeper). A flat-tree read of a deep element is +depth 0 — depth counts surfaces the test actually navigated through. + +REACH PROOF (so "reach" cannot be faked by reading a flat tree): + before = rb_showing(ax) + + 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('')" + python3 -c "import rb_testgen_kit as k; k.rb_lint('')" + python3 -c "import rb_testgen_kit as k; k.rb_lint_sources('')" + python3 -c "import rb_testgen_kit as k; k.rb_audit_depth('','')" +""" +from __future__ import annotations + +import ast +import glob +import json +import os +import re + +JUMP_KINDS = {"none": 0, "liveness": 1, "reach": 2, "transition": 2, "value": 3} + +# Double-axis quota TARGETS (fractions) — goals rb_audit REPORTS, NOT a hard gate. +QUOTAS = { + "existence_max": 0.30, # jump_kind=="none" share of ALL tests + "interactive_min": 0.60, # reach|transition|value share of ALL tests + "depth_ge1_min": 0.40, # depth>=1 share of INTERACTIVE tests + "depth_ge2_min": 0.10, # depth>=2 share of INTERACTIVE tests + "value_min": 0.25, # jump_kind=="value" share of INTERACTIVE tests +} + +# Depth family: a test "crosses a surface" iff it calls a member of the depth family. +# macOS accepts BOTH the naming convention rb_enter_*/rb_reach_* (write your own nav +# helper and NAME it so) AND the existing verifier_helpers/ax_helpers navigation +# functions (whitelist below) — so tests can reuse the mature reveal/navigate helpers. +DEPTH_FWD_RE = re.compile(r"^rb_(enter|reach)[a-z0-9_]*$") +DEPTH_BACK_RE = re.compile(r"^rb_back[a-z0-9_]*$") +# verifier_helpers / ax_helpers navigation functions that OPEN or move to a new surface. +FWD_WHITELIST = { + "ensure_ui_visible", "ensure_panel_open", "open_actions_menu", "open_menu", + "open_settings", "open_preferences", "open_dialog", "open_panel", "open_window", + "navigate_month", "navigate", "switch_tab", "switch_mode", "switch_page", + "select_tab", "reveal_window", "show_panel", "show_menu", +} +BACK_WHITELIST = { + "dismiss_menus", "dismiss_panel", "dismiss_any_dialog", "close_panel", + "close_window", "go_back", +} +# pytest fixtures that themselves navigate into a surface during setup (so a test taking +# one legitimately has depth>=1 without a nav call in its own body). `ax` does NOT navigate. +_NAV_FIXTURES = {"ax_with_reset", "open_panel"} +# MEASURED-TIER verdict families (ported from keliang): a tier2/3 jump_kind must be BACKED +# by its verdict function — transition->rb_flip*, value->rb_value*, reach->rb_reach* — whose +# bool result is the test's assertion. Self-named wrappers count by prefix. +TIER_FLIP_RE = re.compile(r"^rb_flip[a-z0-9_]*$") +TIER_VALUE_RE = re.compile(r"^rb_value[a-z0-9_]*$") +_JK_FAMILY = {"transition": "flip", "value": "value", "reach": "reach"} +# normalize plural (v73prep) / singular module names so a JSON module ("button") and a +# file stem ("buttons") join. +_MODULE_ALIAS = {"menus": "menu", "buttons": "button", "states": "state", + "structures": "structure", "texts": "text", + "computations": "computation", "workflows": "workflow"} + +_DEPTH = 0 # module-global surface counter for rb_enter/rb_back + + +def tier_of(jump_kind: str) -> int: + return JUMP_KINDS.get(jump_kind, 2) + + +def rb_reset_depth() -> None: + global _DEPTH + _DEPTH = 0 + + +def rb_enter(_surface: str = "") -> int: + """Call right after your test navigates into a new surface (dialog/panel/submenu).""" + global _DEPTH + _DEPTH += 1 + return _DEPTH + + +def rb_back() -> int: + global _DEPTH + _DEPTH = max(0, _DEPTH - 1) + return _DEPTH + + +def _walk_tree_nodes(node, out, seen): + """Yield 'role|name' for a macOS AXHelper.tree() dict node (+children).""" + if not isinstance(node, dict) or seen[0] >= 8000: + return + seen[0] += 1 + role = str(node.get("role") or "") + name = str(node.get("name") or node.get("value") or "") + if role or name: + out.add(f"{role}|{name}") + for c in (node.get("children") or []): + _walk_tree_nodes(c, out, seen) + + +def rb_showing(ax, max_depth: int = 12) -> set: + """Snapshot the currently-reachable AX subtree under the app as {"role|name"}. + macOS AX has no AT-SPI SHOWING/VISIBLE state, so we approximate "showing" by the + live AX tree (AXChildren) the app currently exposes — a new window/sheet/popover + adds its elements; a dismissed one removes them. Feed before+after a trigger to + rb_reach() so a 'reach' test proves a REAL surface change, not a flat-tree read. + Safe no-op (empty set) if `ax` cannot produce a tree.""" + out: set = set() + try: + tree = ax.tree(max_depth=max_depth) # AXHelper.tree() -> nested dict + except Exception: + return out + _walk_tree_nodes(tree, out, [0]) + return out + + +def rb_reach(before, after, target: str, source: str | None = None) -> bool: + """True-jump verdict: the TARGET surface's discriminating element newly APPEARED + AND (if given) the SOURCE surface's discriminating element DISAPPEARED. This is + what separates a real surface jump from reading an element that was always there.""" + before = set(before or []) + after = set(after or []) + t = target.lower() + appeared = any(t in k.lower() for k in (after - before)) + if source is None: + return appeared + s = source.lower() + src_before = any(s in k.lower() for k in before) + src_after = any(s in k.lower() for k in after) + return appeared and src_before and not src_after + + +def rb_flip(before, after, expect: str = "") -> bool: + """In-page STATE-FLIP verdict (tier2 `transition`): the observed state actually CHANGED + before->after (a CHECKED/ENABLED/mode/selection value read the two times). Pass its bool + as the test's assertion. Does NOT touch depth — an in-page flip is depth 0 unless you + navigated a surface to reach the control. You MAY write your own `rb_flip_()` 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_()` 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 | " + "{audit_depth|audit_tier} [results_dir]}") diff --git a/macos/sveinbjornt-katsearch/tests/requirements.txt b/macos/sveinbjornt-katsearch/tests/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..feef67ce2aadbaa26d12e6b01cff7b8ce89ecb5c --- /dev/null +++ b/macos/sveinbjornt-katsearch/tests/requirements.txt @@ -0,0 +1,3 @@ +pytest +pytest-check +pyobjc diff --git a/macos/sveinbjornt-katsearch/tests/test_ax_buttons.py b/macos/sveinbjornt-katsearch/tests/test_ax_buttons.py new file mode 100644 index 0000000000000000000000000000000000000000..9c3c386c97515613aefa69ad80d2fedb3dce3486 --- /dev/null +++ b/macos/sveinbjornt-katsearch/tests/test_ax_buttons.py @@ -0,0 +1,646 @@ +"""AX button tests for KatSearch — each button verified by its OBSERVED consequence.""" + +import os +import re +import sys +import time + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +import pytest + +import ks_helpers as ks +import rb_testgen_kit as kit + + +# --------------------------------------------------------------------------- +# tiny AX compatibility layer +# +# recon.md documents WHICH ks_helpers functions to use, but a few button facts +# (AXEnabled / AXHelp) and two raw presses (`Search`, the `Items` sort header) +# have no dedicated ks helper. The shims below read/act through whatever API +# the deployed AXHelper exposes, falling back to the raw ApplicationServices +# calls, so the SAME test drives the reference app and any recreation. +# --------------------------------------------------------------------------- + +_REF_NAMES = ("ref", "element", "_element", "ax_element", "axelement", "_ref", "raw", "native") + + +def _lookup(obj, name): + try: + val = getattr(obj, name) + except Exception: + val = None + if val is not None: + if callable(val): + try: + val = val() + except Exception: + val = None + if val is not None: + return val + for holder in ("attrs", "attributes", "_attrs", "data"): + bag = getattr(obj, holder, None) + if isinstance(bag, dict) and name in bag: + return bag[name] + try: + if isinstance(obj, dict) and name in obj: + return obj[name] + except Exception: + pass + return None + + +def _attr(obj, *names): + for name in names: + val = _lookup(obj, name) + if val is not None: + return val + return None + + +def _eid(el): + if el is None: + return None + for name in ("id", "element_id", "uid", "index"): + val = getattr(el, name, None) + if isinstance(val, (str, int)) and not isinstance(val, bool): + return val + return el + + +def _role(el): + return _attr(el, "role", "AXRole") or "" + + +def _name(el): + val = _attr(el, "name", "title", "AXTitle", "label") + return val if isinstance(val, str) else ("" if val is None else str(val)) + + +def _refs(el): + out = [el] + for name in _REF_NAMES: + cand = getattr(el, name, None) + if cand is not None: + out.append(cand) + return out + + +def _raw_attr(el, ax_name): + try: + from ApplicationServices import AXUIElementCopyAttributeValue + except Exception: + return None + for ref in _refs(el): + try: + err, val = AXUIElementCopyAttributeValue(ref, ax_name, None) + except Exception: + continue + if err == 0 and val is not None: + return val + return None + + +def _raw_action(el, action): + try: + from ApplicationServices import AXUIElementPerformAction + except Exception: + return False + for ref in _refs(el): + try: + if AXUIElementPerformAction(ref, action) == 0: + return True + except Exception: + continue + return False + + +def _ax_attr(ax, el, ax_name, *py_names): + """Read one AX attribute of `el` through any available AXHelper API.""" + if el is None: + return None + val = _attr(el, *py_names) + if val is not None: + return val + for meth in ("get_attribute", "attribute_value", "get_attr", "attr", + "copy_attribute_value", "get_element_attribute"): + fn = getattr(ax, meth, None) + if not callable(fn): + continue + for target in (_eid(el), el): + try: + got = fn(target, ax_name) + except Exception: + continue + if got is not None: + return got + return _raw_attr(el, ax_name) + + +def _to_bool(val): + if isinstance(val, bool): + return val + if isinstance(val, int) and val in (0, 1): + return bool(val) + if isinstance(val, str): + low = val.strip().lower() + if low in ("true", "1", "yes"): + return True + if low in ("false", "0", "no"): + return False + return None + + +def _enabled(ax, el): + return _to_bool(_ax_attr(ax, el, "AXEnabled", "enabled", "is_enabled", "AXEnabled")) + + +def _help(ax, el): + val = _ax_attr(ax, el, "AXHelp", "help", "help_text", "AXHelp", "tooltip") + return val if isinstance(val, str) else (None if val is None else str(val)) + + +def _press(ax, el, action="AXPress"): + """AXPress / AXShowMenu `el`, trying every plausible AXHelper entry point.""" + if el is None: + return False + attempts = [] + for meth in ("perform_action", "do_action", "perform", "action"): + fn = getattr(ax, meth, None) + if callable(fn): + attempts.append((fn, (_eid(el), action))) + attempts.append((fn, (el, action))) + if action == "AXPress": + for meth in ("press", "click_element", "activate"): + fn = getattr(ax, meth, None) + if callable(fn): + attempts.append((fn, (_eid(el),))) + attempts.append((fn, (el,))) + fn = getattr(el, "press", None) + if callable(fn): + attempts.append((fn, ())) + for meth in ("perform_action", "do_action"): + fn = getattr(el, meth, None) + if callable(fn): + attempts.append((fn, (action,))) + for fn, args in attempts: + try: + res = fn(*args) + except Exception: + continue + if res is False: + continue + return True + return _raw_action(el, action) + + +def _under(ax, el, limit=400): + """ks.elements_under tolerant of element-vs-element_id.""" + if el is None: + return [] + for target in (_eid(el), el): + try: + got = ks.elements_under(ax, target, limit=limit) + except Exception: + continue + if got: + return list(got) + return [] + + +def _buttons_under(ax, el): + return [e for e in _under(ax, el) if _role(e) == "button"] + + +def _button_named(ax, root, name): + for btn in _buttons_under(ax, root): + if _name(btn) == name: + return btn + return None + + +def _action_button_title(ax): + """Title currently worn by the search window's primary action button.""" + for name in ("Stop", "Search"): + try: + if ks.sw_button(ax, name) is not None: + return name + except Exception: + continue + return None + + +def _search_window_title(ax): + try: + titles = ks.window_titles(ax) or [] + except Exception: + return None + for title in titles: + if title and title.endswith(" - KatSearch"): + return title + for title in titles: + if title == "KatSearch": + return title + return None + + +def _dismiss_sheet(): + try: + ks.close_menus(2) + except TypeError: + ks.close_menus() + ks.send_escape(2) + except Exception: + pass + + +def _stop_quietly(ax): + try: + ks.stop_search(ax) + except Exception: + pass + + +# --------------------------------------------------------------------------- +# intro / welcome window buttons +# --------------------------------------------------------------------------- + +class TestIntroButtons: + + @pytest.mark.rb(depth=1, jump_kind="reach", + expect="pressing intro 'Continue →' re-titles the same button to " + "'Start using KatSearch' and 'Continue →' disappears") + def test_continue_button_advances_to_page_two(self, ax): + assert ks.intro_window(ax) is not None, "intro window is not present at launch" + before = ks.ks_showing(ax) + assert "button|Continue →" in before, "intro page 1 has no 'Continue →' button" + assert ks.rb_enter_intro_page2(ax), "pressing 'Continue →' failed" + time.sleep(0.5) + after = ks.ks_showing(ax) + assert kit.rb_reach(before, after, + target="button|Start using KatSearch", + source="button|Continue →") + assert "button|←" in after, "intro page 2 has no '←' back button" + + @pytest.mark.rb(depth=1, jump_kind="reach", + expect="pressing intro '←' brings 'Continue →' back while " + "'Start using KatSearch' and '←' disappear") + def test_back_button_returns_to_page_one(self, ax): + assert ks.rb_enter_intro_page2(ax), "could not reach intro page 2" + time.sleep(0.5) + before = ks.ks_showing(ax) + assert "button|Start using KatSearch" in before + assert "button|←" in before + assert ks.rb_back_intro_page1(ax), "pressing the '←' back button failed" + time.sleep(0.6) + after = ks.ks_showing(ax) + assert kit.rb_reach(before, after, + target="button|Continue →", + source="button|Start using KatSearch") + assert "button|←" not in after, "the '←' button did not hide itself on page 1" + + @pytest.mark.rb(depth=2, jump_kind="reach", + expect="pressing 'Start using KatSearch' closes the intro window " + "('Welcome to KatSearch! ' gone) and opens window|KatSearch") + def test_start_using_katsearch_opens_search_window(self, ax): + before = ks.ks_showing(ax) + assert "label|Welcome to KatSearch! " in before, "intro headline missing at launch" + assert ks.search_window(ax) is None, "a search window already existed before the wizard" + win = ks.rb_reach_search_window_via_intro(ax) + assert win is not None, "'Start using KatSearch' did not open a search window" + time.sleep(0.8) + after = ks.ks_showing(ax) + assert kit.rb_reach(before, after, + target="window|KatSearch", + source="label|Welcome to KatSearch! ") + assert "label|Please select your preferred interface mode:" not in after + assert ks.intro_window(ax) is None, "the intro window survived the wizard" + assert "button|Search" in after + ks.screenshot_assert( + "buttons_start_using_katsearch_opens_search_window", + "The welcome/intro window is gone and a window titled “KatSearch” is showing a " + "query row reading “Find [items ▾] [name contains ▾] [text field] where/on " + "[volume ▾]”, a “Search” button, and an empty results table with the column " + "headers Items / Kind / Date Modified / Size.") + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="intro page 2 carries button 'Empty keyboard shortcut' whose AXHelp is " + "'To record a new shortcut, click this button, and then type the new " + "shortcut, or press delete to clear an existing shortcut.'") + def test_shortcut_recorder_button_is_present_with_help(self, ax): + assert ks.rb_enter_intro_page2(ax), "could not reach intro page 2" + time.sleep(0.5) + win = ks.intro_window(ax) + assert win is not None, "intro window disappeared" + showing = ks.ks_showing(ax) + assert "button|Empty keyboard shortcut" in showing, \ + "no shortcut-recorder button on intro page 2" + btn = _button_named(ax, win, "Empty keyboard shortcut") + assert btn is not None, "shortcut-recorder button not found under the intro window" + # NEVER pressed: recording a shortcut needs real key events (recon ## UNREACHED). + help_text = _help(ax, btn) + assert help_text is not None, "could not read AXHelp of the shortcut-recorder button" + assert kit.rb_value( + help_text.strip(), + "To record a new shortcut, click this button, and then type the new shortcut, " + "or press delete to clear an existing shortcut.") + ks.screenshot_assert( + "buttons_shortcut_recorder_button_is_present_with_help", + "The welcome window now shows “Set keyboard shortcut for search window " + "(optional):”, a keyboard image, a shortcut-recorder button, the checkboxes " + "“Launch on Login” and “Check for Updates”, a “←” back button and a " + "“Start using KatSearch” button.") + + +# --------------------------------------------------------------------------- +# search window buttons: Search / Stop / action / lock +# --------------------------------------------------------------------------- + +class TestSearchWindowButtons: + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="pressing 'Search' flips the button title Search→Stop, the status line " + "empty→'Searching...' and the window title to “Automator” on - KatSearch") + def test_search_button_starts_search(self, ax): + win = ks.rb_enter_search_window(ax) + assert win is not None, "File > New Search Window did not open a search window" + popups = ks.sw_popups(ax, win) + assert len(popups) >= 3, "search window is missing its 3 query popups" + volume = ks.popup_value(ax, popups[2]) + assert volume, "could not read the search-target volume popup" + assert ks.set_search_text(ax, "Automator"), "could not type into the search field" + + before_status = ks.status_text(ax) or "" + before_title = _action_button_title(ax) + assert before_title == "Search", "the action button did not start out titled 'Search'" + + btn = ks.sw_button(ax, "Search") + assert btn is not None + assert _press(ax, btn), "AXPress on the 'Search' button failed" + + ks.wait_until(lambda: (ks.status_text(ax) or "").startswith("Searching") + or ks.sw_button(ax, "Stop") is not None, timeout=6.0) + after_status = ks.status_text(ax) or "" + after_title = _action_button_title(ax) + title = _search_window_title(ax) + ks.screenshot_assert( + "buttons_search_button_starts_search", + "In the KatSearch search window the query controls are greyed out, a spinning " + "progress indicator is visible, the button that read “Search” now reads “Stop” " + "and the status text reads “Searching...”.") + _stop_quietly(ax) + + assert after_title == "Stop", "the 'Search' button did not become 'Stop'" + assert ks.sw_button(ax, "Search") is None or after_title == "Stop" + assert kit.rb_flip(before_title, after_title) + assert before_status == "" or before_status.strip() == "", \ + "status line was not empty before the first search" + assert re.match(r"^(Searching\.\.\.|Found \d+ items)", after_status), \ + "status line did not report the running search, got %r" % after_status + assert title is not None, "could not read the search window title" + assert kit.rb_value(title, "“Automator” on %s - KatSearch" % volume) + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="pressing 'Stop' flips the button title Stop→Search and the status " + "line gains '(cancelled)'") + def test_stop_button_cancels_search(self, ax): + win = ks.rb_enter_search_window(ax) + assert win is not None, "File > New Search Window did not open a search window" + ks.run_search(ax, "Automator", w=win, stop=False) + + before_title = _action_button_title(ax) + before_status = ks.status_text(ax) or "" + assert before_title == "Stop", "the action button is not titled 'Stop' while searching" + assert "(cancelled)" not in before_status + + assert ks.stop_search(ax), "pressing the 'Stop' button failed" + ks.wait_until(lambda: "(cancelled)" in (ks.status_text(ax) or ""), timeout=6.0) + after_title = _action_button_title(ax) + after_status = ks.status_text(ax) or "" + + assert after_title == "Search", "the 'Stop' button did not turn back into 'Search'" + assert kit.rb_flip(before_title, after_title) + assert "(cancelled)" in after_status, \ + "status line did not report the cancellation, got %r" % after_status + assert kit.rb_flip(before_status, after_status) + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="the 'Search' button is enabled with query text, enabled=False when the " + "search field is emptied, and enabled again after re-typing") + def test_search_button_enable_gating(self, ax): + win = ks.rb_enter_search_window(ax) + assert win is not None, "File > New Search Window did not open a search window" + + assert ks.set_search_text(ax, "Automator"), "could not type into the search field" + time.sleep(0.4) + with_text = _enabled(ax, ks.sw_button(ax, "Search")) + + ks.set_search_text(ax, "") + time.sleep(0.5) + emptied = _enabled(ax, ks.sw_button(ax, "Search")) + + ks.set_search_text(ax, "Automator") + time.sleep(0.5) + retyped = _enabled(ax, ks.sw_button(ax, "Search")) + + assert with_text is True, "'Search' was not enabled with text in the field" + assert emptied is False, "'Search' stayed enabled with an empty query" + assert retyped is True, "'Search' did not re-enable after re-typing" + assert kit.rb_flip(with_text, emptied) + assert kit.rb_flip(emptied, retyped) + + @pytest.mark.rb(depth=1, jump_kind="reach", + expect="AXShowMenu on the 'action' gear button drops a menu containing " + "menu_item|Case Sensitive plus Skip Package Contents / Skip Invisible " + "Files / Skip System Folder") + def test_action_gear_button_opens_options_menu(self, ax): + win = ks.rb_enter_search_window(ax) + assert win is not None, "File > New Search Window did not open a search window" + gear = ks.sw_button(ax, "action") + assert gear is not None, "search window has no 'action' gear button" + + before = ks.ks_showing(ax) + assert "menu_item|Case Sensitive" not in before + items = ks.rb_enter_options_menu(ax, win) + time.sleep(0.5) + after = ks.ks_showing(ax) + names = ks.item_names(items) if items else [] + ks.screenshot_assert( + "buttons_action_gear_button_opens_options_menu", + "A small drop-down menu dropped from the gear/action button of the KatSearch " + "search window listing “Case Sensitive”, “Skip Package Contents”, " + "“Skip Invisible Files” and “Skip System Folder”.") + ks.close_menus() + + assert kit.rb_reach(before, after, target="menu_item|Case Sensitive") + for expected in ("Case Sensitive", "Skip Package Contents", + "Skip Invisible Files", "Skip System Folder"): + assert expected in names, "advanced-options menu is missing %r" % expected + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="the search window 'lock' button exists with AXHelp " + "'Authenticate to search with root privileges'") + def test_lock_button_advertises_root_authentication(self, ax): + win = ks.rb_enter_search_window(ax) + assert win is not None, "File > New Search Window did not open a search window" + lock = ks.sw_button(ax, "lock") + assert lock is not None, "search window has no 'lock' button" + # NEVER pressed: it raises the macOS admin auth prompt (recon ## APP NEVER TOUCH). + help_text = _help(ax, lock) + assert help_text is not None, "could not read AXHelp of the 'lock' button" + assert kit.rb_value(help_text.strip(), + "Authenticate to search with root privileges") + assert _enabled(ax, lock) is True, "'lock' button is not enabled" + + +# --------------------------------------------------------------------------- +# results-table sort-header buttons +# --------------------------------------------------------------------------- + +class TestSortHeaderButtons: + + @pytest.mark.rb(depth=2, jump_kind="transition", + expect="the first press of the 'Items' sort header orders row names " + "DESCENDING and the second press orders them ASCENDING") + def test_items_sort_header_toggles_direction(self, ax): + win = ks.rb_enter_search_window(ax) + assert win is not None, "File > New Search Window did not open a search window" + status = ks.run_search(ax, "Automator", w=win) + assert status is not None + names0 = ks.row_names(ax, win) or [] + assert len(names0) >= 2, "search produced too few rows to sort (%d)" % len(names0) + + header = ks.sw_button(ax, "Items") + assert header is not None, "no 'Items' sort header" + assert ks.role_description(ax, header) == "sort button" + assert _press(ax, header), "AXPress on the 'Items' sort header failed" + time.sleep(1.0) + descending = ks.row_names(ax, win) or [] + + header = ks.sw_button(ax, "Items") # re-read: the element may have gone stale + assert header is not None + assert _press(ax, header), "second AXPress on the 'Items' sort header failed" + time.sleep(1.0) + ascending = ks.row_names(ax, win) or [] + + ks.screenshot_assert( + "buttons_items_sort_header_toggles_direction", + "The results table lists rows whose names contain “Automator” with icons, a Kind " + "column (Application / Unix Executable File …), a date and a size; the bottom " + "status line reads “Found N items (cancelled)” and the rows are sorted by name in " + "ascending order after two presses of the “Items” column header.") + + key = lambda s: (s or "").lower() + assert len(descending) >= 2, "rows vanished after the first sort press" + assert len(ascending) >= 2, "rows vanished after the second sort press" + assert descending == sorted(descending, key=key, reverse=True), \ + "first 'Items' press did not sort names descending: %r" % (descending[:5],) + assert ascending == sorted(ascending, key=key), \ + "second 'Items' press did not sort names ascending: %r" % (ascending[:5],) + if len(set(key(n) for n in ascending)) >= 2: + assert kit.rb_flip("|".join(descending), "|".join(ascending)) + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="the search window exposes exactly the sort buttons " + "['Items','Kind','Date Modified','Size'] left→right, each with " + "roleDescription 'sort button'") + def test_default_sort_headers_are_sort_buttons(self, ax): + win = ks.rb_enter_search_window(ax) + assert win is not None, "File > New Search Window did not open a search window" + headers = list(ks.sort_headers(ax, win) or []) + assert kit.rb_value(headers, ["Items", "Kind", "Date Modified", "Size"]) + for name in headers: + btn = ks.sw_button(ax, name) + assert btn is not None, "sort header %r not reachable as a button" % name + assert ks.role_description(ax, btn) == "sort button", \ + "%r is not a 'sort button'" % name + assert _enabled(ax, btn) is True, "sort header %r is disabled" % name + + +# --------------------------------------------------------------------------- +# preferences toolbar buttons (pane switching) +# --------------------------------------------------------------------------- + +# --------------------------------------------------------------------------- +# preferences buttons that must never be pressed (existence + exact label) +# --------------------------------------------------------------------------- + +# --------------------------------------------------------------------------- +# buttons that only exist once another surface is revealed +# --------------------------------------------------------------------------- + +class TestRevealedButtons: + + @pytest.mark.rb(depth=1, jump_kind="reach", + expect="Action > Show Filter reveals button|search together with the " + "'Filter...' placeholder search field") + def test_filter_magnifier_button_appears_with_filter_field(self, ax): + win = ks.rb_enter_search_window(ax) + assert win is not None, "File > New Search Window did not open a search window" + assert ks.filter_field(ax) is None, "the filter field was visible before Show Filter" + before = ks.ks_showing(ax) + assert "button|search" not in before + assert ks.pick_menu_item(ax, "Action", "Show Filter"), \ + "Action > Show Filter could not be activated" + time.sleep(0.8) + after = ks.ks_showing(ax) + assert kit.rb_reach(before, after, target="button|search") + assert "placeholder|Filter..." in after, "the 'Filter...' placeholder did not appear" + assert ks.filter_field(ax) is not None, "ks.filter_field still reports no filter field" + + @pytest.mark.rb(depth=2, jump_kind="reach", + expect="File > Save… after a search drops sheet|save carrying both " + "button|Save and button|Cancel") + def test_save_sheet_exposes_save_and_cancel_buttons(self, ax): + win = ks.rb_enter_search_window(ax) + assert win is not None, "File > New Search Window did not open a search window" + ks.run_search(ax, "Automator", w=win) + assert (ks.row_names(ax, win) or []), "the search produced no results to save" + before = ks.ks_showing(ax) + sheet = ks.rb_enter_save_sheet(ax, win) + assert sheet is not None, "File > Save… did not drop the save sheet" + time.sleep(0.6) + after = ks.ks_showing(ax) + names = [_name(b) for b in _buttons_under(ax, sheet)] + _dismiss_sheet() + + assert kit.rb_reach(before, after, target="button|Cancel") + assert "button|Save" in after, "the save sheet has no 'Save' button" + assert "sheet|save" in after, "no sheet|save in the AX snapshot" + # NEVER pressed: Save would write a file; the sheet is dismissed with Escape. + assert "Save" in names, "no 'Save' button inside sheet 'save': %r" % (names,) + assert "Cancel" in names, "no 'Cancel' button inside sheet 'save': %r" % (names,) + + +# --------------------------------------------------------------------------- +# window title-bar buttons +# --------------------------------------------------------------------------- + +class TestWindowTitleBarButtons: + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="on the intro window the close title-bar button is enabled=True while " + "the minimize and zoom buttons are enabled=False") + def test_intro_window_titlebar_button_states(self, ax): + win = ks.intro_window(ax) + assert win is not None, "intro window is not present at launch" + found = {} + for btn in _buttons_under(ax, win): + desc = (ks.role_description(ax, btn) or "").lower() + if not desc: + continue + if "close" in desc: + found.setdefault("close", btn) + elif "minimi" in desc: + found.setdefault("minimize", btn) + elif "zoom" in desc or "full screen" in desc or "maximi" in desc: + found.setdefault("zoom", btn) + assert "close" in found, "no close title-bar button on the intro window" + assert "minimize" in found, "no minimize title-bar button on the intro window" + assert "zoom" in found, "no zoom/full-screen title-bar button on the intro window" + # The close button is read only, never pressed. + observed = [_enabled(ax, found["close"]), + _enabled(ax, found["minimize"]), + _enabled(ax, found["zoom"])] + assert kit.rb_value(observed, [True, False, False]) diff --git a/macos/sveinbjornt-katsearch/tests/test_ax_computation.py b/macos/sveinbjornt-katsearch/tests/test_ax_computation.py new file mode 100644 index 0000000000000000000000000000000000000000..30a13868b113502263f5e4b50fd45a2cf3c9d1d8 --- /dev/null +++ b/macos/sveinbjornt-katsearch/tests/test_ax_computation.py @@ -0,0 +1,814 @@ +"""AX computation tests for KatSearch — query input -> observed search output.""" + +import os +import re +import sys +import time + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +import pytest + +import ks_helpers as ks +import rb_testgen_kit as kit + +# --------------------------------------------------------------------------- +# constants derived from recon ## COMPUTATION / ## TEXT (all OBSERVED values) +# --------------------------------------------------------------------------- + +TERM = "Automator" # the only reliably findable term: the default target + # volume is the sealed system volume, /Users is NOT + # searchable, so fixture files are not findable. +ALT_TERM = "zebra123" # yields no results -> used only for the save prefill +FILTER_HIT = "Automator.app" +FILTER_MISS = "zzzznope" + +DEFAULT_HEADERS = ["Items", "Kind", "Date Modified", "Size"] + +# status-line shapes (counts vary run to run because the scan is cancelled mid-stream) +RE_FOUND_ITEMS = r"^Found\s+\d+\s+items" +RE_FOUND_FOLDERS = r"^Found\s+\d+\s+folders" +RE_FOUND_FILES = r"^Found\s+\d+\s+files" + +# cell formats (recon worked example 11): date "M/D/YY, H:MM AM", size "-" or "782 KB" +RE_DATE_CELL = r"\d{1,2}/\d{1,2}/\d{2}," +RE_SIZE_CELL = r"^(?:Zero|[\d.,]+)\s?(?:bytes|byte|KB|MB|GB|TB)$" + +# kinds that can only belong to a plain file — must never show up in `folders` mode +PLAIN_FILE_KINDS = { + "Unix Executable File", + "AppleScript Script Suite", + "AppleScript Script", + "Symbolic Link", + "Document", + "Apple icon image", + "Plain Text Document", + "Property List", +} + +# NBSP / narrow-NBSP / figure-space / thin-space, which macOS formatters sprinkle into +# dates and byte counts. +_ODD_SPACES = "".join(chr(c) for c in (0x00A0, 0x2007, 0x2009, 0x202F)) + + +# --------------------------------------------------------------------------- +# tiny local utilities (no AX knowledge of their own — everything goes via ks) +# --------------------------------------------------------------------------- + +def _norm(s): + """Normalise a UI string: fold exotic spaces to ASCII and strip.""" + if s is None: + return "" + if not isinstance(s, str): + s = str(s) + for ch in _ODD_SPACES: + s = s.replace(ch, " ") + return s.strip() + + +def _token(text, pattern, label): + """Collapse a run-to-run-varying string into a stable token for kit.rb_value.""" + return label if re.match(pattern, _norm(text)) else "MISMATCH(%r)" % (_norm(text),) + + +def _dismiss(n=1): + """ks.close_menus(n) with a signature-tolerant fallback.""" + try: + ks.close_menus(n) + return + except TypeError: + pass + except Exception: + return + for _ in range(max(1, n)): + try: + ks.close_menus() + except Exception: + return + + +def _press(ax, el): + """AXPress an element through whatever press affordance the helpers expose. + + `el` may be a raw AXUIElement, a wrapper object, or an id/dict handle — try every + plausible shape rather than betting on one framework's internals. + """ + if el is None: + return False + + handles = [el] + for attr in ("id", "element_id", "uid"): + h = None + try: + h = el.get(attr) if isinstance(el, dict) else getattr(el, attr, None) + except Exception: + h = None + if h is not None and h not in handles: + handles.append(h) + + for name in ("press", "press_element", "press_button", "_press", "click_element", "do_press"): + fn = getattr(ks, name, None) + if callable(fn): + for h in handles: + try: + if fn(ax, h) is not False: + return True + except Exception: + pass + for name in ("press", "press_element", "click_element", "do_press", "click"): + fn = getattr(ax, name, None) + if callable(fn): + for h in handles: + try: + if fn(h) is not False: + return True + except Exception: + pass + for name in ("perform_action", "do_action", "action", "perform"): + fn = getattr(ax, name, None) + if callable(fn): + for h in handles: + try: + if fn(h, "AXPress") is not False: + return True + except Exception: + pass + for name in ("press", "click", "AXPress", "perform_press"): + fn = getattr(el, name, None) + if callable(fn): + try: + fn() + return True + except Exception: + pass + try: + from ApplicationServices import AXUIElementPerformAction + for attr in ("ref", "element", "el", "_el", "_ref", "uielement", "raw"): + raw = getattr(el, attr, None) + if raw is not None: + try: + if AXUIElementPerformAction(raw, "AXPress") == 0: + return True + except Exception: + pass + if AXUIElementPerformAction(el, "AXPress") == 0: + return True + except Exception: + pass + return False + + +def _names(ax): + return [_norm(n) for n in (ks.row_names(ax) or [])] + + +def _kinds(ax): + return [_norm(k) for k in (ks.row_kinds(ax) or []) if _norm(k)] + + +def _status(ax): + return _norm(ks.status_text(ax)) + + +def _rows(ax): + return list(ks.result_rows(ax) or []) + + +def _show_filter(ax): + """Action > Show Filter, then hand back the revealed filter field (or None).""" + picked = ks.pick_menu_item(ax, "Action", "Show Filter") + _dismiss(1) + time.sleep(0.4) + return picked, ks.filter_field(ax) + + +# =========================================================================== +# 1-6: the search engine itself (term + item-type + match-criterion modes) +# =========================================================================== + +class TestSearchCompute: + + @pytest.mark.rb( + depth=1, + jump_kind="value", + expect="status matches '^Found items' and every result row name contains 'automator'", + ) + def test_search_automator_default(self, ax): + w = ks.rb_enter_search_window(ax) + assert w is not None, "expected the search window after File > New Search Window, observed None" + + ks.run_search(ax, TERM) + status = _status(ax) + rows = _rows(ax) + names = _names(ax) + + assert len(rows) >= 1, ( + "expected >= 1 streamed result row for term %r, observed %d rows (status %r)" + % (TERM, len(rows), status) + ) + assert kit.rb_value(_token(status, RE_FOUND_ITEMS, "Found items"), "Found items"), ( + "expected the status line to match %r, observed %r" % (RE_FOUND_ITEMS, status) + ) + + offenders = [n for n in names if "automator" not in n.lower()] + ks.screenshot_assert( + "computation_search_automator_default", + "The KatSearch results table lists rows whose names all contain “Automator” " + "with file icons, a Kind column (Application / Unix Executable File …), a Date " + "Modified and a Size column; the bottom status line reads “Found N items " + "(cancelled)” and the title bar shows “Automator” on the volume.", + ) + assert kit.rb_value(str(len(offenders)), "0"), ( + "expected 0 row names without 'automator' (case-insensitive), observed %d offenders %r " + "out of %d names %r" % (len(offenders), offenders, len(names), names) + ) + + @pytest.mark.rb( + depth=1, + jump_kind="value", + expect="window title “Automator” on - KatSearch", + ) + def test_window_title_interpolates_term_and_volume(self, ax): + w = ks.rb_enter_search_window(ax) + assert w is not None, "expected the search window after File > New Search Window, observed None" + + popups = ks.sw_popups(ax) + assert popups and len(popups) >= 3, ( + "expected 3 query popups (item type / match criterion / target volume), observed %r" + % (popups,) + ) + volume = _norm(ks.popup_value(ax, popups[2])) + assert volume, "expected a non-empty target-volume popup value, observed %r" % (volume,) + + ks.run_search(ax, TERM) + titles = [_norm(t) for t in (ks.window_titles(ax) or [])] + candidates = [t for t in titles if "- KatSearch" in t] + observed = candidates[0] if candidates else ("titles=" + "|".join(titles)) + expected = "“%s” on %s - KatSearch" % (TERM, volume) + + ks.screenshot_assert( + "computation_window_title_after_search", + "The KatSearch search window title bar reads “Automator” on the volume name, " + "the results table below lists matching Automator rows, and the status line reads " + "“Found N items (cancelled)”.", + ) + assert kit.rb_value(observed, expected), ( + "expected the search window title %r (term + volume popup value %r), observed %r " + "(all window titles %r)" % (expected, volume, observed, titles) + ) + + @pytest.mark.rb( + depth=1, + jump_kind="value", + expect="with criterion 'name is', every result row name is exactly 'Automator'", + ) + def test_match_criterion_name_is_exact(self, ax): + w = ks.rb_enter_search_window(ax) + assert w is not None, "expected the search window after File > New Search Window, observed None" + + popups = ks.sw_popups(ax) + assert popups and len(popups) >= 2, ( + "expected >= 2 query popups in the search window, observed %r" % (popups,) + ) + switched = ks.switch_mode(ax, popups[1], "name is") + _dismiss(1) + assert switched, ( + "expected switch_mode(match-criterion popup, 'name is') to succeed, observed False" + ) + mode = _norm(ks.popup_value(ax, ks.sw_popups(ax)[1])) + assert mode == "name is", ( + "expected the match-criterion popup value 'name is', observed %r" % (mode,) + ) + + ks.run_search(ax, TERM) + status = _status(ax) + rows = _rows(ax) + names = _names(ax) + assert len(rows) >= 1, ( + "expected >= 1 exact-match row for 'name is' + %r, observed %d rows (status %r)" + % (TERM, len(rows), status) + ) + + offenders = [n for n in names if n != TERM] + assert kit.rb_value(str(len(offenders)), "0"), ( + "expected every row name to be exactly %r with criterion 'name is', observed %d " + "offenders %r out of %d names %r (status %r)" + % (TERM, len(offenders), offenders, len(names), names, status) + ) + + @pytest.mark.rb( + depth=1, + jump_kind="value", + expect="status matches '^Found folders' after switching the item-type popup to 'folders'", + ) + def test_item_type_folders_status(self, ax): + w = ks.rb_enter_search_window(ax) + assert w is not None, "expected the search window after File > New Search Window, observed None" + + popups = ks.sw_popups(ax) + assert popups, "expected the query popups in the search window, observed %r" % (popups,) + switched = ks.switch_mode(ax, popups[0], "folders") + _dismiss(1) + assert switched, "expected switch_mode(item-type popup, 'folders') to succeed, observed False" + mode = _norm(ks.popup_value(ax, ks.sw_popups(ax)[0])) + assert mode == "folders", "expected the item-type popup value 'folders', observed %r" % (mode,) + + ks.run_search(ax, TERM) + status = _status(ax) + rows = _rows(ax) + assert len(rows) >= 1, ( + "expected >= 1 folder row for %r in 'folders' mode, observed %d rows (status %r)" + % (TERM, len(rows), status) + ) + + ks.screenshot_assert( + "computation_item_type_folders", + "The KatSearch search window has its item-type popup set to “folders”; the " + "results table lists only folder-like rows (Application / Folder / Framework kinds) " + "whose names contain “Automator”, and the status line reads “Found N " + "folders (cancelled)”.", + ) + assert kit.rb_value(_token(status, RE_FOUND_FOLDERS, "Found folders"), "Found folders"), ( + "expected the status line to match %r (the item-type popup title is interpolated), " + "observed %r" % (RE_FOUND_FOLDERS, status) + ) + + @pytest.mark.rb( + depth=1, + jump_kind="value", + expect="status matches '^Found files' after switching the item-type popup to 'files'", + ) + def test_item_type_files_status(self, ax): + w = ks.rb_enter_search_window(ax) + assert w is not None, "expected the search window after File > New Search Window, observed None" + + popups = ks.sw_popups(ax) + assert popups, "expected the query popups in the search window, observed %r" % (popups,) + switched = ks.switch_mode(ax, popups[0], "files") + _dismiss(1) + assert switched, "expected switch_mode(item-type popup, 'files') to succeed, observed False" + mode = _norm(ks.popup_value(ax, ks.sw_popups(ax)[0])) + assert mode == "files", "expected the item-type popup value 'files', observed %r" % (mode,) + + ks.run_search(ax, TERM) + status = _status(ax) + rows = _rows(ax) + kinds = _kinds(ax) + assert len(rows) >= 1, ( + "expected >= 1 file row for %r in 'files' mode, observed %d rows (status %r)" + % (TERM, len(rows), status) + ) + assert "Folder" not in set(kinds), ( + "expected no bare 'Folder' kind in 'files' mode, observed kinds %r" + % (sorted(set(kinds)),) + ) + assert kit.rb_value(_token(status, RE_FOUND_FILES, "Found files"), "Found files"), ( + "expected the status line to match %r (the item-type popup title is interpolated), " + "observed %r" % (RE_FOUND_FILES, status) + ) + + @pytest.mark.rb( + depth=1, + jump_kind="value", + expect="'folders' mode kinds differ from 'files' mode kinds and contain 0 plain-file kinds", + ) + def test_folders_vs_files_kind_sets_differ(self, ax): + w = ks.rb_enter_search_window(ax) + assert w is not None, "expected the search window after File > New Search Window, observed None" + + popups = ks.sw_popups(ax) + assert popups, "expected the query popups in the search window, observed %r" % (popups,) + assert ks.switch_mode(ax, popups[0], "folders"), ( + "expected switch_mode(item-type popup, 'folders') to succeed, observed False" + ) + _dismiss(1) + ks.run_search(ax, TERM) + folder_status = _status(ax) + folder_kinds = set(_kinds(ax)) + assert folder_kinds, ( + "expected >= 1 folder-mode row kind for %r, observed none (status %r)" + % (TERM, folder_status) + ) + + popups = ks.sw_popups(ax) + assert popups, "expected the query popups to be re-enabled after Stop, observed %r" % (popups,) + assert ks.switch_mode(ax, popups[0], "files"), ( + "expected switch_mode(item-type popup, 'files') to succeed, observed False" + ) + _dismiss(1) + ks.run_search(ax, TERM) + file_status = _status(ax) + file_kinds = set(_kinds(ax)) + assert file_kinds, ( + "expected >= 1 file-mode row kind for %r, observed none (status %r)" + % (TERM, file_status) + ) + + leak = sorted(folder_kinds & PLAIN_FILE_KINDS) + assert kit.rb_value(str(len(leak)), "0"), ( + "expected 0 plain-file kinds among the 'folders' results, observed %d %r " + "(folder kinds %r, status %r)" + % (len(leak), leak, sorted(folder_kinds), folder_status) + ) + + differ = "differ" if folder_kinds != file_kinds else "identical" + assert kit.rb_value(differ, "differ"), ( + "expected the 'folders' kind set to differ from the 'files' kind set, observed " + "%s: folders=%r (status %r) files=%r (status %r)" + % (differ, sorted(folder_kinds), folder_status, sorted(file_kinds), file_status) + ) + + +# =========================================================================== +# 7-9: the in-place results filter (post-filter arithmetic on the result set) +# =========================================================================== + +class TestFilterCompute: + + @pytest.mark.rb( + depth=1, + jump_kind="value", + expect="status 'Showing 1 of items' with exactly 1 row named 'Automator.app'", + ) + def test_filter_single_match(self, ax): + w = ks.rb_enter_search_window(ax) + assert w is not None, "expected the search window after File > New Search Window, observed None" + + ks.run_search(ax, TERM) + base_status = _status(ax) + assert len(_rows(ax)) >= 1, ( + "expected >= 1 result row before filtering, observed 0 (status %r)" % (base_status,) + ) + + picked, fld = _show_filter(ax) + assert picked, "expected Action > Show Filter to be pickable, observed pick_menu_item() == False" + assert fld is not None, ( + "expected the filter field (placeholder 'Filter...') after Action > Show Filter, observed None" + ) + assert ks.set_text(ax, fld, FILTER_HIT), ( + "expected to type %r into the filter field, observed set_text() == False" % (FILTER_HIT,) + ) + ks.wait_until(lambda: _status(ax).startswith("Showing"), timeout=6.0) + time.sleep(0.3) + + status = _status(ax) + rows = _rows(ax) + names = _names(ax) + + ks.screenshot_assert( + "computation_filter_single_match", + "A rounded search field with the placeholder “Filter...” is visible at the " + "bottom-left of the KatSearch window, the results table shows exactly one row named " + "“Automator.app”, and the status line reads “Showing 1 of N items”.", + ) + + shape = "Showing 1 of items" if ( + status.startswith("Showing 1 of") and status.endswith("items") + ) else "MISMATCH(%r)" % (status,) + assert kit.rb_value(shape, "Showing 1 of items"), ( + "expected the status line to start with 'Showing 1 of' and end with 'items' after " + "filtering by %r, observed %r (unfiltered status was %r)" + % (FILTER_HIT, status, base_status) + ) + assert kit.rb_value(str(len(rows)), "1"), ( + "expected exactly 1 visible row after filtering by %r, observed %d rows %r (status %r)" + % (FILTER_HIT, len(rows), names, status) + ) + assert kit.rb_value(names[0] if names else "", FILTER_HIT), ( + "expected the single remaining row name to be %r, observed %r (status %r)" + % (FILTER_HIT, names, status) + ) + + @pytest.mark.rb( + depth=1, + jump_kind="value", + expect="status 'Showing 0 of items' with 0 rows for the filter 'zzzznope'", + ) + def test_filter_no_match(self, ax): + w = ks.rb_enter_search_window(ax) + assert w is not None, "expected the search window after File > New Search Window, observed None" + + ks.run_search(ax, TERM) + base_status = _status(ax) + assert len(_rows(ax)) >= 1, ( + "expected >= 1 result row before filtering, observed 0 (status %r)" % (base_status,) + ) + + picked, fld = _show_filter(ax) + assert picked, "expected Action > Show Filter to be pickable, observed pick_menu_item() == False" + assert fld is not None, ( + "expected the filter field (placeholder 'Filter...') after Action > Show Filter, observed None" + ) + assert ks.set_text(ax, fld, FILTER_MISS), ( + "expected to type %r into the filter field, observed set_text() == False" % (FILTER_MISS,) + ) + ks.wait_until(lambda: _status(ax).startswith("Showing"), timeout=6.0) + time.sleep(0.3) + + status = _status(ax) + rows = _rows(ax) + + shape = "Showing 0 of items" if ( + status.startswith("Showing 0 of") and status.endswith("items") + ) else "MISMATCH(%r)" % (status,) + assert kit.rb_value(shape, "Showing 0 of items"), ( + "expected the status line to start with 'Showing 0 of' and end with 'items' after " + "filtering by %r, observed %r (unfiltered status was %r)" + % (FILTER_MISS, status, base_status) + ) + assert kit.rb_value(str(len(rows)), "0"), ( + "expected 0 visible rows after filtering by %r, observed %d rows %r (status %r)" + % (FILTER_MISS, len(rows), _names(ax), status) + ) + + + +# =========================================================================== +# 10-11: the save-sheet filename is COMPUTED from the search field text +# =========================================================================== + +class TestSaveNamePrefill: + + @pytest.mark.rb( + depth=2, + jump_kind="value", + expect="save sheet filename field == 'SearchResults-Automator.txt'", + ) + def test_save_sheet_prefill_from_term(self, ax): + w = ks.rb_enter_search_window(ax) + assert w is not None, "expected the search window after File > New Search Window, observed None" + + ks.run_search(ax, TERM) + status = _status(ax) + assert len(_rows(ax)) >= 1, ( + "expected >= 1 result row (File > Save… is disabled without results), observed 0 " + "(status %r)" % (status,) + ) + + sheet = ks.rb_enter_save_sheet(ax) + values = ( + [_norm(v) for v in (ks.sheet_field_values(ax, sheet) or [])] + if sheet is not None else [] + ) + candidates = [v for v in values if v.startswith("SearchResults")] + observed = candidates[0] if candidates else ( + "sheet=None" if sheet is None else ("fields=" + "|".join(values)) + ) + expected = "SearchResults-%s.txt" % TERM + + if sheet is not None: + ks.screenshot_assert( + "computation_save_sheet_prefill", + "A macOS save sheet is dropped over the KatSearch search window with " + "“Save As:” prefilled “SearchResults-Automator.txt”, a Where " + "popup, and Cancel / Save buttons.", + ) + _dismiss(2) + + assert kit.rb_value(observed, expected), ( + "expected the save-sheet filename field to be %r after searching %r, observed %r " + "(all sheet field values %r)" % (expected, TERM, observed, values) + ) + + @pytest.mark.rb( + depth=2, + jump_kind="value", + expect="save sheet filename field == 'SearchResults-zebra123.txt' after retyping the query field", + ) + def test_save_sheet_prefill_tracks_field_text(self, ax): + w = ks.rb_enter_search_window(ax) + assert w is not None, "expected the search window after File > New Search Window, observed None" + + # A real search first: File > Save… only becomes enabled once results exist. `zebra123` + # itself matches nothing, so search `Automator` and then retype the query field — the + # prefill must follow the FIELD text, proving it is computed and not hardcoded. + ks.run_search(ax, TERM) + status = _status(ax) + assert len(_rows(ax)) >= 1, ( + "expected >= 1 result row (File > Save… is disabled without results), observed 0 " + "(status %r)" % (status,) + ) + + fld = ks.search_field(ax) + assert fld is not None, "expected the search text field in the search window, observed None" + assert ks.set_text(ax, fld, ALT_TERM), ( + "expected to retype the query field as %r, observed set_text() == False" % (ALT_TERM,) + ) + time.sleep(0.4) + + sheet = ks.rb_enter_save_sheet(ax) + values = ( + [_norm(v) for v in (ks.sheet_field_values(ax, sheet) or [])] + if sheet is not None else [] + ) + candidates = [v for v in values if v.startswith("SearchResults")] + observed = candidates[0] if candidates else ( + "sheet=None" if sheet is None else ("fields=" + "|".join(values)) + ) + expected = "SearchResults-%s.txt" % ALT_TERM + _dismiss(2) + + assert kit.rb_value(observed, expected), ( + "expected the save-sheet filename to be COMPUTED from the query field text (%r -> %r), " + "observed %r (all sheet field values %r)" % (ALT_TERM, expected, observed, values) + ) + + +# =========================================================================== +# 12-13: the per-row cell computation (4 columns, formatted date + size) +# =========================================================================== + +class TestRowCellCompute: + + @pytest.mark.rb( + depth=1, + jump_kind="value", + expect="every result row yields 4 cell texts and the columns are Items/Kind/Date Modified/Size", + ) + def test_row_has_four_cells_and_four_columns(self, ax): + w = ks.rb_enter_search_window(ax) + assert w is not None, "expected the search window after File > New Search Window, observed None" + + ks.run_search(ax, TERM) + status = _status(ax) + rows = _rows(ax) + assert len(rows) >= 1, ( + "expected >= 1 result row for %r, observed 0 (status %r)" % (TERM, status) + ) + + sampled = rows[:5] + cell_counts = [len(list(ks.row_cell_texts(ax, row) or [])) for row in sampled] + wrong = [n for n in cell_counts if n != 4] + assert kit.rb_value(str(len(wrong)), "0"), ( + "expected every sampled result row to expose exactly 4 cell texts " + "(name, kind, date, size), observed cell counts %r for the first %d rows (names %r)" + % (cell_counts, len(sampled), _names(ax)[:5]) + ) + + headers = [_norm(h) for h in (ks.sort_headers(ax) or [])] + assert kit.rb_value("|".join(headers), "|".join(DEFAULT_HEADERS)), ( + "expected the 4 default columns %r, observed %r" % (DEFAULT_HEADERS, headers) + ) + + @pytest.mark.rb( + depth=1, + jump_kind="value", + expect="date cell matches 'M/D/YY,' and size cell is '-' or a human-friendly size like '782 KB'", + ) + def test_date_and_size_cell_formats(self, ax): + w = ks.rb_enter_search_window(ax) + assert w is not None, "expected the search window after File > New Search Window, observed None" + + ks.run_search(ax, TERM) + status = _status(ax) + rows = _rows(ax) + assert len(rows) >= 1, ( + "expected >= 1 result row for %r, observed 0 (status %r)" % (TERM, status) + ) + + checked = 0 + bad_dates = [] + bad_sizes = [] + seen = [] + for row in rows[:6]: + cells = [_norm(c) for c in (ks.row_cell_texts(ax, row) or [])] + if len(cells) < 4: + continue + date_cell, size_cell = cells[2], cells[3] + seen.append((date_cell, size_cell)) + checked += 1 + if not re.search(RE_DATE_CELL, date_cell): + bad_dates.append(date_cell) + if not (size_cell == "-" or re.match(RE_SIZE_CELL, size_cell)): + bad_sizes.append(size_cell) + + assert checked >= 1, ( + "expected >= 1 result row exposing 4 cells to check date/size formatting, observed %d " + "(status %r)" % (checked, status) + ) + assert kit.rb_value(str(len(bad_dates)), "0"), ( + "expected every date cell to match %r, observed %d bad values %r out of %d checked " + "(date/size pairs %r)" % (RE_DATE_CELL, len(bad_dates), bad_dates, checked, seen) + ) + assert kit.rb_value(str(len(bad_sizes)), "0"), ( + "expected every size cell to be '-' or a human-friendly size matching %r, observed %d " + "bad values %r out of %d checked (date/size pairs %r)" + % (RE_SIZE_CELL, len(bad_sizes), bad_sizes, checked, seen) + ) + + +# =========================================================================== +# 14-15: sort computation + status-line progression +# =========================================================================== + +class TestSortAndStatusCompute: + + @pytest.mark.rb( + depth=1, + jump_kind="value", + expect="row names sorted DESCENDING after 1 press of the 'Items' header and ASCENDING after 2", + ) + def test_items_header_sorts_descending_then_ascending(self, ax): + w = ks.rb_enter_search_window(ax) + assert w is not None, "expected the search window after File > New Search Window, observed None" + + ks.run_search(ax, TERM) + status = _status(ax) + initial = _names(ax) + assert len(initial) >= 2, ( + "expected >= 2 result rows to prove sorting, observed %d (%r, status %r)" + % (len(initial), initial, status) + ) + + btn = ks.sw_button(ax, "Items") + assert btn is not None, "expected the 'Items' sort-header button, observed None" + assert _press(ax, btn), ( + "expected to AXPress the 'Items' sort header (1st press), observed failure" + ) + time.sleep(0.9) + desc = _names(ax) + desc_keys = [n.lower() for n in desc] + desc_ok = "descending" if desc_keys == sorted(desc_keys, reverse=True) else "unsorted" + + btn2 = ks.sw_button(ax, "Items") + assert btn2 is not None, ( + "expected the 'Items' sort-header button for the 2nd press, observed None" + ) + assert _press(ax, btn2), ( + "expected to AXPress the 'Items' sort header (2nd press), observed failure" + ) + time.sleep(0.9) + asc = _names(ax) + asc_keys = [n.lower() for n in asc] + asc_ok = "ascending" if asc_keys == sorted(asc_keys) else "unsorted" + + ks.screenshot_assert( + "computation_items_header_sort", + "The KatSearch results table is sorted by the Items column — the row names are in " + "ascending alphabetical order after two presses of the “Items” sort header " + "— with the Items / Kind / Date Modified / Size headers visible and the status " + "line reading “Found N items (cancelled)”.", + ) + assert kit.rb_value(desc_ok, "descending"), ( + "expected the row names to be sorted DESCENDING after 1 press of the 'Items' header, " + "observed %s: %r (discovery order was %r)" % (desc_ok, desc, initial) + ) + assert kit.rb_value(asc_ok, "ascending"), ( + "expected the row names to be sorted ASCENDING after 2 presses of the 'Items' header, " + "observed %s: %r (after 1 press it was %r)" % (asc_ok, asc, desc) + ) + + @pytest.mark.rb( + depth=1, + jump_kind="transition", + expect="status progresses from 'Searching...' to 'Found items'", + ) + def test_status_progresses_searching_then_found(self, ax): + w = ks.rb_enter_search_window(ax) + assert w is not None, "expected the search window after File > New Search Window, observed None" + + assert ks.set_search_text(ax, TERM), ( + "expected to type %r into the search field, observed set_search_text() == False" % (TERM,) + ) + started = _press(ax, ks.sw_button(ax, "Search")) + if not started: + started = bool(ks.pick_menu_item(ax, "Action", "Search")) + _dismiss(1) + assert started, ( + "expected to be able to start the search (Search button AXPress or Action > Search), " + "observed failure" + ) + + seen = [] + + def _poll(): + s = _status(ax) + if s and (not seen or seen[-1] != s): + seen.append(s) + return s.startswith("Found") + + _poll() + ks.wait_until(_poll, timeout=14.0) + ks.stop_search(ax) + + searching = next((s for s in seen if s.startswith("Searching")), None) + found = next((s for s in seen if s.startswith("Found")), None) + before = searching if searching is not None else ("seen=" + "|".join(seen)) + after = found if found is not None else ("seen=" + "|".join(seen)) + + assert searching is not None, ( + "expected a 'Searching...' status while the search ran, observed status sequence %r" + % (seen,) + ) + assert found is not None, ( + "expected a 'Found items' status once results streamed in, observed status " + "sequence %r" % (seen,) + ) + assert kit.rb_flip(before, after), ( + "expected the status line to flip from %r to %r, observed sequence %r" + % (before, after, seen) + ) + assert re.match(RE_FOUND_ITEMS, after), ( + "expected the settled status to match %r, observed %r (sequence %r)" + % (RE_FOUND_ITEMS, after, seen) + ) diff --git a/macos/sveinbjornt-katsearch/tests/test_ax_menus.py b/macos/sveinbjornt-katsearch/tests/test_ax_menus.py new file mode 100644 index 0000000000000000000000000000000000000000..667acb1624a41759fee9169d612cd548e7d20558 --- /dev/null +++ b/macos/sveinbjornt-katsearch/tests/test_ax_menus.py @@ -0,0 +1,935 @@ +"""AX menu tests for KatSearch — menu structure, item state and item activation.""" + +import os +import sys +import time + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +import pytest + +import ks_helpers as ks +import rb_testgen_kit as kit + + +# -------------------------------------------------------------------------- +# Expected menu content (every list below is copied from the recon report's +# ## MENUS section — i.e. observed on the running official app). +# -------------------------------------------------------------------------- + +MENU_BAR = ["KatSearch", "File", "Edit", "View", "Action", "Window", "Help"] + +KATSEARCH_ITEMS = [ + "About KatSearch", + "KatSearch License", + "Check for Updates…", + "Settings…", + "Visit KatSearch Website", + "Make a Donation", + "Services", + "Hide KatSearch", + "Hide Others", + "Show All", + "Quit KatSearch", +] + +FILE_ITEMS = [ + "New Search Window", + "Open Recent", + "Close", + "Close All", + "Save…", + "Page Setup…", + "Print…", +] + +EDIT_ITEMS = [ + "Undo", + "Redo", + "Cut", + "Copy", + "Paste", + "Select All", + "Transformations", + "Speech", +] + +EDIT_FIND_ITEMS = [ + "Find…", + "Find and Replace…", + "Find Next", + "Find Previous", + "Use Selection for Find", + "Jump to Selection", +] + +VIEW_ITEMS = [ + "Show Path Bar", + "Show Full Path", + "Show Kind", + "Show Size", + "Show Date Created", + "Show Date Modified", + "Show Date Accessed", + "Show User:Group", + "Show Permissions", + "Show UTI", + "Show MIME Type", + "Show HFS File Type", + "Show Creator Type", + "Enter Full Screen", +] + +VIEW_DEFAULT_MARKS = { + "Show Path Bar": "✓", + "Show Full Path": None, + "Show Kind": "✓", + "Show Size": "✓", + "Show Date Created": None, + "Show Date Modified": "✓", + "Show Date Accessed": None, + "Show User:Group": None, + "Show Permissions": None, + "Show UTI": None, + "Show MIME Type": None, + "Show HFS File Type": None, + "Show Creator Type": None, +} + +ACTION_ITEMS = [ + "Search", + "Open", + "Show in Finder", + "Get Info", + "Quick Look", + "Move to Trash", + "Show Selected Item(s)", + "Show Filter", + "Hide Filter", + "Authenticate", +] + +# no search window open -> everything but Authenticate is disabled +ACTION_DEFAULT_ENABLED = { + "Search": False, + "Open": False, + "Show in Finder": False, + "Get Info": False, + "Quick Look": False, + "Move to Trash": False, + "Show Selected Item(s)": False, + "Show Filter": False, + "Hide Filter": False, + "Authenticate": True, +} + +# the six item actions that only light up once a results row is selected +ACTION_SELECTION_ITEMS = [ + "Open", + "Show in Finder", + "Get Info", + "Quick Look", + "Move to Trash", + "Show Selected Item(s)", +] + +WINDOW_ITEMS = [ + "Minimize", + "Minimize All", + "Zoom", + "Zoom All", + "Bring All to Front", + "Arrange in Front", +] + +HELP_ITEMS = [ + "KatSearch Website", + "GitHub Project Page", + "Make a Donation", + "searchfs Man Page", + "KatSearch Help", +] + +# results-table header contextual menu — note "Show Uniform Type Identifier" +# instead of the View menu's "Show UTI" +COLUMN_MENU_MARKS = { + "Show Kind": "✓", + "Show Size": "✓", + "Show Date Created": None, + "Show Date Modified": "✓", + "Show Date Accessed": None, + "Show User:Group": None, + "Show Permissions": None, + "Show Uniform Type Identifier": None, + "Show MIME Type": None, + "Show HFS File Type": None, + "Show Creator Type": None, +} + +ROW_MENU_ITEMS = [ + "Open", + "Open With", + "Show Package Contents", + "Move to Trash", + "Get Info", + "Show in Finder", + "Quick Look", + "Share", +] + +OPTIONS_ITEMS = [ + "Case Sensitive", + "Skip Package Contents", + "Skip Invisible Files", + "Skip System Folder", +] + +DEFAULT_HEADERS = ["Items", "Kind", "Date Modified", "Size"] +SEARCH_TERM = "Automator" +CHECK = "✓" + + +# -------------------------------------------------------------------------- +# small local utilities (naming/locating only — never framework internals) +# -------------------------------------------------------------------------- + +def _norm(s): + """Normalise a visible menu label: unify ellipsis/quote rendering.""" + return (s or "").replace("…", "...").replace("’", "'").strip() + + +def _names(items): + """Visible names of menu items, tolerant of helper return shapes.""" + try: + raw = list(ks.item_names(items) or []) + except Exception: + raw = [] + if not raw: + raw = [] + for it in (items or []): + n = None + for attr in ("name", "title", "label", "value"): + n = getattr(it, attr, None) + if isinstance(n, str) and n: + break + n = None + if n is None and isinstance(it, dict): + n = it.get("name") or it.get("title") or it.get("label") + raw.append(n or "") + return [(n or "") for n in raw] + + +def _real(names): + """Drop separators / unnamed entries.""" + return [n for n in names if n and n.strip() and n.strip() != "-"] + + +def _missing(names, expected): + have = set(_norm(n) for n in names) + return [e for e in expected if _norm(e) not in have] + + +def _element_id(el): + for attr in ("id", "element_id", "uid", "path"): + v = getattr(el, attr, None) + if v is not None: + return v + if isinstance(el, dict): + for k in ("id", "element_id", "uid", "path"): + if k in el: + return el[k] + return el + + +def _submenu_names(ax, items, parent_title): + """Visible names inside the submenu hanging off `parent_title`.""" + parent = ks.find_item(items, parent_title) + if parent is None: + return None + eid = _element_id(parent) + kids = [] + try: + kids = list(ks.elements_under(ax, eid, limit=200) or []) + except Exception: + kids = [] + names = _real(_names(kids)) + if not names: + try: + names = _real(list(ks.texts_under(ax, eid, limit=200) or [])) + except Exception: + names = [] + # the parent itself may be included by the walker — that is harmless + return names + + +def _enabled_any(ax, menu, *candidates): + """menu_item_enabled tolerant of ellipsis rendering ('Save…' vs 'Save...').""" + for cand in candidates: + try: + v = ks.menu_item_enabled(ax, menu, cand) + except Exception: + v = None + if v is not None: + return v + return None + + +def _marks_of(ax, items, expected_names): + """{name: mark} read straight off an already-open menu.""" + out = {} + for name in expected_names: + item = ks.find_item(items, name) + out[name] = ks.mark_of(ax, item) if item is not None else "" + return out + + +def _open(ax, menu): + """ks.open_menu + a loud assertion naming the menu that failed.""" + items = ks.open_menu(ax, menu) + assert items, "menu %r did not drop down / exposed no items" % menu + return items + + +# ========================================================================== +# A. MENU STRUCTURE +# ========================================================================== + +class TestMenuBarStructure: + + @pytest.mark.rb( + depth=0, + jump_kind="value", + expect="menu bar items are exactly ['KatSearch','File','Edit','View','Action','Window','Help'] (Apple menu excluded)", + ) + def test_menu_bar_has_exactly_the_app_menus(self, ax): + items = ks.menu_bar_items(ax) + assert items, "no application menu-bar items found (is the app in status-item mode?)" + titles = _real(_names(items)) + assert kit.rb_value([_norm(t) for t in titles], [_norm(t) for t in MENU_BAR]), ( + "menu bar titles are %r, expected %r" % (titles, MENU_BAR) + ) + + @pytest.mark.rb( + depth=1, + jump_kind="value", + expect="KatSearch menu drops down containing About KatSearch, KatSearch License, Check for Updates…, Settings…, Visit KatSearch Website, Make a Donation, Services, Hide KatSearch, Hide Others, Show All, Quit KatSearch", + ) + def test_katsearch_menu_items(self, ax): + items = _open(ax, "KatSearch") + names = _real(_names(items)) + ks.close_menus() + missing = _missing(names, KATSEARCH_ITEMS) + assert kit.rb_value(missing, []), ( + "KatSearch menu is missing %r; observed items were %r" % (missing, names) + ) + + @pytest.mark.rb( + depth=1, + jump_kind="value", + expect="File menu drops down containing New Search Window, Open Recent, Close, Close All, Save…, Page Setup…, Print…", + ) + def test_file_menu_items(self, ax): + items = _open(ax, "File") + names = _real(_names(items)) + ks.close_menus() + missing = _missing(names, FILE_ITEMS) + assert kit.rb_value(missing, []), ( + "File menu is missing %r; observed items were %r" % (missing, names) + ) + + @pytest.mark.rb( + depth=1, + jump_kind="value", + expect="Edit menu drops down containing Undo, Redo, Cut, Copy, Paste, Select All plus the Transformations and Speech submenus", + ) + def test_edit_menu_items(self, ax): + items = _open(ax, "Edit") + names = _real(_names(items)) + ks.close_menus() + missing = _missing(names, EDIT_ITEMS) + assert kit.rb_value(missing, []), ( + "Edit menu is missing %r; observed items were %r" % (missing, names) + ) + + @pytest.mark.rb( + depth=1, + jump_kind="value", + expect="Edit > Find submenu contains Find…, Find and Replace…, Find Next, Find Previous, Use Selection for Find, Jump to Selection", + ) + def test_edit_find_submenu_items(self, ax): + items = _open(ax, "Edit") + sub = _submenu_names(ax, items, "Find") + ks.close_menus() + assert sub is not None, "Edit menu has no 'Find' item to hang a submenu off" + assert sub, "Edit > Find exposed no submenu items" + missing = _missing(sub, EDIT_FIND_ITEMS) + assert kit.rb_value(missing, []), ( + "Edit > Find submenu is missing %r; observed %r" % (missing, sub) + ) + + @pytest.mark.rb( + depth=1, + jump_kind="value", + expect="View menu drops down with all 13 'Show …' column items plus Enter Full Screen", + ) + def test_view_menu_items(self, ax): + items = _open(ax, "View") + names = _real(_names(items)) + ks.close_menus() + missing = _missing(names, VIEW_ITEMS) + assert kit.rb_value(missing, []), ( + "View menu is missing %r; observed items were %r" % (missing, names) + ) + + @pytest.mark.rb( + depth=1, + jump_kind="value", + expect="Action menu drops down containing Search, Open, Show in Finder, Get Info, Quick Look, Move to Trash, Show Selected Item(s), Show Filter, Hide Filter, Authenticate", + ) + def test_action_menu_items(self, ax): + items = _open(ax, "Action") + names = _real(_names(items)) + ks.close_menus() + missing = _missing(names, ACTION_ITEMS) + assert kit.rb_value(missing, []), ( + "Action menu is missing %r; observed items were %r" % (missing, names) + ) + + @pytest.mark.rb( + depth=1, + jump_kind="value", + expect="Window menu drops down containing Minimize, Minimize All, Zoom, Zoom All, Bring All to Front, Arrange in Front", + ) + def test_window_menu_items(self, ax): + items = _open(ax, "Window") + names = _real(_names(items)) + ks.close_menus() + missing = _missing(names, WINDOW_ITEMS) + assert kit.rb_value(missing, []), ( + "Window menu is missing %r; observed items were %r" % (missing, names) + ) + + @pytest.mark.rb( + depth=1, + jump_kind="value", + expect="Help menu drops down containing KatSearch Website, GitHub Project Page, Make a Donation, searchfs Man Page, KatSearch Help (read only — never activated)", + ) + def test_help_menu_items(self, ax): + # READ ONLY: every Help item launches a browser, so we only enumerate. + items = _open(ax, "Help") + names = _real(_names(items)) + ks.close_menus() + missing = _missing(names, HELP_ITEMS) + assert kit.rb_value(missing, []), ( + "Help menu is missing %r; observed items were %r" % (missing, names) + ) + + +# ========================================================================== +# B. MENU-ITEM STATE +# ========================================================================== + +class TestMenuItemState: + + @pytest.mark.rb( + depth=1, + jump_kind="value", + expect="View menu default marks: Show Path Bar/Show Kind/Show Size/Show Date Modified are '✓', the other nine 'Show …' items have no mark", + ) + def test_view_menu_default_marks(self, ax): + items = _open(ax, "View") + observed = _marks_of(ax, items, list(VIEW_DEFAULT_MARKS.keys())) + ks.close_menus() + assert kit.rb_value(observed, dict(VIEW_DEFAULT_MARKS)), ( + "View menu default marks differ.\n observed: %r\n expected: %r" + % (observed, VIEW_DEFAULT_MARKS) + ) + + @pytest.mark.rb( + depth=1, + jump_kind="value", + expect="File > Save… is enabled=False in the default state (no search has produced results yet)", + ) + def test_file_save_disabled_by_default(self, ax): + items = _open(ax, "File") + names = _real(_names(items)) + ks.close_menus() + assert not _missing(names, ["Save…"]), ( + "File menu has no 'Save…' item; observed %r" % (names,) + ) + observed = _enabled_any(ax, "File", "Save…", "Save...") + assert kit.rb_value(observed, False), ( + "File > Save… enabled state is %r, expected False before any search results" + % (observed,) + ) + + @pytest.mark.rb( + depth=1, + jump_kind="value", + expect="with no search window every Action item is enabled=False except Authenticate which is enabled=True", + ) + def test_action_items_disabled_without_search_window(self, ax): + assert ks.search_window(ax) is None, ( + "a search window already exists — the default state should have none" + ) + items = _open(ax, "Action") + ks.close_menus() + names = _real(_names(items)) + missing = _missing(names, list(ACTION_DEFAULT_ENABLED.keys())) + assert not missing, "Action menu is missing %r; observed %r" % (missing, names) + observed = {} + for name in ACTION_DEFAULT_ENABLED: + observed[name] = ks.menu_item_enabled(ax, "Action", name) + assert kit.rb_value(observed, dict(ACTION_DEFAULT_ENABLED)), ( + "Action item enable states differ with no search window.\n observed: %r\n expected: %r" + % (observed, ACTION_DEFAULT_ENABLED) + ) + + +# ========================================================================== +# C. SAFE MENU-ITEM ACTIVATION +# ========================================================================== + +class TestSafeMenuActivation: + + @pytest.mark.rb( + depth=1, + jump_kind="reach", + expect="File > New Search Window: a window titled KatSearch appears — ks_showing gains 'window|KatSearch'", + ) + def test_new_search_window_reaches_search_window(self, ax): + assert ks.search_window(ax) is None, "a search window existed before File > New Search Window" + before = ks.ks_showing(ax) + w = ks.rb_enter_search_window(ax) + assert w is not None, "File > New Search Window did not open a search window" + after = ks.ks_showing(ax) + assert kit.rb_reach(before, after, target="window|KatSearch"), ( + "'window|KatSearch' did not newly appear.\n gained: %r" + % (sorted(after - before),) + ) + ks.screenshot_assert( + "menus_new_search_window", + "Window titled “KatSearch” opened from File > New Search Window, showing the " + "query row “Find [items ▾] [name contains ▾] [text field] where/on [volume ▾]”, " + "a “Search” button and an empty results table with the column headers " + "Items / Kind / Date Modified / Size.", + ) + + + + @pytest.mark.rb( + depth=1, + jump_kind="reach", + expect="Action > Show Filter: a search field with AXPlaceholderValue 'Filter...' appears in the search window — ks_showing gains 'placeholder|Filter...'", + ) + def test_show_filter_reaches_filter_field(self, ax): + w = ks.rb_enter_search_window(ax) + assert w is not None, "could not open a search window for Action > Show Filter" + assert ks.filter_field(ax) is None, "the filter field was visible before Show Filter" + assert ks.menu_item_enabled(ax, "Action", "Show Filter") is True, ( + "Action > Show Filter is not enabled with a search window open" + ) + before = ks.ks_showing(ax) + assert ks.pick_menu_item(ax, "Action", "Show Filter"), ( + "could not activate Action > Show Filter" + ) + time.sleep(0.6) + after = ks.ks_showing(ax) + assert kit.rb_reach(before, after, target="placeholder|Filter..."), ( + "'placeholder|Filter...' did not newly appear.\n gained: %r" + % (sorted(after - before),) + ) + assert ks.filter_field(ax) is not None, "ks.filter_field() is still None after Show Filter" + ks.close_menus() + + @pytest.mark.rb( + depth=1, + jump_kind="transition", + expect="Action > Hide Filter: ks.filter_field(ax) is not None -> False (the 'Filter...' search field disappears)", + ) + def test_hide_filter_removes_filter_field(self, ax): + w = ks.rb_enter_search_window(ax) + assert w is not None, "could not open a search window for Action > Hide Filter" + assert ks.pick_menu_item(ax, "Action", "Show Filter"), ( + "could not activate Action > Show Filter (needed before Hide Filter)" + ) + time.sleep(0.6) + before = ks.filter_field(ax) is not None + assert before is True, "the filter field never appeared, so Hide Filter cannot be tested" + assert ks.menu_item_enabled(ax, "Action", "Hide Filter") is True, ( + "Action > Hide Filter is not enabled while the filter field is visible" + ) + assert ks.pick_menu_item(ax, "Action", "Hide Filter"), ( + "could not activate Action > Hide Filter" + ) + time.sleep(0.6) + after = ks.filter_field(ax) is not None + assert kit.rb_flip(before, after), ( + "filter-field presence did not flip: before=%r after=%r" % (before, after) + ) + assert after is False, "the filter field is still present after Hide Filter" + assert "placeholder|Filter..." not in ks.ks_showing(ax), ( + "'placeholder|Filter...' is still showing after Hide Filter" + ) + ks.close_menus() + + @pytest.mark.rb( + depth=1, + jump_kind="transition", + expect="View > Show Kind: mark '✓' -> None and sort headers ['Items','Kind','Date Modified','Size'] -> ['Items','Date Modified','Size']", + ) + def test_show_kind_hides_kind_column(self, ax): + w = ks.rb_enter_search_window(ax) + assert w is not None, "could not open a search window to observe the Kind column" + items = _open(ax, "View") + assert ks.find_item(items, "Show Kind") is not None, "View menu has no 'Show Kind' item" + ks.close_menus() + mark_before = ks.menu_mark(ax, "View", "Show Kind") + headers_before = list(ks.sort_headers(ax) or []) + assert mark_before == CHECK, "View > Show Kind default mark is %r, expected '✓'" % (mark_before,) + assert headers_before == DEFAULT_HEADERS, ( + "default sort headers are %r, expected %r" % (headers_before, DEFAULT_HEADERS) + ) + assert ks.pick_menu_item(ax, "View", "Show Kind"), "could not activate View > Show Kind" + time.sleep(0.8) + mark_after = ks.menu_mark(ax, "View", "Show Kind") + headers_after = list(ks.sort_headers(ax) or []) + ks.close_menus() + assert kit.rb_flip(mark_before, mark_after), ( + "the Show Kind mark did not flip: before=%r after=%r" % (mark_before, mark_after) + ) + assert mark_after is None, "Show Kind mark is %r, expected None after toggling off" % (mark_after,) + assert kit.rb_flip(headers_before, headers_after), ( + "the sort headers did not change: %r" % (headers_after,) + ) + assert kit.rb_value(headers_after, ["Items", "Date Modified", "Size"]), ( + "sort headers after hiding Kind are %r, expected ['Items','Date Modified','Size']" + % (headers_after,) + ) + + @pytest.mark.rb( + depth=1, + jump_kind="transition", + expect="View > Show Date Created: mark None -> '✓' and sort headers become ['Items','Kind','Date Modified','Date Created','Size']", + ) + def test_show_date_created_adds_column(self, ax): + w = ks.rb_enter_search_window(ax) + assert w is not None, "could not open a search window to observe the Date Created column" + items = _open(ax, "View") + assert ks.find_item(items, "Show Date Created") is not None, ( + "View menu has no 'Show Date Created' item" + ) + ks.close_menus() + mark_before = ks.menu_mark(ax, "View", "Show Date Created") + headers_before = list(ks.sort_headers(ax) or []) + assert mark_before is None, ( + "View > Show Date Created default mark is %r, expected None" % (mark_before,) + ) + assert "Date Created" not in headers_before, ( + "'Date Created' header already present by default: %r" % (headers_before,) + ) + assert ks.pick_menu_item(ax, "View", "Show Date Created"), ( + "could not activate View > Show Date Created" + ) + time.sleep(0.8) + mark_after = ks.menu_mark(ax, "View", "Show Date Created") + headers_after = list(ks.sort_headers(ax) or []) + ks.close_menus() + assert kit.rb_flip(mark_before, mark_after), ( + "the Show Date Created mark did not flip: before=%r after=%r" % (mark_before, mark_after) + ) + assert mark_after == CHECK, "Show Date Created mark is %r, expected '✓'" % (mark_after,) + assert kit.rb_value( + headers_after, ["Items", "Kind", "Date Modified", "Date Created", "Size"] + ), ( + "sort headers after showing Date Created are %r, expected " + "['Items','Kind','Date Modified','Date Created','Size']" % (headers_after,) + ) + + @pytest.mark.rb( + depth=1, + jump_kind="transition", + expect="View > Show Size: mark '✓' -> None and the 'Size' sort header disappears from ks.sort_headers", + ) + def test_show_size_hides_size_column(self, ax): + w = ks.rb_enter_search_window(ax) + assert w is not None, "could not open a search window to observe the Size column" + items = _open(ax, "View") + assert ks.find_item(items, "Show Size") is not None, "View menu has no 'Show Size' item" + ks.close_menus() + mark_before = ks.menu_mark(ax, "View", "Show Size") + headers_before = list(ks.sort_headers(ax) or []) + size_before = "Size" in headers_before + assert mark_before == CHECK, "View > Show Size default mark is %r, expected '✓'" % (mark_before,) + assert size_before is True, "no 'Size' sort header by default: %r" % (headers_before,) + assert ks.pick_menu_item(ax, "View", "Show Size"), "could not activate View > Show Size" + time.sleep(0.8) + mark_after = ks.menu_mark(ax, "View", "Show Size") + headers_after = list(ks.sort_headers(ax) or []) + size_after = "Size" in headers_after + ks.close_menus() + assert kit.rb_flip(size_before, size_after), ( + "the 'Size' header presence did not flip: before=%r after=%r headers=%r" + % (size_before, size_after, headers_after) + ) + assert size_after is False, "'Size' header still present after toggling: %r" % (headers_after,) + assert mark_after is None, "Show Size mark is %r, expected None" % (mark_after,) + + @pytest.mark.rb( + depth=1, + jump_kind="transition", + expect="View > Show Full Path: AXMenuItemMarkChar None -> '✓'", + ) + def test_show_full_path_marks_item(self, ax): + items = _open(ax, "View") + assert ks.find_item(items, "Show Full Path") is not None, ( + "View menu has no 'Show Full Path' item" + ) + ks.close_menus() + mark_before = ks.menu_mark(ax, "View", "Show Full Path") + assert mark_before is None, ( + "View > Show Full Path default mark is %r, expected None" % (mark_before,) + ) + assert ks.pick_menu_item(ax, "View", "Show Full Path"), ( + "could not activate View > Show Full Path" + ) + time.sleep(0.8) + mark_after = ks.menu_mark(ax, "View", "Show Full Path") + ks.close_menus() + assert kit.rb_flip(mark_before, mark_after), ( + "the Show Full Path mark did not flip: before=%r after=%r" % (mark_before, mark_after) + ) + assert mark_after == CHECK, "Show Full Path mark is %r, expected '✓'" % (mark_after,) + + @pytest.mark.rb( + depth=1, + jump_kind="transition", + expect="Action > Search / Show Filter enabled (False, False) with no search window -> (True, True) after File > New Search Window", + ) + def test_action_items_enable_with_search_window(self, ax): + assert ks.search_window(ax) is None, "a search window already existed" + before = ( + ks.menu_item_enabled(ax, "Action", "Search"), + ks.menu_item_enabled(ax, "Action", "Show Filter"), + ) + assert before == (False, False), ( + "Action Search/Show Filter enabled=%r with no search window, expected (False, False)" + % (before,) + ) + w = ks.rb_enter_search_window(ax) + assert w is not None, "File > New Search Window did not open a search window" + time.sleep(0.5) + after = ( + ks.menu_item_enabled(ax, "Action", "Search"), + ks.menu_item_enabled(ax, "Action", "Show Filter"), + ) + assert kit.rb_flip(before, after), ( + "Action item enable states did not flip: before=%r after=%r" % (before, after) + ) + assert after == (True, True), ( + "Action Search/Show Filter enabled=%r with a search window, expected (True, True)" + % (after,) + ) + # the item actions still need a selection + assert ks.menu_item_enabled(ax, "Action", "Open") is False, ( + "Action > Open is enabled without any selected row" + ) + ks.close_menus() + + @pytest.mark.rb( + depth=2, + jump_kind="transition", + expect="Action item actions all enabled=False -> all enabled=True once a results row is selected (Open, Show in Finder, Get Info, Quick Look, Move to Trash, Show Selected Item(s))", + ) + def test_action_item_actions_enable_after_row_selection(self, ax): + w = ks.rb_enter_search_window(ax) + assert w is not None, "could not open a search window" + before = tuple( + ks.menu_item_enabled(ax, "Action", n) for n in ACTION_SELECTION_ITEMS + ) + assert before == tuple([False] * len(ACTION_SELECTION_ITEMS)), ( + "Action item actions are %r before any selection, expected all False" % (before,) + ) + status = ks.run_search(ax, SEARCH_TERM) + rows = ks.result_rows(ax) or [] + assert rows, "the search for %r produced no rows (status=%r)" % (SEARCH_TERM, status) + assert ks.select_first_row(ax), "could not select the first results row" + time.sleep(0.6) + after = tuple( + ks.menu_item_enabled(ax, "Action", n) for n in ACTION_SELECTION_ITEMS + ) + ks.close_menus() + # READ ONLY: these items mutate the filesystem / open other apps — never activated. + assert kit.rb_flip(before, after), ( + "Action item actions did not flip on selection: before=%r after=%r" % (before, after) + ) + assert after == tuple([True] * len(ACTION_SELECTION_ITEMS)), ( + "after selecting a row the Action item actions are %r (%r), expected all True" + % (after, ACTION_SELECTION_ITEMS) + ) + + @pytest.mark.rb( + depth=2, + jump_kind="reach", + expect="File > Save… after a search: a 'save' sheet appears over the search window — ks_showing gains 'sheet|save'", + ) + def test_save_after_search_reaches_save_sheet(self, ax): + w = ks.rb_enter_search_window(ax) + assert w is not None, "could not open a search window" + status = ks.run_search(ax, SEARCH_TERM) + assert (ks.result_rows(ax) or []), ( + "the search for %r produced no rows, so File > Save… stays disabled (status=%r)" + % (SEARCH_TERM, status) + ) + before = ks.ks_showing(ax) + sheet = ks.rb_enter_save_sheet(ax) + assert sheet is not None, "File > Save… did not drop a save sheet" + after = ks.ks_showing(ax) + try: + assert kit.rb_reach(before, after, target="sheet|save"), ( + "'sheet|save' did not newly appear.\n gained: %r" % (sorted(after - before),) + ) + ks.screenshot_assert( + "menus_save_sheet", + "A macOS save sheet dropped over the KatSearch search window by File > Save…, with " + "“Save As:” prefilled “SearchResults-Automator.txt”, a “Where:” " + "popup and Cancel / Save buttons.", + ) + finally: + ks.close_menus(2) + + @pytest.mark.rb( + depth=1, + jump_kind="value", + expect="File > Open Recent submenu exists and contains 'Clear Menu' (RecentSearches is wiped before each test)", + ) + def test_open_recent_submenu_contains_clear_menu(self, ax): + items = _open(ax, "File") + assert ks.find_item(items, "Open Recent") is not None, ( + "File menu has no 'Open Recent' item; observed %r" % (_real(_names(items)),) + ) + sub = _submenu_names(ax, items, "Open Recent") + ks.close_menus() + assert sub, "File > Open Recent exposed no submenu items" + # never activate Clear Menu — existence only + missing = _missing(sub, ["Clear Menu"]) + assert kit.rb_value(missing, []), ( + "File > Open Recent submenu is missing 'Clear Menu'; observed %r" % (sub,) + ) + + +# ========================================================================== +# D. CONTEXTUAL MENUS +# ========================================================================== + +class TestContextualMenus: + + @pytest.mark.rb( + depth=1, + jump_kind="value", + expect="results-header columns menu lists the 11 'Show …' items (incl. 'Show Uniform Type Identifier', not 'Show UTI') with marks ✓ on Show Kind/Show Size/Show Date Modified only", + ) + def test_column_menu_items_and_default_marks(self, ax): + w = ks.rb_enter_search_window(ax) + assert w is not None, "could not open a search window for the columns menu" + items = ks.rb_enter_column_menu(ax) + assert items, "the results-table header contextual (columns) menu exposed no items" + names = _real(_names(items)) + observed = _marks_of(ax, items, list(COLUMN_MENU_MARKS.keys())) + ks.screenshot_assert( + "menus_columns_menu_open", + "The results-table header contextual menu is open: a drop-down of “Show …” items " + "with checkmarks next to Show Kind, Show Size and Show Date Modified.", + ) + ks.close_menus() + missing = _missing(names, list(COLUMN_MENU_MARKS.keys())) + assert kit.rb_value(missing, []), ( + "columns menu is missing %r; observed items were %r" % (missing, names) + ) + assert kit.rb_value(observed, dict(COLUMN_MENU_MARKS)), ( + "columns menu default marks differ.\n observed: %r\n expected: %r" + % (observed, COLUMN_MENU_MARKS) + ) + + @pytest.mark.rb( + depth=2, + jump_kind="value", + expect="results-row contextual menu lists Open, Open With, Show Package Contents, Move to Trash, Get Info, Show in Finder, Quick Look, Share", + ) + def test_row_context_menu_items(self, ax): + w = ks.rb_enter_search_window(ax) + assert w is not None, "could not open a search window" + status = ks.run_search(ax, SEARCH_TERM) + assert (ks.result_rows(ax) or []), ( + "the search for %r produced no rows (status=%r)" % (SEARCH_TERM, status) + ) + assert ks.select_first_row(ax), "could not select the first results row" + items = ks.rb_enter_row_context_menu(ax) + assert items, "the results-row contextual menu exposed no items" + names = _real(_names(items)) + ks.screenshot_assert( + "menus_row_context_menu", + "A contextual menu over the selected results row listing Open, Open With, Show Package " + "Contents, Move to Trash, Get Info, Show in Finder, Quick Look, Share and a " + "Copy “” item.", + ) + ks.close_menus() + # READ ONLY: every one of these mutates the filesystem or opens another app. + missing = _missing(names, ROW_MENU_ITEMS) + assert kit.rb_value(missing, []), ( + "row contextual menu is missing %r; observed items were %r" % (missing, names) + ) + + @pytest.mark.rb( + depth=2, + jump_kind="value", + expect="results-row contextual menu carries the dynamic item Copy “” interpolating ks.row_names(ax)[0]", + ) + def test_row_context_menu_copy_item_is_dynamic(self, ax): + w = ks.rb_enter_search_window(ax) + assert w is not None, "could not open a search window" + status = ks.run_search(ax, SEARCH_TERM) + assert (ks.result_rows(ax) or []), ( + "the search for %r produced no rows (status=%r)" % (SEARCH_TERM, status) + ) + assert ks.select_first_row(ax), "could not select the first results row" + row_names = ks.row_names(ax) or [] + assert row_names, "ks.row_names(ax) returned nothing, so the dynamic Copy item is untestable" + selected = row_names[0] + expected = "Copy “%s”" % selected + items = ks.rb_enter_row_context_menu(ax) + assert items, "the results-row contextual menu exposed no items" + names = _real(_names(items)) + ks.close_menus() + copies = [n for n in names if _norm(n).startswith("Copy")] + missing = _missing(names, [expected]) + assert kit.rb_value(missing, []), ( + "expected the dynamic item %r for the selected row %r; the menu's Copy items were %r" + % (expected, selected, copies) + ) + + @pytest.mark.rb( + depth=1, + jump_kind="value", + expect="search-options menu (gear 'action' button) lists exactly Case Sensitive, Skip Package Contents, Skip Invisible Files, Skip System Folder — all unmarked", + ) + def test_search_options_menu_items_and_marks(self, ax): + w = ks.rb_enter_search_window(ax) + assert w is not None, "could not open a search window for the options menu" + items = ks.rb_enter_options_menu(ax) + assert items, "the advanced search-options menu exposed no items" + names = _real(_names(items)) + observed = _marks_of(ax, items, list(OPTIONS_ITEMS)) + ks.screenshot_assert( + "menus_options_menu_open", + "A small drop-down menu opened from the search window's gear button listing " + "“Case Sensitive”, “Skip Package Contents”, “Skip Invisible Files” " + "and “Skip System Folder”, none of them checked.", + ) + ks.close_menus() + assert kit.rb_value([_norm(n) for n in names], [_norm(n) for n in OPTIONS_ITEMS]), ( + "search-options menu items are %r, expected exactly %r" % (names, OPTIONS_ITEMS) + ) + assert kit.rb_value(observed, dict((n, None) for n in OPTIONS_ITEMS)), ( + "search-option default marks differ.\n observed: %r\n expected all None" % (observed,) + ) diff --git a/macos/sveinbjornt-katsearch/tests/test_ax_states.py b/macos/sveinbjornt-katsearch/tests/test_ax_states.py new file mode 100644 index 0000000000000000000000000000000000000000..07a4a8c77fdfd1948cc6625ec42bb336ca6d9e1b --- /dev/null +++ b/macos/sveinbjornt-katsearch/tests/test_ax_states.py @@ -0,0 +1,587 @@ +"""AX state tests for KatSearch — checked/enabled/focus/mode flips and their consequences.""" + +import os +import sys +import time + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +import pytest + +import ks_helpers as ks +import rb_testgen_kit as kit + +# --------------------------------------------------------------------------- +# Observation helpers. Every one of them RE-FETCHES the element it reads, so a +# before/after pair is never taken from a stale AX handle. Locators are always +# semantic: role + visible title (AXTitle/AXDescription) or the visible label of +# a menu item — never a child index or an internal identifier. +# --------------------------------------------------------------------------- + +GENERAL_CHECKBOXES = ("Remember Search History", "Launch On Login", + "Show Full Item Path", "Show Path String Instead of Bar") +SEARCH_CHECKBOXES = ("Case Sensitive", "Skip Package Contents", + "Skip Hidden Files", "Skip System Folder") +ADVANCED_CHECKBOXES = ("Human-friendly Dates", "Human-friendly File Sizes", + "Human-friendly Permissions", "Authenticate on Launch") +ROW_ACTION_ITEMS = ("Open", "Show in Finder", "Get Info", "Quick Look", + "Show Selected Item(s)") + + +def _marked(mark): + """True when a menu item's AXMenuItemMarkChar reports CHECKED (the '✓' glyph).""" + return mark is not None and str(mark).strip() != "" + + +# ── preferences checkboxes ──────────────────────────────────────────────────── + +def _prefs_cb_value(ax, name): + """AXValue (1/0) of a preferences checkbox found by its visible label.""" + w = ks.prefs_window(ax) + if w is None: + return None + return ks.checkbox_value(ax, ks.checkbox_named(ax, name, w)) + + +def _press_prefs_cb(ax, name): + w = ks.prefs_window(ax) + assert w is not None, "preferences window is not open" + cb = ks.checkbox_named(ax, name, w) + assert cb is not None, "prefs checkbox %r not found in the visible pane" % name + assert ks.toggle_checkbox(ax, cb), "AXPress on prefs checkbox %r failed" % name + + +def _prefs_cb_values(ax, names): + return dict((n, _prefs_cb_value(ax, n)) for n in names) + + +def _prefs_cb_names(ax, w): + return set((c.name or "").strip() for c in ks.prefs_checkboxes(ax, w)) + + +# ── intro checkboxes ───────────────────────────────────────────────────────── + +def _intro_cb_value(ax, name): + w = ks.intro_window(ax) + if w is None: + return None + return ks.checkbox_value(ax, ks.checkbox_named(ax, name, w)) + + +def _press_intro_cb(ax, name): + w = ks.intro_window(ax) + assert w is not None, "intro/welcome window is not present" + cb = ks.checkbox_named(ax, name, w) + assert cb is not None, "intro checkbox %r not found" % name + assert ks.toggle_checkbox(ax, cb), "AXPress on intro checkbox %r failed" % name + + +# ── menus ──────────────────────────────────────────────────────────────────── + +def _view_menu_mark(ax, item_name): + """NAV: drop the View menu (so AppKit revalidates it), then read the item's mark.""" + items = ks.open_menu(ax, "View") + found = ks.find_item(items, item_name) is not None + ks.close_menus() + time.sleep(0.4) + assert found, "View menu item %r not found" % item_name + return ks.menu_mark(ax, "View", item_name) + + +def _action_items_enabled(ax, names): + """NAV: drop the Action menu and read AXEnabled of each named item.""" + items = ks.open_menu(ax, "Action") + out = {} + for n in names: + it = ks.find_item(items, n) + out[n] = None if it is None else bool(it.enabled) + ks.close_menus() + time.sleep(0.4) + return out + + +def _assert_option_mark_flip(ax, w, title): + """search-options menu item: None -> '✓' -> None (default proved by restoring it).""" + before = ks.search_option_mark(ax, title, w) + assert before is None, ( + "search option %r must start UNCHECKED (mark None), got %r" % (title, before)) + assert ks.toggle_search_option(ax, title, w), ( + "could not pick %r in the search-options menu" % title) + after = ks.search_option_mark(ax, title, w) + assert kit.rb_flip(before, after), ( + "the %r mark did not change (%r -> %r)" % (title, before, after)) + assert _marked(after), ( + "expected the '✓' mark on %r after picking it, got %r" % (title, after)) + assert ks.toggle_search_option(ax, title, w), "could not un-pick %r" % title + back = ks.search_option_mark(ax, title, w) + assert kit.rb_flip(after, back), ( + "the %r mark did not come back (%r -> %r)" % (title, after, back)) + assert back is None, ( + "expected %r to return to its UNCHECKED default, got %r" % (title, back)) + + +# ── search window ──────────────────────────────────────────────────────────── + +def _query_control_states(ax, w): + """((popup enabled x3), search-field enabled, action-button enabled).""" + pops = tuple(bool(p.enabled) for p in ks.sw_popups(ax, w)[:3]) + f = ks.search_field(ax, w) + a = ks.sw_button(ax, "action", w) + return (pops, + None if f is None else bool(f.enabled), + None if a is None else bool(a.enabled)) + + +def _search_button_enabled(ax, w): + b = ks.sw_button(ax, "Search", w) + return None if b is None else bool(b.enabled) + + +def _path_bar_present(ax, w): + """True when the `list "path"` path bar is exposed by the search window.""" + for l in ax.find(role="list", root_id=w.id, max_results=8): + if "path" in (l.name or "").lower(): + return True + return False + + +def _popup_value(ax, w, index): + pops = ks.sw_popups(ax, w) + assert len(pops) > index, ( + "expected at least %d pop up buttons in the search window, found %d" + % (index + 1, len(pops))) + return ks.popup_value(ax, pops[index]).strip() + + +def _popup_item_marks(ax, w, index, titles): + """Open a search-window popup, read the mark of each named option, close it.""" + pops = ks.sw_popups(ax, w) + assert len(pops) > index, "search-window popup #%d not found" % index + items = ks.popup_items(ax, pops[index]) + out = {} + for t in titles: + it = ks.find_item(items, t) + out[t] = ks.mark_of(ax, it) if it is not None else None + ks.close_menus() + time.sleep(0.4) + return out + + +# =========================================================================== +# 1. INTRO WINDOW checkbox state +# =========================================================================== + +class TestIntroCheckboxStates: + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="intro checkbox 'Launch on Login' AXValue 1 -> 0, " + "press again -> 1 (CHECKED is the first-run default)") + def test_intro_launch_on_login_checked_flip(self, ax): + assert ks.intro_window(ax) is not None, ( + "the intro/welcome window is not present at launch") + assert ks.rb_enter_intro_page2(ax), ( + "intro page 2 did not appear (no 'Start using KatSearch' button)") + before = _intro_cb_value(ax, "Launch on Login") + assert before == 1, ( + "intro 'Launch on Login' must default to CHECKED (1), got %r" % before) + _press_intro_cb(ax, "Launch on Login") + after = _intro_cb_value(ax, "Launch on Login") + assert kit.rb_flip(before, after), ( + "'Launch on Login' AXValue did not change (%r -> %r)" % (before, after)) + assert before == 1 and after == 0, ( + "expected 1 -> 0 on 'Launch on Login', got %r -> %r" % (before, after)) + _press_intro_cb(ax, "Launch on Login") + restored = _intro_cb_value(ax, "Launch on Login") + assert kit.rb_flip(after, restored), ( + "'Launch on Login' did not flip back (%r -> %r)" % (after, restored)) + assert restored == 1, ( + "'Launch on Login' must return to its CHECKED default, got %r" % restored) + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="intro checkbox 'Check for Updates' AXValue 1 -> 0, " + "press again -> 1 (CHECKED is the first-run default)") + def test_intro_check_for_updates_checked_flip(self, ax): + assert ks.intro_window(ax) is not None, ( + "the intro/welcome window is not present at launch") + assert ks.rb_enter_intro_page2(ax), ( + "intro page 2 did not appear (no 'Start using KatSearch' button)") + before = _intro_cb_value(ax, "Check for Updates") + assert before == 1, ( + "intro 'Check for Updates' must default to CHECKED (1), got %r" % before) + _press_intro_cb(ax, "Check for Updates") + after = _intro_cb_value(ax, "Check for Updates") + assert kit.rb_flip(before, after), ( + "'Check for Updates' AXValue did not change (%r -> %r)" % (before, after)) + assert before == 1 and after == 0, ( + "expected 1 -> 0 on 'Check for Updates', got %r -> %r" % (before, after)) + _press_intro_cb(ax, "Check for Updates") + restored = _intro_cb_value(ax, "Check for Updates") + assert kit.rb_flip(after, restored), ( + "'Check for Updates' did not flip back (%r -> %r)" % (after, restored)) + assert restored == 1, ( + "'Check for Updates' must return to its CHECKED default, got %r" % restored) + + +# =========================================================================== +# 2. PREFERENCES — General pane checkbox state +# =========================================================================== + +class TestPrefsGeneralCheckboxStates: + + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="prefs General 'Launch On Login' AXValue 1 -> 0, " + "press again -> 1") + def test_launch_on_login_flip(self, ax): + p = ks.open_preferences(ax) + assert p is not None, "preferences window did not open (KatSearch > Settings…)" + before = _prefs_cb_value(ax, "Launch On Login") + assert before == 1, ( + "prefs 'Launch On Login' must default to CHECKED (1), got %r" % before) + _press_prefs_cb(ax, "Launch On Login") + after = _prefs_cb_value(ax, "Launch On Login") + assert kit.rb_flip(before, after), ( + "'Launch On Login' did not change (%r -> %r)" % (before, after)) + assert before == 1 and after == 0, ( + "expected 1 -> 0, got %r -> %r" % (before, after)) + _press_prefs_cb(ax, "Launch On Login") + restored = _prefs_cb_value(ax, "Launch On Login") + assert kit.rb_flip(after, restored) and restored == 1, ( + "'Launch On Login' must return to 1, got %r" % restored) + + + + + + +# =========================================================================== +# 3. PREFERENCES — Search pane checkbox state +# =========================================================================== + +# =========================================================================== +# 4. PREFERENCES — Advanced pane checkbox state +# =========================================================================== + +# =========================================================================== +# 5. PREFERENCES — pane selection state +# =========================================================================== + +# =========================================================================== +# 6. SEARCH-OPTIONS MENU marks (the 'action' gear button) +# =========================================================================== + +class TestSearchOptionMarkStates: + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="options menu 'Case Sensitive' mark None -> '✓' -> None") + def test_option_case_sensitive_mark_flip(self, ax): + w = ks.rb_enter_search_window(ax) + assert w is not None, "search window did not open (File > New Search Window)" + _assert_option_mark_flip(ax, w, "Case Sensitive") + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="options menu 'Skip Package Contents' mark None -> '✓' " + "-> None") + def test_option_skip_package_contents_mark_flip(self, ax): + w = ks.rb_enter_search_window(ax) + assert w is not None, "search window did not open (File > New Search Window)" + _assert_option_mark_flip(ax, w, "Skip Package Contents") + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="options menu 'Skip Invisible Files' mark None -> '✓' " + "-> None") + def test_option_skip_invisible_files_mark_flip(self, ax): + w = ks.rb_enter_search_window(ax) + assert w is not None, "search window did not open (File > New Search Window)" + _assert_option_mark_flip(ax, w, "Skip Invisible Files") + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="options menu 'Skip System Folder' mark None -> '✓' -> None") + def test_option_skip_system_folder_mark_flip(self, ax): + w = ks.rb_enter_search_window(ax) + assert w is not None, "search window did not open (File > New Search Window)" + _assert_option_mark_flip(ax, w, "Skip System Folder") + + +# =========================================================================== +# 7. VIEW MENU column marks + their sort-header consequence +# =========================================================================== + +class TestViewMenuColumnStates: + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="'View > Show Kind' mark '✓' -> None AND the 'Kind' sort " + "header disappears; picking it again restores both") + def test_show_kind_mark_and_header_disappear(self, ax): + w = ks.rb_enter_search_window(ax) + assert w is not None, "search window did not open (File > New Search Window)" + mark_before = _view_menu_mark(ax, "Show Kind") + headers_before = ks.sort_headers(ax, w) + assert _marked(mark_before), ( + "'View > Show Kind' must be CHECKED by default, got %r" % mark_before) + assert "Kind" in headers_before, ( + "the 'Kind' sort header must be present by default, headers=%r" + % headers_before) + ks.pick_menu_item(ax, "View", "Show Kind") + mark_after = _view_menu_mark(ax, "Show Kind") + headers_after = ks.sort_headers(ax, w) + assert kit.rb_flip(mark_before, mark_after), ( + "the 'Show Kind' mark did not change (%r -> %r)" + % (mark_before, mark_after)) + assert kit.rb_flip(headers_before, headers_after), ( + "the sort headers did not change (%r -> %r)" + % (headers_before, headers_after)) + assert mark_after is None, ( + "expected the 'Show Kind' mark to become None, got %r" % mark_after) + assert "Kind" not in headers_after, ( + "the 'Kind' column header should be gone, headers=%r" % headers_after) + ks.pick_menu_item(ax, "View", "Show Kind") + mark_back = _view_menu_mark(ax, "Show Kind") + headers_back = ks.sort_headers(ax, w) + assert _marked(mark_back), ( + "'View > Show Kind' must return to CHECKED, got %r" % mark_back) + assert "Kind" in headers_back, ( + "the 'Kind' column header must come back, headers=%r" % headers_back) + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="'View > Show Date Created' mark None -> '✓' AND a " + "'Date Created' sort header appears; picking it again " + "restores both") + def test_show_date_created_mark_and_header_appear(self, ax): + w = ks.rb_enter_search_window(ax) + assert w is not None, "search window did not open (File > New Search Window)" + mark_before = _view_menu_mark(ax, "Show Date Created") + headers_before = ks.sort_headers(ax, w) + assert mark_before is None, ( + "'View > Show Date Created' must be UNCHECKED by default, got %r" + % mark_before) + assert "Date Created" not in headers_before, ( + "there must be no 'Date Created' header by default, headers=%r" + % headers_before) + ks.pick_menu_item(ax, "View", "Show Date Created") + mark_after = _view_menu_mark(ax, "Show Date Created") + headers_after = ks.sort_headers(ax, w) + assert kit.rb_flip(mark_before, mark_after), ( + "the 'Show Date Created' mark did not change (%r -> %r)" + % (mark_before, mark_after)) + assert kit.rb_flip(headers_before, headers_after), ( + "the sort headers did not change (%r -> %r)" + % (headers_before, headers_after)) + assert _marked(mark_after), ( + "expected the 'Show Date Created' mark to become '✓', got %r" % mark_after) + assert "Date Created" in headers_after, ( + "a 'Date Created' column header should have appeared, headers=%r" + % headers_after) + ks.pick_menu_item(ax, "View", "Show Date Created") + mark_back = _view_menu_mark(ax, "Show Date Created") + headers_back = ks.sort_headers(ax, w) + assert mark_back is None, ( + "'View > Show Date Created' must return to UNCHECKED, got %r" % mark_back) + assert "Date Created" not in headers_back, ( + "the 'Date Created' header must disappear again, headers=%r" % headers_back) + + +# =========================================================================== +# 8. SEARCH WINDOW enabled / focus state +# =========================================================================== + +class TestSearchWindowEnabledStates: + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="pressing Search: 3 popups + search field + 'action' button " + "AXEnabled True -> False and a 'Stop' button exists; after " + "Stop they are all AXEnabled True again") + def test_query_controls_lock_during_search(self, ax): + w = ks.rb_enter_search_window(ax) + assert w is not None, "search window did not open (File > New Search Window)" + assert ks.set_search_text(ax, "Automator", w), ( + "could not type the search term into the search field") + before = _query_control_states(ax, w) + assert before == ((True, True, True), True, True), ( + "before pressing Search the 3 popups, the search field and the 'action' " + "button must all be ENABLED, got %r" % (before,)) + btn = ks.sw_button(ax, "Search", w) + assert btn is not None, "the 'Search' button was not found in the search window" + assert ax.action(btn.id, "AXPress"), "AXPress on the 'Search' button failed" + time.sleep(1.4) + ks.screenshot_assert( + "states_test_query_controls_lock_during_search", + "The KatSearch search window during an active search: the query controls " + "(the 'items' and 'name contains' popups, the volume popup and the search " + "text field holding 'Automator') are greyed out / disabled, the primary " + "button now reads 'Stop' instead of 'Search', a progress indicator is " + "spinning, and the status line reports the running search.") + stop_btn = ks.sw_button(ax, "Stop", w) + during = _query_control_states(ax, w) + assert stop_btn is not None, ( + "the 'Search' button did not become 'Stop' while searching") + assert kit.rb_flip(before, during), ( + "the query controls did not change enabled-state when the search started " + "(%r)" % (during,)) + assert during == ((False, False, False), False, False), ( + "while searching the 3 popups, the search field and the 'action' button " + "must all be DISABLED, got %r" % (during,)) + assert ks.stop_search(ax, w), "could not press the 'Stop' button" + after = _query_control_states(ax, w) + assert kit.rb_flip(during, after), ( + "the query controls stayed disabled after Stop (%r)" % (after,)) + assert after == before, ( + "after Stop every query control must be ENABLED again, got %r" % (after,)) + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="'Search' button AXEnabled True with text -> False when the " + "search field is emptied -> True again after re-typing") + def test_search_button_enable_gating(self, ax): + w = ks.rb_enter_search_window(ax) + assert w is not None, "search window did not open (File > New Search Window)" + assert ks.set_search_text(ax, "Automator", w), ( + "could not type the search term into the search field") + before = _search_button_enabled(ax, w) + assert before is True, ( + "with text in the search field the 'Search' button must be ENABLED, got %r" + % before) + ks.set_search_text(ax, "", w) + field = ks.search_field(ax, w) + assert field is not None, "the search text field disappeared" + cleared = ax.get(field.id, ["AXValue"]).get("AXValue") + assert (cleared or "") == "", ( + "could not clear the search field, AXValue=%r" % cleared) + after = _search_button_enabled(ax, w) + assert kit.rb_flip(before, after), ( + "the 'Search' button enabled-state did not change when the query was " + "emptied (%r -> %r)" % (before, after)) + assert after is False, ( + "with an empty query the 'Search' button must be DISABLED, got %r" % after) + assert ks.set_search_text(ax, "Automator", w), ( + "could not re-type the search term") + restored = _search_button_enabled(ax, w) + assert kit.rb_flip(after, restored), ( + "the 'Search' button did not re-enable after re-typing (%r -> %r)" + % (after, restored)) + assert restored is True, ( + "after re-typing the 'Search' button must be ENABLED again, got %r" + % restored) + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="in a newly opened search window the search text_field has " + "AXFocused == True (initial first responder)") + def test_search_field_is_initial_first_responder(self, ax): + w = ks.rb_enter_search_window(ax) + assert w is not None, "search window did not open (File > New Search Window)" + field = ks.search_field(ax, w) + assert field is not None, ( + "the search text field was not found in the search window") + focused = ax.get(field.id, ["AXFocused"]).get("AXFocused") + assert kit.rb_value(focused, True), ( + "the search text field must be the initial first responder " + "(AXFocused True), got %r" % focused) + + +# =========================================================================== +# 9. RESULTS SELECTION state + query MODE state +# =========================================================================== + +class TestSelectionAndModeStates: + + @pytest.mark.rb(depth=2, jump_kind="transition", + expect="selecting result row 0 sets AXSelected True, the list " + "'path' path bar appears, and Action > Open / Show in Finder " + "/ Get Info / Quick Look / Show Selected Item(s) go " + "AXEnabled False -> True (read only, never activated)") + def test_row_selection_enables_item_actions(self, ax): + w = ks.rb_enter_search_window(ax) + assert w is not None, "search window did not open (File > New Search Window)" + actions_before = _action_items_enabled(ax, ROW_ACTION_ITEMS) + path_before = _path_bar_present(ax, w) + for name in ROW_ACTION_ITEMS: + assert actions_before.get(name) is False, ( + "with no selection Action > %r must be DISABLED, got %r" + % (name, actions_before.get(name))) + assert path_before is False, ( + "the path bar must not be exposed before a row is selected") + status = ks.run_search(ax, "Automator", w, first_result_timeout=9.0, settle=0.8) + rows = ks.result_rows(ax, w, 5) + assert rows, "the search produced no result rows (status=%r)" % status + assert ks.select_first_row(ax, w), ( + "could not set AXSelected on the first results row") + path_after = _path_bar_present(ax, w) + actions_after = _action_items_enabled(ax, ROW_ACTION_ITEMS) + assert kit.rb_flip(path_before, path_after), ( + "the path bar did not appear after selecting a row (%r -> %r)" + % (path_before, path_after)) + assert path_after is True, ( + "a list named 'path' (the path bar) must be exposed once a row is selected") + assert kit.rb_flip(actions_before, actions_after), ( + "the Action item enabled-states did not change on selection (%r -> %r)" + % (actions_before, actions_after)) + for name in ROW_ACTION_ITEMS: + assert actions_after.get(name) is True, ( + "after selecting a row Action > %r must be ENABLED, got %r" + % (name, actions_after.get(name))) + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="item-type popup value 'items' (its menu item marked '✓', " + "files/folders unmarked) -> 'files' after picking files, " + "then back to 'items'") + def test_item_type_popup_mode_flip(self, ax): + w = ks.rb_enter_search_window(ax) + assert w is not None, "search window did not open (File > New Search Window)" + before = _popup_value(ax, w, 0) + assert before == "items", ( + "the item-type popup must start on 'items', got %r" % before) + marks = _popup_item_marks(ax, w, 0, ("items", "files", "folders")) + assert _marked(marks.get("items")), ( + "the 'items' option must carry the '✓' selection mark, got %r" + % marks.get("items")) + assert marks.get("files") is None and marks.get("folders") is None, ( + "only the selected item-type option may be marked, got %r" % marks) + pops = ks.sw_popups(ax, w) + assert pops, "the item-type popup disappeared" + assert ks.switch_mode(ax, pops[0], "files"), ( + "could not pick 'files' in the item-type popup") + after = _popup_value(ax, w, 0) + assert kit.rb_flip(before, after), ( + "the item-type popup value did not change (%r -> %r)" % (before, after)) + assert after == "files", ( + "the item-type popup must read 'files' after picking it, got %r" % after) + pops = ks.sw_popups(ax, w) + assert ks.switch_mode(ax, pops[0], "items"), ( + "could not switch the item-type popup back to 'items'") + restored = _popup_value(ax, w, 0) + assert kit.rb_flip(after, restored) and restored == "items", ( + "the item-type popup must return to its 'items' default, got %r" % restored) + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="match-criterion popup value 'name contains' (marked '✓') " + "-> 'name is' after picking it, then back to 'name contains'") + def test_match_criterion_popup_mode_flip(self, ax): + w = ks.rb_enter_search_window(ax) + assert w is not None, "search window did not open (File > New Search Window)" + before = _popup_value(ax, w, 1) + assert before == "name contains", ( + "the match-criterion popup must start on 'name contains', got %r" % before) + marks = _popup_item_marks(ax, w, 1, ("name contains", "name is")) + assert _marked(marks.get("name contains")), ( + "'name contains' must carry the '✓' selection mark, got %r" + % marks.get("name contains")) + assert marks.get("name is") is None, ( + "'name is' must be unmarked while 'name contains' is selected, got %r" + % marks.get("name is")) + pops = ks.sw_popups(ax, w) + assert len(pops) > 1, "the match-criterion popup disappeared" + assert ks.switch_mode(ax, pops[1], "name is"), ( + "could not pick 'name is' in the match-criterion popup") + after = _popup_value(ax, w, 1) + assert kit.rb_flip(before, after), ( + "the match-criterion popup value did not change (%r -> %r)" + % (before, after)) + assert after == "name is", ( + "the match-criterion popup must read 'name is' after picking it, got %r" + % after) + pops = ks.sw_popups(ax, w) + assert ks.switch_mode(ax, pops[1], "name contains"), ( + "could not switch the match-criterion popup back to 'name contains'") + restored = _popup_value(ax, w, 1) + assert kit.rb_flip(after, restored) and restored == "name contains", ( + "the match-criterion popup must return to its 'name contains' default, " + "got %r" % restored) diff --git a/macos/sveinbjornt-katsearch/tests/test_ax_structure.py b/macos/sveinbjornt-katsearch/tests/test_ax_structure.py new file mode 100644 index 0000000000000000000000000000000000000000..7e6afdc7984ca7097cf7baf801e5c35b44db2200 --- /dev/null +++ b/macos/sveinbjornt-katsearch/tests/test_ax_structure.py @@ -0,0 +1,493 @@ +"""AX structure tests for KatSearch — surface presence + shape deltas.""" + +import os +import sys +import time + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +import pytest + +import ks_helpers as ks +import rb_testgen_kit as kit + +import re + +# --------------------------------------------------------------------------- +# Expected inventories (every value OBSERVED on the reference app — recon.md) +# --------------------------------------------------------------------------- + +SEARCH_WINDOW_KEYS = [ + "window|KatSearch", "button|Search", "button|action", "button|lock", + "popup|items", "popup|name contains", "label|Find", "label|where", "label|on", + "button|Items", "button|Kind", "button|Date Modified", "button|Size", +] + +SORT_HEADERS = ["Items", "Kind", "Date Modified", "Size"] + +PREFS_GENERAL_KEYS = [ + "button|General", "button|Search", "button|Advanced", "button|Tool", + "button|Restore Defaults", "checkbox|Remember Search History", + "checkbox|Launch On Login", "checkbox|Show Full Item Path", + "checkbox|Show Path String Instead of Bar", +] + +PREFS_SEARCH_KEYS = [ + "checkbox|Case Sensitive", "checkbox|Skip Package Contents", + "checkbox|Skip Hidden Files", "checkbox|Skip System Folder", + "label|Default Search", +] + +PREFS_ADVANCED_KEYS = [ + "checkbox|Human-friendly Dates", "checkbox|Human-friendly File Sizes", + "checkbox|Human-friendly Permissions", "checkbox|Authenticate on Launch", + "button|Check for Updates...", "popup|Automatic", "label|Search Method:", +] + +PREFS_TOOL_KEYS = [ + "button|Install", "label|Command line tool is not installed", + "image|CommandLineTool", +] + +OPTIONS_MENU_ITEMS = [ + "Case Sensitive", "Skip Package Contents", "Skip Invisible Files", + "Skip System Folder", +] + +COLUMN_MENU_ITEMS = [ + "Show Kind", "Show Size", "Show Date Created", "Show Date Modified", + "Show Date Accessed", "Show User:Group", "Show Permissions", + "Show Uniform Type Identifier", "Show MIME Type", "Show HFS File Type", + "Show Creator Type", +] + +INTERACTIVE_ACTIONS = ("AXPress", "AXShowMenu", "AXPick", "AXConfirm", "AXIncrement") + + +# --------------------------------------------------------------------------- +# Local read-only utilities (no navigation, no state change) +# --------------------------------------------------------------------------- + +def _has(keys, needle): + """Case-insensitive substring match of `needle` over a role|label key set.""" + n = (needle or "").lower() + return any(n in (k or "").lower() for k in keys) + + +def _missing(keys, needles): + return [n for n in needles if not _has(keys, n)] + + +def _present(keys, needles): + return [n for n in needles if _has(keys, n)] + + +def _tree_depth(node, depth=0): + if not isinstance(node, dict): + return depth + kids = node.get("children") or [] + if not kids: + return depth + return max(_tree_depth(k, depth + 1) for k in kids) + + +def _roles_under(ax, win, limit=400): + return [e.role for e in ks.elements_under(ax, win.id, limit) if e.role] + + +def _interactive_under(ax, win, limit=400): + out = [] + for e in ks.elements_under(ax, win.id, limit): + acts = getattr(e, "actions", None) or [] + if any(a in acts for a in INTERACTIVE_ACTIONS): + out.append(e) + return out + + +def _count_role(ax, win, role, max_results=16): + return len(ax.find(role=role, root_id=win.id, max_results=max_results)) + + +def _kat_search_windows(ax): + """Titles of the search windows (title `KatSearch`, prefs/intro excluded).""" + out = [] + for t in ks.window_titles(ax): + low = (t or "").lower() + if "katsearch" in low and "preference" not in low and "setting" not in low: + out.append(t) + return out + + +def _window_menu_kat_entries(ax): + """How many trailing `KatSearch` window entries the Window menu lists.""" + names = ks.item_names(ks.open_menu(ax, "Window")) + ks.close_menus() + return sum(1 for n in names if (n or "").strip().lower() == "katsearch"), names + + +# =========================================================================== +# GATE — top-level surfaces that must exist (jump_kind="none") +# =========================================================================== + +class TestAXStructureGate: + + @pytest.mark.rb(depth=0, jump_kind="none") + def test_gate_menu_bar_app_menus(self, ax): + """The app's own menu bar carries exactly the 7 KatSearch menus.""" + items = ks.menu_bar_items(ax) + names = [(m.name or "").strip() for m in items] + assert names, "no app menu bar items exposed via AX (expected %s)" % (ks.APP_MENUS,) + assert names == ks.APP_MENUS, ( + "menu bar should be exactly %s (Apple menu excluded), found %s" + % (ks.APP_MENUS, names)) + ks.screenshot_assert( + "structure_test_menu_bar", + "The macOS menu bar at the top of the screen shows the KatSearch " + "application menus in this order: KatSearch, File, Edit, View, Action, " + "Window, Help (the Apple menu is at the far left).") + + @pytest.mark.rb(depth=0, jump_kind="none") + def test_gate_intro_window_at_launch(self, ax): + """The first-run intro/welcome window is present with its headline.""" + w = ks.intro_window(ax) + assert w is not None, ( + "no intro/welcome window at launch; window titles=%s" % (ks.window_titles(ax),)) + texts = ks.texts_under(ax, w.id, 300) + assert any("Welcome to KatSearch" in t for t in texts), ( + "intro window has no 'Welcome to KatSearch! ' headline; texts=%s" % (texts[:15],)) + assert any("interface mode" in t.lower() for t in texts), ( + "intro window is missing the 'Please select your preferred interface mode:' " + "prompt; texts=%s" % (texts[:15],)) + assert ks.intro_button(ax, "Continue →", "Continue") is not None, ( + "intro page 1 has no 'Continue →' button") + imgs = ax.find(role="image", root_id=w.id, max_results=10) + assert len(imgs) >= 2, ( + "intro page 1 should show 2 interface-mode thumbnails (Application + " + "Status Item), found %d images" % len(imgs)) + ks.screenshot_assert( + "structure_test_intro_window", + "A dark welcome window titled 'Welcome to KatSearch!' with the text " + "'Please select your preferred interface mode:', two large thumbnails " + "labelled 'Application' (a cartoon cat icon) and 'Status Item' (a menu-bar " + "screenshot), and a 'Continue →' button at the bottom.") + + @pytest.mark.rb(depth=1, jump_kind="none") + def test_gate_search_window_widget_inventory(self, ax): + """The search window exposes the full default widget inventory.""" + w = ks.rb_enter_search_window(ax) + assert w is not None, "no search window after File > New Search Window" + assert "katsearch" in (w.name or "").lower(), ( + "search window title should be 'KatSearch', found %r" % (w.name,)) + + popups = ks.sw_popups(ax, w) + n_tables = _count_role(ax, w, "table", 4) + n_cols = _count_role(ax, w, "column", 12) + n_fields = _count_role(ax, w, "text_field", 8) + headers = ks.sort_headers(ax, w) + + assert len(popups) == 3, ( + "search window should have 3 pop up buttons (item type / match criterion / " + "volume), found %d: %s" % (len(popups), [ks.popup_value(ax, p) for p in popups])) + assert n_tables == 1, "search window should have exactly 1 results table, found %d" % n_tables + assert n_cols == 4, "results table should have 4 default columns, found %d" % n_cols + assert n_fields == 1, ( + "search window should have exactly 1 text field before the filter is shown, " + "found %d" % n_fields) + assert headers == SORT_HEADERS, ( + "sort headers should be %s, found %s" % (SORT_HEADERS, headers)) + for name in ("Search", "action", "lock"): + assert ks.sw_button(ax, name, w) is not None, ( + "search window is missing the %r button" % name) + assert ks.search_field(ax, w) is not None, "search window has no query text field" + assert _count_role(ax, w, "scroll_area", 4) >= 1, ( + "search window has no scroll area hosting the results table") + + roles = set(_roles_under(ax, w)) + assert len(roles) >= 6, ( + "search window role diversity too low: expected >= 6 distinct AX roles " + "(label/popup/text_field/button/scroll_area/table/column/group), found %d: %s" + % (len(roles), sorted(roles))) + inter = _interactive_under(ax, w) + assert len(inter) >= 10, ( + "search window should expose >= 10 actionable widgets (3 popups, query field, " + "Search/action/lock, 4 sort headers, table+header menus), found %d" % len(inter)) + depth = _tree_depth(ax.tree(max_depth=12)) + assert depth >= 4, ( + "AX tree too shallow: application > window > scroll_area > table > column " + "implies depth >= 4, measured %d" % depth) + ks.screenshot_assert( + "structure_test_search_window", + "A window titled 'KatSearch' with a query row reading " + "'Find [items] [name contains] [empty text field] where/on [volume popup]', " + "a 'Search' button plus gear and lock buttons, and an empty results table " + "whose column headers read Items / Kind / Date Modified / Size.") + + + +# =========================================================================== +# Shape deltas — windows +# =========================================================================== + +class TestAXStructureWindows: + + @pytest.mark.rb(depth=1, jump_kind="reach", + expect="File > New Search Window: windows 1 -> 2, window|KatSearch " + "plus button|Search / popup|items / table appear") + def test_new_search_window_adds_window(self, ax): + before = ks.ks_showing(ax) + n_before = len(ks.app_windows(ax)) + w = ks.rb_enter_search_window(ax) + assert w is not None, "no search window after File > New Search Window" + after = ks.ks_showing(ax) + n_after = len(ks.app_windows(ax)) + assert n_after > n_before, ( + "window count should grow when a search window opens: %d -> %d" + % (n_before, n_after)) + missing = _missing(after, SEARCH_WINDOW_KEYS) + assert not missing, ( + "search-window widgets missing after File > New Search Window: %s" % missing) + assert "table|" in after, "no results table exposed by the new search window" + assert kit.rb_reach(before, after, target="window|KatSearch") + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="search windows 1 -> 2 and the Window menu KatSearch entries " + "1 -> 2 after a second File > New Search Window") + def test_two_search_windows_grow_window_menu(self, ax): + w = ks.rb_enter_search_window(ax) + assert w is not None, "no search window after File > New Search Window" + before_titles = _kat_search_windows(ax) + before_kat, before_names = _window_menu_kat_entries(ax) + assert before_names, "the Window menu exposed no items" + + assert ks.pick_menu_item(ax, "File", "New Search Window", settle=1.6), ( + "File > New Search Window not found for the second window") + time.sleep(0.4) + after_titles = _kat_search_windows(ax) + after_kat, after_names = _window_menu_kat_entries(ax) + + before_state = (len(before_titles), before_kat) + after_state = (len(after_titles), after_kat) + assert kit.rb_flip(before_state, after_state), ( + "opening a second search window changed nothing: (windows, Window-menu " + "entries) stayed %s" % (before_state,)) + assert len(after_titles) == len(before_titles) + 1, ( + "expected 2 search windows titled 'KatSearch', found %s (was %s)" + % (after_titles, before_titles)) + assert after_kat == before_kat + 1, ( + "the Window menu should gain one extra 'KatSearch' entry per search window: " + "%d -> %d (items=%s)" % (before_kat, after_kat, after_names[-4:])) + + @pytest.mark.rb(depth=1, jump_kind="reach", + expect="intro Continue →: button|Start using KatSearch appears, " + "button|Continue → disappears") + def test_intro_continue_reveals_start_button(self, ax): + assert ks.intro_window(ax) is not None, "no intro window at launch" + assert ks.intro_button(ax, "Continue →", "Continue") is not None, ( + "intro page 1 has no 'Continue →' button to press") + before = ks.ks_showing(ax) + moved = ks.rb_enter_intro_page2(ax) + after = ks.ks_showing(ax) + assert moved, "pressing 'Continue →' did not reveal 'Start using KatSearch'" + assert _has(after, "button|Start using KatSearch"), ( + "intro page 2 has no 'Start using KatSearch' button") + assert kit.rb_reach(before, after, + target="button|Start using KatSearch", + source="button|Continue →") + + @pytest.mark.rb(depth=2, jump_kind="reach", + expect="intro Start using KatSearch: the intro window (label|Welcome " + "to KatSearch! ) disappears and window|KatSearch appears") + def test_intro_start_using_swaps_intro_for_search_window(self, ax): + assert ks.intro_window(ax) is not None, "no intro window at launch" + assert ks.search_window(ax) is None, ( + "a search window already exists before the intro wizard finished") + before = ks.ks_showing(ax) + w = ks.rb_reach_search_window_via_intro(ax) + after = ks.ks_showing(ax) + assert w is not None, ( + "the intro wizard did not open a search window; titles=%s" + % (ks.window_titles(ax),)) + assert ks.intro_window(ax) is None, ( + "the intro window is still present after 'Start using KatSearch'") + missing = _missing(after, ["button|Search", "popup|items", "table|"]) + assert not missing, "search window incomplete after the intro wizard: %s" % missing + assert kit.rb_reach(before, after, target="window|KatSearch", + source="Welcome to KatSearch") + + +# =========================================================================== +# Shape deltas — preferences panes +# =========================================================================== + +# =========================================================================== +# Shape deltas — sub-surfaces of the search window +# =========================================================================== + +class TestAXStructureSearchSurfaces: + + @pytest.mark.rb(depth=1, jump_kind="reach", + expect="Action > Show Filter: placeholder|Filter... and button|search " + "appear in the search window") + def test_show_filter_reveals_filter_field(self, ax): + w = ks.rb_enter_search_window(ax) + assert w is not None, "no search window after File > New Search Window" + assert ks.filter_field(ax, w) is None, ( + "the filter field is already visible before Action > Show Filter") + before = ks.ks_showing(ax) + assert ks.pick_menu_item(ax, "Action", "Show Filter", settle=1.3), ( + "Action > Show Filter not found in the Action menu") + after = ks.ks_showing(ax) + assert ks.filter_field(ax, w) is not None, ( + "no field with placeholder 'Filter...' after Action > Show Filter") + assert "button|search" in after, ( + "the filter search field's magnifier button (button|search) did not appear") + assert kit.rb_reach(before, after, target="placeholder|Filter...") + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="search-window text_field count 1 -> 2 on Action > Show Filter, " + "restored to 1 on Action > Hide Filter") + def test_filter_toggle_changes_text_field_count(self, ax): + w = ks.rb_enter_search_window(ax) + assert w is not None, "no search window after File > New Search Window" + n0 = _count_role(ax, w, "text_field", 8) + assert ks.pick_menu_item(ax, "Action", "Show Filter", settle=1.3), ( + "Action > Show Filter not found in the Action menu") + n1 = _count_role(ax, w, "text_field", 8) + assert kit.rb_flip(n0, n1), ( + "the search-window text_field count did not change on Show Filter: stayed %d" % n0) + assert (n0, n1) == (1, 2), ( + "text_field count should go 1 -> 2 when the filter is shown, got %d -> %d" + % (n0, n1)) + assert ks.filter_field(ax, w) is not None, "filter field missing while shown" + assert ks.pick_menu_item(ax, "Action", "Hide Filter", settle=1.3), ( + "Action > Hide Filter not found in the Action menu") + n2 = _count_role(ax, w, "text_field", 8) + assert n2 == n0, ( + "hiding the filter should restore the text_field count to %d, got %d" % (n0, n2)) + assert ks.filter_field(ax, w) is None, ( + "the 'Filter...' field is still present after Action > Hide Filter") + + @pytest.mark.rb(depth=1, jump_kind="reach", + expect="'action' gear button AXShowMenu: the 4-item options menu " + "(menu_item|Case Sensitive …) appears") + def test_action_button_opens_options_menu(self, ax): + w = ks.rb_enter_search_window(ax) + assert w is not None, "no search window after File > New Search Window" + assert ks.sw_button(ax, "action", w) is not None, ( + "the search window has no 'action' gear button") + before = ks.ks_showing(ax) + items = ks.rb_enter_options_menu(ax, w) + after = ks.ks_showing(ax) + names = ks.item_names(items) + ks.screenshot_assert( + "structure_test_options_menu", + "A small drop-down menu opened from the gear button of the KatSearch search " + "window listing exactly: 'Case Sensitive', a separator, 'Skip Package " + "Contents', 'Skip Invisible Files', 'Skip System Folder'.") + ks.close_menus() + + missing = [n for n in OPTIONS_MENU_ITEMS if ks.find_item(items, n) is None] + assert not missing, ( + "advanced search-options menu missing %s; found %s" % (missing, names)) + assert len([n for n in names if n.strip()]) == len(OPTIONS_MENU_ITEMS), ( + "the options menu should hold exactly %d items %s, found %s" + % (len(OPTIONS_MENU_ITEMS), OPTIONS_MENU_ITEMS, names)) + assert kit.rb_reach(before, after, target="menu_item|Case Sensitive") + + @pytest.mark.rb(depth=1, jump_kind="reach", + expect="results-table header AXShowMenu: a columns menu with the 11 " + "'Show …' items (incl. menu_item|Show Uniform Type Identifier)") + def test_column_header_menu_lists_show_items(self, ax): + w = ks.rb_enter_search_window(ax) + assert w is not None, "no search window after File > New Search Window" + before = ks.ks_showing(ax) + items = ks.rb_enter_column_menu(ax, w) + after = ks.ks_showing(ax) + names = ks.item_names(items) + ks.screenshot_assert( + "structure_test_column_menu", + "A contextual drop-down over the results-table header of the KatSearch window " + "listing 'Show …' column items, with checkmarks next to Show Kind, Show Size " + "and Show Date Modified.") + ks.close_menus() + + shown = sorted({n.strip() for n in names if n.strip().startswith("Show ")}) + assert shown, "the results-table header exposed no contextual columns menu" + missing = [n for n in COLUMN_MENU_ITEMS if n not in shown] + assert not missing, "columns menu missing %s; found %s" % (missing, shown) + assert len(shown) == len(COLUMN_MENU_ITEMS), ( + "columns menu should hold exactly %d 'Show …' items, found %d: %s" + % (len(COLUMN_MENU_ITEMS), len(shown), shown)) + assert kit.rb_reach(before, after, + target="menu_item|Show Uniform Type Identifier") + + @pytest.mark.rb(depth=2, jump_kind="reach", + expect="selecting a results row: list|path (the path bar) appears under " + "the results table with its path-component labels") + def test_row_selection_reveals_path_bar(self, ax): + w = ks.rb_enter_search_window(ax) + assert w is not None, "no search window after File > New Search Window" + status = ks.run_search(ax, "Automator", w, first_result_timeout=12.0, settle=1.0) + rows = ks.result_rows(ax, w, 20) + assert rows, "no results rows after searching for 'Automator' (status=%r)" % (status,) + before = ks.ks_showing(ax) + assert not _has(before, "list|path"), ( + "the path bar is already present before any row was selected") + assert ks.select_first_row(ax, w), "could not select the first results row" + after = ks.ks_showing(ax) + pb = ks.path_bar(ax, w) + assert pb is not None, "no path bar element after selecting a results row" + comps = ks.texts_under(ax, pb.id, 40) + assert len(comps) >= 1, ( + "the path bar shows no path-component labels for the selected row") + assert kit.rb_reach(before, after, target="list|path") + ks.screenshot_assert( + "structure_test_path_bar", + "The KatSearch results window with one row selected (highlighted) and a " + "Finder-style path bar under the results table showing the volume ▸ System ▸ " + "Applications ▸ Automator components of the selected item.") + + @pytest.mark.rb(depth=2, jump_kind="reach", + expect="File > Save… after a search: sheet|save with button|Save, " + "button|Cancel, label|Save As: and a SearchResults-.txt field") + def test_save_sheet_appears_after_search(self, ax): + w = ks.rb_enter_search_window(ax) + assert w is not None, "no search window after File > New Search Window" + status = ks.run_search(ax, "Automator", w, first_result_timeout=12.0, settle=1.0) + assert ks.result_rows(ax, w, 5), ( + "no results to save after searching for 'Automator' (status=%r)" % (status,)) + before = ks.ks_showing(ax) + assert not _has(before, "sheet|"), "a sheet is already open before File > Save…" + sheet = ks.rb_enter_save_sheet(ax, w) + after = ks.ks_showing(ax) + vals = ks.sheet_field_values(ax, sheet) if sheet is not None else [] + ks.close_menus(2) + + assert sheet is not None, "no save sheet after File > Save… with results present" + missing = _missing(after, ["button|Save", "button|Cancel", "label|Save As:"]) + assert not missing, "save sheet widgets missing: %s" % missing + assert any(v.startswith("SearchResults-") for v in vals), ( + "the save sheet filename field should be prefilled 'SearchResults-.txt', " + "found %s" % (vals,)) + assert kit.rb_reach(before, after, target="sheet|save") + + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="sort headers ['Items','Kind','Date Modified','Size'] and exactly " + "4 table columns in a fresh search window") + def test_search_window_table_shape(self, ax): + w = ks.rb_enter_search_window(ax) + assert w is not None, "no search window after File > New Search Window" + headers = ks.sort_headers(ax, w) + n_cols = _count_role(ax, w, "column", 12) + assert kit.rb_value(headers, SORT_HEADERS), ( + "the default sort headers should be %s left-to-right, found %s" + % (SORT_HEADERS, headers)) + assert kit.rb_value(n_cols, 4), ( + "the results table should have exactly 4 default columns, found %d" % n_cols) + for name in SORT_HEADERS: + b = ks.sw_button(ax, name, w) + assert b is not None, "no %r column header button" % name + assert "sort" in ks.role_description(ax, b).lower(), ( + "the %r header should be a sort button, AXRoleDescription=%r" + % (name, ks.role_description(ax, b))) diff --git a/macos/sveinbjornt-katsearch/tests/test_ax_text.py b/macos/sveinbjornt-katsearch/tests/test_ax_text.py new file mode 100644 index 0000000000000000000000000000000000000000..4c71485d11a7636bf6458e0c9709058e99c58bab --- /dev/null +++ b/macos/sveinbjornt-katsearch/tests/test_ax_text.py @@ -0,0 +1,626 @@ +"""AX text tests for KatSearch — exact label/help/status content and text changes.""" + +import os +import re +import sys +import time + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +import pytest + +import ks_helpers as ks +import rb_testgen_kit as kit + +# --------------------------------------------------------------------------- +# module-local READ helpers (no navigation of their own — every test navigates +# explicitly with a ks.rb_enter_* / open_* / select_tab nav helper) +# --------------------------------------------------------------------------- + +TEXT_ROLES = ("label", "text_field", "text_area", "button", "popup", + "checkbox", "link", "menu_item") + + +def _raw_strings(ax, root_id, limit=300): + """Every AXValue / AXTitle / AXDescription string under root_id, UNSTRIPPED. + + ks.texts_under() strips its strings, which would hide the observed trailing + space in `Welcome to KatSearch! `, so the text-fidelity tests read raw.""" + out = [] + for e in ks.elements_under(ax, root_id, limit): + for s in (e.value, e.name): + if isinstance(s, str) and s.strip(): + out.append(str(s)) + return out + + +def _blob(strings): + """Newline-joined haystack — a trailing space in an expected string can only + match when the widget really carries it (the next char is '\\n').""" + return "\n".join(strings) + + +def _missing(expected, observed): + return [s for s in expected if s not in observed] + + +def _names(elements): + return [str(e.name or "") for e in elements] + + +def _help(ax, el): + if el is None: + return None + v = ax.get(el.id, ["AXHelp"]).get("AXHelp") + return str(v) if isinstance(v, str) else v + + +def _label_values(ax, root_id, limit=30): + """(non_empty, empty) AXValue strings of the label elements under root_id.""" + non_empty, empty = [], [] + for l in ax.find(role="label", root_id=root_id, max_results=limit): + v = l.value if isinstance(l.value, str) else "" + (non_empty if str(v).strip() else empty).append(str(v)) + return non_empty, empty + + +def _show_filter(ax, w): + """Reveal the results filter field via Action > Show Filter (idempotent).""" + f = ks.filter_field(ax, w) + if f is not None: + return f + ks.pick_menu_item(ax, "Action", "Show Filter", settle=1.0) + return ks.wait_until(lambda: ks.filter_field(ax, w), timeout=5.0) + + +# --------------------------------------------------------------------------- +# INTRO / WELCOME WINDOW +# --------------------------------------------------------------------------- + +class TestIntroText: + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="intro labels 'Welcome to KatSearch! ' (trailing space), " + "'Please select your preferred interface mode:', " + "'Application', 'Status Item' + button 'Continue →'") + def test_intro_page1_labels(self, ax): + w = ks.intro_window(ax) + assert w is not None, ( + "intro/welcome window not found (expected the window whose headline is " + "'Welcome to KatSearch! '); window titles observed=%r" % (ks.window_titles(ax),)) + raw = _raw_strings(ax, w.id, 300) + expected = ["Welcome to KatSearch! ", + "Please select your preferred interface mode:", + "Application", + "Status Item", + "Continue →"] + miss = _missing(expected, raw) + assert not miss, ("intro page-1 text missing %r; observed intro strings=%r" + % (miss, raw)) + # the headline keeps its trailing space (observed quirk) + assert kit.rb_value(_blob(raw), "Welcome to KatSearch! "), ( + "expected the exact headline 'Welcome to KatSearch! ' (with the trailing " + "space); observed=%r" % (raw,)) + ks.screenshot_assert( + "text_test_intro_page1_labels", + "The KatSearch dark welcome window: headline 'Welcome to KatSearch!', the " + "text 'Please select your preferred interface mode:', two large thumbnails " + "labelled 'Application' (a cartoon cat icon) and 'Status Item' (a menu-bar " + "screenshot), and a 'Continue →' button at the bottom.") + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="intro page 2 label 'Set keyboard shortcut for search window " + "(optional):'") + def test_intro_page2_shortcut_label(self, ax): + assert ks.intro_window(ax) is not None, ( + "intro window not found at launch; window titles=%r" % (ks.window_titles(ax),)) + assert ks.rb_enter_intro_page2(ax), ( + "could not navigate to intro page 2 (pressing 'Continue →' did not " + "produce 'Start using KatSearch'); intro strings=%r" + % (_raw_strings(ax, ks.intro_window(ax).id, 200) + if ks.intro_window(ax) else None,)) + w = ks.intro_window(ax) + assert w is not None, "intro window disappeared after entering page 2" + raw = _raw_strings(ax, w.id, 300) + expected = "Set keyboard shortcut for search window (optional):" + assert expected in raw, ("expected intro page-2 label %r; observed strings=%r" + % (expected, raw)) + assert kit.rb_value(_blob(raw), expected), ( + "expected %r in the intro page-2 text; observed=%r" % (expected, raw)) + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="intro checkbox names 'Launch on Login' and 'Check for Updates'") + def test_intro_page2_checkbox_names(self, ax): + assert ks.intro_window(ax) is not None, ( + "intro window not found at launch; window titles=%r" % (ks.window_titles(ax),)) + assert ks.rb_enter_intro_page2(ax), ( + "could not navigate to intro page 2 ('Continue →' did not re-title to " + "'Start using KatSearch')") + w = ks.intro_window(ax) + assert w is not None, "intro window disappeared after entering page 2" + names = _names(ax.find(role="checkbox", root_id=w.id, max_results=12)) + expected = ["Launch on Login", "Check for Updates"] + miss = _missing(expected, names) + assert not miss, ("intro checkbox name(s) missing %r; expected %r, observed " + "checkbox names=%r" % (miss, expected, names)) + assert kit.rb_value(_blob(names), "Launch on Login"), ( + "expected a checkbox titled exactly 'Launch on Login'; observed=%r" % (names,)) + assert kit.rb_value(_blob(names), "Check for Updates"), ( + "expected a checkbox titled exactly 'Check for Updates'; observed=%r" % (names,)) + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="AXHelp of both intro checkboxes == 'Enable this to launch " + "KatSearch every time you log in.'") + def test_intro_checkbox_help_strings(self, ax): + assert ks.intro_window(ax) is not None, ( + "intro window not found at launch; window titles=%r" % (ks.window_titles(ax),)) + assert ks.rb_enter_intro_page2(ax), "could not navigate to intro page 2" + w = ks.intro_window(ax) + assert w is not None, "intro window disappeared after entering page 2" + expected = "Enable this to launch KatSearch every time you log in." + cb_login = ks.checkbox_named(ax, "Launch on Login", w) + assert cb_login is not None, ( + "checkbox 'Launch on Login' not found on intro page 2; checkboxes=%r" + % (_names(ax.find(role="checkbox", root_id=w.id, max_results=12)),)) + got_login = _help(ax, cb_login) + assert kit.rb_value(got_login, expected), ( + "'Launch on Login' AXHelp: expected %r, observed %r" % (expected, got_login)) + # observed app quirk: the 'Check for Updates' checkbox carries the SAME help + cb_upd = ks.checkbox_named(ax, "Check for Updates", w) + assert cb_upd is not None, ( + "checkbox 'Check for Updates' not found on intro page 2; checkboxes=%r" + % (_names(ax.find(role="checkbox", root_id=w.id, max_results=12)),)) + got_upd = _help(ax, cb_upd) + assert kit.rb_value(got_upd, expected), ( + "'Check for Updates' AXHelp: expected the same string %r (observed app " + "quirk), observed %r" % (expected, got_upd)) + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="AXHelp of 'Empty keyboard shortcut' == 'To record a new " + "shortcut, click this button, and then type the new shortcut, " + "or press delete to clear an existing shortcut.'") + def test_intro_shortcut_recorder_help(self, ax): + assert ks.intro_window(ax) is not None, ( + "intro window not found at launch; window titles=%r" % (ks.window_titles(ax),)) + assert ks.rb_enter_intro_page2(ax), "could not navigate to intro page 2" + w = ks.intro_window(ax) + assert w is not None, "intro window disappeared after entering page 2" + btns = ax.find(role="button", root_id=w.id, max_results=20) + rec = ks.find_item(btns, "Empty keyboard shortcut") + assert rec is not None, ( + "button 'Empty keyboard shortcut' not found on intro page 2; button " + "names=%r" % (_names(btns),)) + expected = ("To record a new shortcut, click this button, and then type the new " + "shortcut, or press delete to clear an existing shortcut.") + got = _help(ax, rec) + assert kit.rb_value(got, expected), ( + "'Empty keyboard shortcut' AXHelp: expected %r, observed %r" + % (expected, got)) + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="button title flips 'Continue →' -> 'Start using KatSearch'") + def test_intro_continue_button_retitles(self, ax): + w = ks.intro_window(ax) + assert w is not None, ( + "intro window not found at launch; window titles=%r" % (ks.window_titles(ax),)) + b = ks.intro_button(ax, "Continue →", "Continue") + assert b is not None, ("intro page-1 button 'Continue →' not found; button " + "names=%r" + % (_names(ax.find(role="button", root_id=w.id, + max_results=20)),)) + before = str(b.name or "") + assert before == "Continue →", ( + "expected the page-1 button title 'Continue →', observed %r" % (before,)) + assert ks.rb_enter_intro_page2(ax), ( + "pressing 'Continue →' did not reach intro page 2") + b2 = ks.intro_button(ax, "Start using KatSearch", "Start") + after = str(b2.name or "") if b2 is not None else "" + assert kit.rb_flip(before, after), ( + "expected the button text to CHANGE; before=%r after=%r" % (before, after)) + assert after == "Start using KatSearch", ( + "expected the page-2 button title 'Start using KatSearch', observed %r " + "(before was %r)" % (after, before)) + + +# --------------------------------------------------------------------------- +# SEARCH WINDOW +# --------------------------------------------------------------------------- + +class TestSearchWindowText: + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="search-window labels 'Find', 'where', 'on' + one EMPTY status label") + def test_search_window_static_labels(self, ax): + w = ks.rb_enter_search_window(ax) + assert w is not None, ( + "could not open the search window (File > New Search Window); window " + "titles=%r" % (ks.window_titles(ax),)) + non_empty, empty = _label_values(ax, w.id, 30) + expected = ["Find", "where", "on"] + miss = _missing(expected, non_empty) + assert not miss, ("search-window label(s) missing %r; expected %r, observed " + "non-empty labels=%r" % (miss, expected, non_empty)) + assert kit.rb_value(_blob(non_empty), "Find"), ( + "expected a label reading exactly 'Find'; observed=%r" % (non_empty,)) + assert len(empty) >= 1, ( + "expected at least one EMPTY label (the results status line is '' before any " + "search); observed non-empty=%r empty=%r" % (non_empty, empty)) + ks.screenshot_assert( + "text_test_search_window_static_labels", + "The KatSearch search window titled 'KatSearch' with a query row reading " + "'Find [items] [name contains] [empty text field] where/on [volume]', a " + "'Search' button and an empty results table whose column headers read " + "Items / Kind / Date Modified / Size. The status line under the table is " + "empty.") + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="search-window title is exactly 'KatSearch' before any search") + def test_search_window_title(self, ax): + w = ks.rb_enter_search_window(ax) + assert w is not None, ( + "could not open the search window (File > New Search Window); window " + "titles=%r" % (ks.window_titles(ax),)) + title = str(w.name or "") + assert kit.rb_value(title, "KatSearch"), ( + "search-window title: expected the app name 'KatSearch', observed %r " + "(all window titles=%r)" % (title, ks.window_titles(ax))) + assert title == "KatSearch", ( + "expected the pre-search title to be exactly 'KatSearch' (it only becomes " + "'“” on - KatSearch' after a search); observed %r" + % (title,)) + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="sort-header texts left->right == ['Items','Kind','Date Modified','Size']") + def test_sort_header_texts(self, ax): + w = ks.rb_enter_search_window(ax) + assert w is not None, "could not open the search window (File > New Search Window)" + headers = ks.sort_headers(ax, w) + expected = ["Items", "Kind", "Date Modified", "Size"] + assert headers == expected, ( + "column header texts: expected %r, observed %r" % (expected, headers)) + assert kit.rb_value(_blob(headers), "Date Modified"), ( + "expected a header reading exactly 'Date Modified'; observed %r" % (headers,)) + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="popup display values 'items' and 'name contains'") + def test_popup_default_values(self, ax): + w = ks.rb_enter_search_window(ax) + assert w is not None, "could not open the search window (File > New Search Window)" + popups = ks.sw_popups(ax, w) + vals = [str(ks.popup_value(ax, p) or "") for p in popups] + assert len(popups) >= 3, ( + "expected 3 pop-up buttons (item type / match criterion / volume); observed " + "%d with values %r" % (len(popups), vals)) + assert kit.rb_value(vals[0], "items"), ( + "item-type popup: expected the default value 'items', observed %r " + "(all popup values=%r)" % (vals[0], vals)) + assert kit.rb_value(vals[1], "name contains"), ( + "match-criterion popup: expected the default value 'name contains', observed " + "%r (all popup values=%r)" % (vals[1], vals)) + assert vals[2].strip(), ( + "volume popup: expected a non-empty volume name (machine specific), observed " + "%r (all popup values=%r)" % (vals[2], vals)) + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="AXHelp 'Advanced search options.' on the action button and " + "'Authenticate to search with root privileges' on the lock button") + def test_action_and_lock_button_help(self, ax): + w = ks.rb_enter_search_window(ax) + assert w is not None, "could not open the search window (File > New Search Window)" + btns = ax.find(role="button", root_id=w.id, max_results=25) + action = ks.find_item(btns, "action") + assert action is not None, ( + "button 'action' (the gear / advanced-options button) not found; button " + "names=%r" % (_names(btns),)) + exp_action = "Advanced search options." + got_action = _help(ax, action) + assert kit.rb_value(got_action, exp_action), ( + "'action' button AXHelp: expected %r, observed %r" % (exp_action, got_action)) + lock = ks.find_item(btns, "lock") + assert lock is not None, ( + "button 'lock' not found; button names=%r" % (_names(btns),)) + exp_lock = "Authenticate to search with root privileges" + got_lock = _help(ax, lock) # READ ONLY — pressing it opens an admin prompt + assert kit.rb_value(got_lock, exp_lock), ( + "'lock' button AXHelp: expected %r, observed %r" % (exp_lock, got_lock)) + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="search-window text census: >=12 widgets WITH content " + "('Find','where','on','items','name contains','Search','action'," + "'lock','Items','Kind','Date Modified','Size') and >=2 without") + def test_text_widget_census(self, ax): + w = ks.rb_enter_search_window(ax) + assert w is not None, "could not open the search window (File > New Search Window)" + with_content, without_content = [], [] + for e in ks.elements_under(ax, w.id, 400): + if e.role not in TEXT_ROLES: + continue + s = str(e.name or "") or (str(e.value) if isinstance(e.value, str) else "") + (with_content if s.strip() else without_content).append((e.role, s)) + found = [s for _r, s in with_content] + expected = ["Find", "where", "on", "items", "name contains", "Search", + "action", "lock", "Items", "Kind", "Date Modified", "Size"] + miss = _missing(expected, found) + assert not miss, ( + "text census: expected content %r missing %r; widgets WITH content=%r" + % (expected, miss, with_content)) + assert len(with_content) >= 12, ( + "expected >=12 text-bearing widgets with content, observed %d: %r" + % (len(with_content), with_content)) + assert len(without_content) >= 2, ( + "expected >=2 text-bearing widgets WITHOUT content (the empty status label " + "and the empty search field), observed %d: %r" + % (len(without_content), without_content)) + # character count of each expected string equals the observed string's length + for exp in expected: + hits = [s for s in found if s == exp] + assert hits, "no widget text equal to %r; observed=%r" % (exp, found) + assert len(hits[0]) == len(exp), ( + "character count mismatch for %r: expected %d chars, observed %d (%r)" + % (exp, len(exp), len(hits[0]), hits[0])) + assert kit.rb_value(_blob(found), "name contains"), ( + "expected the text 'name contains' somewhere in the search window; " + "observed=%r" % (found,)) + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="status text '' -> 'Searching...' -> 'Found items (cancelled)'") + def test_status_label_transition(self, ax): + w = ks.rb_enter_search_window(ax) + assert w is not None, "could not open the search window (File > New Search Window)" + pre = ks.status_text(ax, w) + assert pre is None, ( + "expected an EMPTY status line before any search (no Found/Showing/Searching " + "text), observed %r" % (pre,)) + _ne, empty = _label_values(ax, w.id, 30) + assert empty, ("expected the results status label to exist and be '' before a " + "search; non-empty labels=%r" % (_ne,)) + before = "" + assert ks.set_search_text(ax, "Automator", w), ( + "could not type 'Automator' into the search field") + btn = ks.sw_button(ax, "Search", w) + assert btn is not None, ( + "button 'Search' not found; button names=%r" + % (_names(ax.find(role="button", root_id=w.id, max_results=25)),)) + ax.action(btn.id, "AXPress") + time.sleep(0.4) + mid = str(ks.status_text(ax, w) or "") + assert re.match(r"^(Searching|Found)", mid), ( + "right after pressing Search the status line should read 'Searching...' " + "(or already 'Found items ' if results streamed in), observed %r" % (mid,)) + ks.wait_until(lambda: ks.result_rows(ax, w, 2), timeout=12.0) + time.sleep(1.0) + ks.stop_search(ax, w) + after = str(ks.status_text(ax, w) or "") + assert kit.rb_flip(before, after), ( + "expected the status text to CHANGE; before=%r after=%r" % (before, after)) + assert re.match(r"^Found \d+ items", after), ( + "expected the post-search status to match '^Found \\d+ items', observed %r " + "(mid-search text was %r)" % (after, mid)) + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="status text after Stop contains '(cancelled)' " + "(e.g. 'Found 11 items (cancelled)')") + def test_status_after_stop_cancelled(self, ax): + w = ks.rb_enter_search_window(ax) + assert w is not None, "could not open the search window (File > New Search Window)" + status = ks.run_search(ax, "Automator", w, settle=1.0) + assert status, ( + "no status text after searching for 'Automator'; window titles=%r rows=%d" + % (ks.window_titles(ax), len(ks.result_rows(ax, w, 5)))) + assert kit.rb_value(status, "(cancelled)"), ( + "expected the stopped-search status to contain '(cancelled)', observed %r" + % (status,)) + assert re.match(r"^Found \d+ items", status), ( + "expected the status to match '^Found \\d+ items', observed %r" % (status,)) + ks.screenshot_assert( + "text_test_status_after_stop_cancelled", + "The KatSearch results table listing rows whose names contain 'Automator' " + "with icons, a Kind column (Application / Unix Executable File ...), a date " + "and a size; the bottom status line reads 'Found N items (cancelled)' and " + "the title bar shows “Automator” on the volume.") + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="filter field AXPlaceholderValue == 'Filter...' and " + "AXSubrole == 'AXSearchField'") + def test_filter_field_placeholder(self, ax): + w = ks.rb_enter_search_window(ax) + assert w is not None, "could not open the search window (File > New Search Window)" + assert ks.filter_field(ax, w) is None, ( + "the filter field should be HIDDEN before Action > Show Filter") + f = _show_filter(ax, w) + assert f is not None, ( + "Action > Show Filter did not reveal the filter field; text_field count=%d" + % (len(ax.find(role="text_field", root_id=w.id, max_results=8)),)) + attrs = ax.get(f.id, ["AXPlaceholderValue", "AXSubrole"]) + ph = attrs.get("AXPlaceholderValue") + sub = attrs.get("AXSubrole") + assert kit.rb_value(ph, "Filter..."), ( + "filter field placeholder: expected 'Filter...', observed %r (subrole=%r)" + % (ph, sub)) + assert str(ph) == "Filter...", ( + "filter field placeholder should be exactly 'Filter...', observed %r" % (ph,)) + assert kit.rb_value(sub, "AXSearchField"), ( + "filter field AXSubrole: expected 'AXSearchField', observed %r " + "(placeholder=%r)" % (sub, ph)) + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="status text starts with 'Showing 1 of' and ends with 'items' " + "when filtering on 'Automator.app'") + def test_filtered_status_showing(self, ax): + w = ks.rb_enter_search_window(ax) + assert w is not None, "could not open the search window (File > New Search Window)" + found = ks.run_search(ax, "Automator", w, settle=0.9) + assert found and found.startswith("Found"), ( + "expected a 'Found items' status before filtering, observed %r" % (found,)) + f = _show_filter(ax, w) + assert f is not None, "Action > Show Filter did not reveal the filter field" + assert ks.set_text(ax, f, "Automator.app"), ( + "could not type 'Automator.app' into the filter field") + status = ks.wait_until( + lambda: (ks.status_text(ax, w) or "").startswith("Showing") + and ks.status_text(ax, w), timeout=5.0) + status = str(status or ks.status_text(ax, w) or "") + assert kit.rb_value(status, "Showing 1 of"), ( + "filtered status: expected it to start with 'Showing 1 of', observed %r " + "(unfiltered was %r)" % (status, found)) + assert status.startswith("Showing 1 of") and status.endswith("items"), ( + "filtered status: expected 'Showing 1 of items', observed %r" % (status,)) + ks.screenshot_assert( + "text_test_filtered_status_showing", + "The KatSearch search window with a rounded filter search field (placeholder " + "'Filter...') at the bottom left holding the text 'Automator.app', exactly " + "one result row named Automator.app, and the status line reading 'Showing 1 " + "of N items'.") + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="a result row's 4 cell texts: name contains 'Automator', a " + "non-empty kind, a 'M/D/YY,' date and '-' or a human-friendly size") + def test_result_row_cell_texts(self, ax): + w = ks.rb_enter_search_window(ax) + assert w is not None, "could not open the search window (File > New Search Window)" + status = ks.run_search(ax, "Automator", w, settle=1.0) + assert status, "no status text after searching for 'Automator'" + rows = ks.result_rows(ax, w, 12) + assert rows, ("expected >=1 result row for 'Automator'; status=%r" % (status,)) + best = None + seen = [] + for r in rows: + cells = [str(c) for c in ks.row_cell_texts(ax, r)] + seen.append(cells) + if len(cells) == 4 and "automator" in cells[0].lower(): + best = cells + break + if best is None: + best = seen[0] + assert len(best) == 4, ( + "expected 4 text cells per result row (name, kind, date, size), observed %d: " + "%r (all rows read=%r)" % (len(best), best, seen)) + name, kind, date, size = best + assert kit.rb_value(name.lower(), "automator"), ( + "row name cell: expected it to contain 'Automator', observed %r (row=%r)" + % (name, best)) + assert kind.strip(), ( + "row kind cell: expected a non-empty kind string, observed %r (row=%r)" + % (kind, best)) + assert re.search(r"\d{1,2}/\d{1,2}/\d{2},", date), ( + "row date cell: expected a 'M/D/YY,' style date, observed %r (row=%r)" + % (date, best)) + assert size.strip() == "-" or re.match(r"^[\d.,]+\s*\S*B", size.strip()), ( + "row size cell: expected '-' (folder) or a human-friendly size like " + "'782 KB', observed %r (row=%r)" % (size, best)) + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="header texts 'Items, Kind, Date Modified, Size' -> " + "'Items, Date Modified, Size' after View > Show Kind") + def test_show_kind_changes_headers(self, ax): + w = ks.rb_enter_search_window(ax) + assert w is not None, "could not open the search window (File > New Search Window)" + before = ks.sort_headers(ax, w) + assert before == ["Items", "Kind", "Date Modified", "Size"], ( + "expected the default headers ['Items','Kind','Date Modified','Size'], " + "observed %r" % (before,)) + assert ks.pick_menu_item(ax, "View", "Show Kind", settle=1.1), ( + "could not activate View > Show Kind; View items=%r" + % (ks.item_names(ks.menu_items(ax, "View")),)) + ks.close_menus() + after = ks.sort_headers(ax, w) + assert kit.rb_flip(before, after), ( + "expected the header texts to CHANGE after View > Show Kind; before=%r " + "after=%r" % (before, after)) + assert after == ["Items", "Date Modified", "Size"], ( + "after hiding the Kind column the headers should read " + "['Items','Date Modified','Size'], observed %r (before=%r)" % (after, before)) + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="status text says 'folders' (^Found \\d+ folders) once the " + "item-type popup is switched to 'folders'") + def test_folders_status_wording(self, ax): + w = ks.rb_enter_search_window(ax) + assert w is not None, "could not open the search window (File > New Search Window)" + popups = ks.sw_popups(ax, w) + assert popups, "no pop-up buttons in the search window" + assert ks.set_item_type(ax, "folders", w), ( + "could not switch the item-type popup to 'folders'; popup value is %r" + % (ks.popup_value(ax, popups[0]),)) + status = ks.run_search(ax, "Automator", w, settle=1.0) + assert status, "no status text after searching with item type 'folders'" + assert kit.rb_value(status, "folders"), ( + "expected the status line to interpolate the item type 'folders' (instead of " + "'items'), observed %r" % (status,)) + assert re.match(r"^Found \d+ folders", status), ( + "expected the status to match '^Found \\d+ folders', observed %r" % (status,)) + assert " items" not in status, ( + "the status should no longer say 'items' when searching for folders, " + "observed %r" % (status,)) + + @pytest.mark.rb(depth=2, jump_kind="value", + expect="path-bar component texts include 'System' and 'Applications' " + "for /System/Applications/Automator.app") + def test_path_bar_component_texts(self, ax): + w = ks.rb_enter_search_window(ax) + assert w is not None, "could not open the search window (File > New Search Window)" + found = ks.run_search(ax, "Automator", w, settle=0.9) + assert found and found.startswith("Found"), ( + "expected a 'Found items' status, observed %r" % (found,)) + f = _show_filter(ax, w) + assert f is not None, "Action > Show Filter did not reveal the filter field" + assert ks.set_text(ax, f, "Automator.app"), ( + "could not type 'Automator.app' into the filter field") + ks.wait_until(lambda: (ks.status_text(ax, w) or "").startswith("Showing"), + timeout=5.0) + rows = ks.result_rows(ax, w, 5) + assert rows, ("expected the single filtered row 'Automator.app'; status=%r" + % (ks.status_text(ax, w),)) + assert ks.select_first_row(ax, w), ( + "could not select the filtered result row; row names=%r" + % (ks.row_names(ax, w, 5),)) + pb = ks.wait_until(lambda: ks.path_bar(ax, w), timeout=4.0) + assert pb is not None, ( + "no path bar (list 'path') after selecting a row; status=%r" + % (ks.status_text(ax, w),)) + comps = [str(c) for c in ks.texts_under(ax, pb.id, 60)] + expected = ["System", "Applications"] + miss = _missing(expected, comps) + assert not miss, ( + "path-bar component(s) missing %r for /System/Applications/Automator.app; " + "expected %r, observed components=%r (path element name=%r)" + % (miss, expected, comps, pb.name)) + assert kit.rb_value(_blob(comps), "Applications"), ( + "expected an 'Applications' path component; observed=%r" % (comps,)) + ks.screenshot_assert( + "text_test_path_bar_component_texts", + "A Finder-style path bar under the KatSearch results table showing the " + "volume ▸ System ▸ Applications ▸ Automator components of the " + "selected Automator.app row.") + + @pytest.mark.rb(depth=2, jump_kind="value", + expect="save-sheet labels 'Save As:', 'Where:', 'Tags:'") + def test_save_sheet_labels(self, ax): + w = ks.rb_enter_search_window(ax) + assert w is not None, "could not open the search window (File > New Search Window)" + status = ks.run_search(ax, "Automator", w, settle=0.9) + assert status, "no results, so File > Save… stays disabled" + try: + sheet = ks.rb_enter_save_sheet(ax, w) + assert sheet is not None, ( + "File > Save… did not open a save sheet; File items=%r" + % (ks.item_names(ks.menu_items(ax, "File")),)) + texts = [str(t) for t in ks.texts_under(ax, sheet.id, 300)] + expected = ["Save As:", "Where:", "Tags:"] + miss = _missing(expected, texts) + assert not miss, ( + "save-sheet label(s) missing %r; expected %r, observed sheet texts=%r" + % (miss, expected, texts)) + assert kit.rb_value(_blob(texts), "Save As:"), ( + "expected a 'Save As:' label in the save sheet; observed=%r" % (texts,)) + finally: + ks.close_menus(2) + + +# --------------------------------------------------------------------------- +# PREFERENCES WINDOW +# --------------------------------------------------------------------------- + +# --------------------------------------------------------------------------- +# ABOUT PANEL +# --------------------------------------------------------------------------- diff --git a/macos/sveinbjornt-katsearch/tests/testcase_counts.json b/macos/sveinbjornt-katsearch/tests/testcase_counts.json new file mode 100644 index 0000000000000000000000000000000000000000..b78b324467fa5dfcdae5e582d9da712760701844 --- /dev/null +++ b/macos/sveinbjornt-katsearch/tests/testcase_counts.json @@ -0,0 +1,47 @@ +{ + "ax_total": 105, + "vlm_total": 24, + "ax_by_lane": { + "test_ax_buttons.py": 14, + "test_ax_computation.py": 14, + "test_ax_menus.py": 27, + "test_ax_states.py": 15, + "test_ax_structure.py": 14, + "test_ax_text.py": 21 + }, + "vlm_by_dir": { + "buttons": 4, + "computation": 4, + "menus": 5, + "states": 1, + "structure": 6, + "text": 4 + }, + "vlm_names": [ + "buttons_action_gear_button_opens_options_menu.png", + "buttons_items_sort_header_toggles_direction.png", + "buttons_shortcut_recorder_button_is_present_with_help.png", + "buttons_start_using_katsearch_opens_search_window.png", + "computation_items_header_sort.png", + "computation_save_sheet_prefill.png", + "computation_search_automator_default.png", + "computation_window_title_after_search.png", + "menus_columns_menu_open.png", + "menus_new_search_window.png", + "menus_options_menu_open.png", + "menus_row_context_menu.png", + "menus_save_sheet.png", + "states_test_query_controls_lock_during_search.png", + "structure_test_column_menu.png", + "structure_test_intro_window.png", + "structure_test_menu_bar.png", + "structure_test_options_menu.png", + "structure_test_path_bar.png", + "structure_test_search_window.png", + "text_test_intro_page1_labels.png", + "text_test_path_bar_component_texts.png", + "text_test_search_window_static_labels.png", + "text_test_status_after_stop_cancelled.png" + ], + "frozen_at": "stage2_finalize" +} \ No newline at end of file diff --git a/macos/sveinbjornt-katsearch/tests/verifier_helpers.py b/macos/sveinbjornt-katsearch/tests/verifier_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..ce369cdae8db3a7427890d1636f8f5a3201dbef1 --- /dev/null +++ b/macos/sveinbjornt-katsearch/tests/verifier_helpers.py @@ -0,0 +1,753 @@ +""" +verifier_helpers.py — High-level AX testing patterns for macOS app verification. + +v6 core library. Encodes all robust testing patterns as reusable functions +so verifier agents call high-level APIs instead of building from scratch. + +Depends on: ax_helpers.py (AXHelper class) +""" + +import datetime +import os +import re +import signal +import subprocess +import time +from collections import Counter + +# --------------------------------------------------------------------------- +# Key codes (macOS virtual key codes) +# --------------------------------------------------------------------------- +KC_LEFT_ARROW = 123 +KC_RIGHT_ARROW = 124 +KC_UP_ARROW = 126 +KC_DOWN_ARROW = 125 +KC_SPACE = 49 +KC_RETURN = 36 +KC_TAB = 48 +KC_ESCAPE = 53 +KC_Q = 12 +KC_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": , "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)" + ) diff --git a/macos/sveinbjornt-katsearch/vlm_assertions.json b/macos/sveinbjornt-katsearch/vlm_assertions.json new file mode 100644 index 0000000000000000000000000000000000000000..098fdf7997b026a5b0dbaedd5ed96ff6f3a52600 --- /dev/null +++ b/macos/sveinbjornt-katsearch/vlm_assertions.json @@ -0,0 +1,335 @@ +{ + "schema_version": 2, + "instance_id": "macos/sveinbjornt-katsearch", + "grading": { + "mode": "deferred", + "model": null, + "scored_separately": true + }, + "totals": { + "assertions": 24, + "with_verdict": 0, + "calibrated": 0, + "usable": null, + "scored_records": 0, + "unbacked_records": 0 + }, + "assertions": [ + { + "id": "buttons_start_using_katsearch_opens_search_window.png", + "screenshot": "buttons_start_using_katsearch_opens_search_window.png", + "assertion": "The welcome/intro window is gone and a window titled “KatSearch” is showing a query row reading “Find [items ▾] [name contains ▾] [text field] where/on [volume ▾]”, a “Search” button, and an empty results table with the column headers Items / Kind / Date Modified / Size.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "buttons_start_using_katsearch_opens_search_window.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "buttons_shortcut_recorder_button_is_present_with_help.png", + "screenshot": "buttons_shortcut_recorder_button_is_present_with_help.png", + "assertion": "The welcome window now shows “Set keyboard shortcut for search window (optional):”, a keyboard image, a shortcut-recorder button, the checkboxes “Launch on Login” and “Check for Updates”, a “←” back button and a “Start using KatSearch” button.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "buttons_shortcut_recorder_button_is_present_with_help.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "buttons_action_gear_button_opens_options_menu.png", + "screenshot": "buttons_action_gear_button_opens_options_menu.png", + "assertion": "A small drop-down menu dropped from the gear/action button of the KatSearch search window listing “Case Sensitive”, “Skip Package Contents”, “Skip Invisible Files” and “Skip System Folder”.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "buttons_action_gear_button_opens_options_menu.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "buttons_items_sort_header_toggles_direction.png", + "screenshot": "buttons_items_sort_header_toggles_direction.png", + "assertion": "The results table lists rows whose names contain “Automator” with icons, a Kind column (Application / Unix Executable File …), a date and a size; the bottom status line reads “Found N items (cancelled)” and the rows are sorted by name in ascending order after two presses of the “Items” column header.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "buttons_items_sort_header_toggles_direction.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "computation_search_automator_default.png", + "screenshot": "computation_search_automator_default.png", + "assertion": "The KatSearch results table lists rows whose names all contain “Automator” with file icons, a Kind column (Application / Unix Executable File …), a Date Modified and a Size column; the bottom status line reads “Found N items (cancelled)” and the title bar shows “Automator” on the volume.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "computation_search_automator_default.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "computation_window_title_after_search.png", + "screenshot": "computation_window_title_after_search.png", + "assertion": "The KatSearch search window title bar reads “Automator” on the volume name, the results table below lists matching Automator rows, and the status line reads “Found N items (cancelled)”.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "computation_window_title_after_search.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "computation_save_sheet_prefill.png", + "screenshot": "computation_save_sheet_prefill.png", + "assertion": "A macOS save sheet is dropped over the KatSearch search window with “Save As:” prefilled “SearchResults-Automator.txt”, a Where popup, and Cancel / Save buttons.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "computation_save_sheet_prefill.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "computation_items_header_sort.png", + "screenshot": "computation_items_header_sort.png", + "assertion": "The KatSearch results table is sorted by the Items column — the row names are in ascending alphabetical order after two presses of the “Items” sort header — with the Items / Kind / Date Modified / Size headers visible and the status line reading “Found N items (cancelled)”.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "computation_items_header_sort.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "menus_new_search_window.png", + "screenshot": "menus_new_search_window.png", + "assertion": "Window titled “KatSearch” opened from File > New Search Window, showing the query row “Find [items ▾] [name contains ▾] [text field] where/on [volume ▾]”, a “Search” button and an empty results table with the column headers Items / Kind / Date Modified / Size.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "menus_new_search_window.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "menus_save_sheet.png", + "screenshot": "menus_save_sheet.png", + "assertion": "A macOS save sheet dropped over the KatSearch search window by File > Save…, with “Save As:” prefilled “SearchResults-Automator.txt”, a “Where:” popup and Cancel / Save buttons.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "menus_save_sheet.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "menus_columns_menu_open.png", + "screenshot": "menus_columns_menu_open.png", + "assertion": "The results-table header contextual menu is open: a drop-down of “Show …” items with checkmarks next to Show Kind, Show Size and Show Date Modified.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "menus_columns_menu_open.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "menus_row_context_menu.png", + "screenshot": "menus_row_context_menu.png", + "assertion": "A contextual menu over the selected results row listing Open, Open With, Show Package Contents, Move to Trash, Get Info, Show in Finder, Quick Look, Share and a Copy “” item.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "menus_row_context_menu.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "menus_options_menu_open.png", + "screenshot": "menus_options_menu_open.png", + "assertion": "A small drop-down menu opened from the search window's gear button listing “Case Sensitive”, “Skip Package Contents”, “Skip Invisible Files” and “Skip System Folder”, none of them checked.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "menus_options_menu_open.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "states_test_query_controls_lock_during_search.png", + "screenshot": "states_test_query_controls_lock_during_search.png", + "assertion": "The KatSearch search window during an active search: the query controls (the 'items' and 'name contains' popups, the volume popup and the search text field holding 'Automator') are greyed out / disabled, the primary button now reads 'Stop' instead of 'Search', a progress indicator is spinning, and the status line reports the running search.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "states_test_query_controls_lock_during_search.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "structure_test_menu_bar.png", + "screenshot": "structure_test_menu_bar.png", + "assertion": "The macOS menu bar at the top of the screen shows the KatSearch application menus in this order: KatSearch, File, Edit, View, Action, Window, Help (the Apple menu is at the far left).", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "structure_test_menu_bar.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "structure_test_intro_window.png", + "screenshot": "structure_test_intro_window.png", + "assertion": "A dark welcome window titled 'Welcome to KatSearch!' with the text 'Please select your preferred interface mode:', two large thumbnails labelled 'Application' (a cartoon cat icon) and 'Status Item' (a menu-bar screenshot), and a 'Continue →' button at the bottom.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "structure_test_intro_window.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "structure_test_search_window.png", + "screenshot": "structure_test_search_window.png", + "assertion": "A window titled 'KatSearch' with a query row reading 'Find [items] [name contains] [empty text field] where/on [volume popup]', a 'Search' button plus gear and lock buttons, and an empty results table whose column headers read Items / Kind / Date Modified / Size.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "structure_test_search_window.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "structure_test_options_menu.png", + "screenshot": "structure_test_options_menu.png", + "assertion": "A small drop-down menu opened from the gear button of the KatSearch search window listing exactly: 'Case Sensitive', a separator, 'Skip Package Contents', 'Skip Invisible Files', 'Skip System Folder'.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "structure_test_options_menu.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "structure_test_column_menu.png", + "screenshot": "structure_test_column_menu.png", + "assertion": "A contextual drop-down over the results-table header of the KatSearch window listing 'Show …' column items, with checkmarks next to Show Kind, Show Size and Show Date Modified.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "structure_test_column_menu.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "structure_test_path_bar.png", + "screenshot": "structure_test_path_bar.png", + "assertion": "The KatSearch results window with one row selected (highlighted) and a Finder-style path bar under the results table showing the volume ▸ System ▸ Applications ▸ Automator components of the selected item.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "structure_test_path_bar.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "text_test_intro_page1_labels.png", + "screenshot": "text_test_intro_page1_labels.png", + "assertion": "The KatSearch dark welcome window: headline 'Welcome to KatSearch!', the text 'Please select your preferred interface mode:', two large thumbnails labelled 'Application' (a cartoon cat icon) and 'Status Item' (a menu-bar screenshot), and a 'Continue →' button at the bottom.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "text_test_intro_page1_labels.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "text_test_search_window_static_labels.png", + "screenshot": "text_test_search_window_static_labels.png", + "assertion": "The KatSearch search window titled 'KatSearch' with a query row reading 'Find [items] [name contains] [empty text field] where/on [volume]', a 'Search' button and an empty results table whose column headers read Items / Kind / Date Modified / Size. The status line under the table is empty.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "text_test_search_window_static_labels.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "text_test_status_after_stop_cancelled.png", + "screenshot": "text_test_status_after_stop_cancelled.png", + "assertion": "The KatSearch results table listing rows whose names contain 'Automator' with icons, a Kind column (Application / Unix Executable File ...), a date and a size; the bottom status line reads 'Found N items (cancelled)' and the title bar shows “Automator” on the volume.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "text_test_status_after_stop_cancelled.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "text_test_path_bar_component_texts.png", + "screenshot": "text_test_path_bar_component_texts.png", + "assertion": "A Finder-style path bar under the KatSearch results table showing the volume ▸ System ▸ Applications ▸ Automator components of the selected Automator.app row.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "text_test_path_bar_component_texts.png", + "rigor": null, + "verdict": null, + "calibration": null + } + ], + "merged_from_files": 6, + "source_shapes": { + "dict_str": 24 + } +} \ No newline at end of file diff --git a/macos/tannerc-spf/LICENSE b/macos/tannerc-spf/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..8f068602a7eca1b8f809038d47977731576dd440 --- /dev/null +++ b/macos/tannerc-spf/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 Tanner Christensen + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, 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 THE +SOFTWARE. diff --git a/macos/tannerc-spf/instance.json b/macos/tannerc-spf/instance.json new file mode 100644 index 0000000000000000000000000000000000000000..4f64ce9bce704a110aaae0da2bcf62d7fd135ad9 --- /dev/null +++ b/macos/tannerc-spf/instance.json @@ -0,0 +1,10 @@ +{ + "schema_version": 1, + "instance_id": "macos/tannerc-spf", + "platform": "macos", + "repo": "https://github.com/tannerc/spf", + "commit": "c0084e7143e5333649bbc9d30db568a4ff23a046", + "patches": [], + "package": null, + "license": null +} \ No newline at end of file diff --git a/macos/tannerc-spf/reference/build.sh b/macos/tannerc-spf/reference/build.sh new file mode 100644 index 0000000000000000000000000000000000000000..954002baa6c275e759eebbe628a9b3c32aa5fa33 --- /dev/null +++ b/macos/tannerc-spf/reference/build.sh @@ -0,0 +1,80 @@ +#!/usr/bin/env bash +# +# build.sh — reproducible build for Spf (Screen polarization function) +# +# Spf is a small Cocoa/Swift macOS menu-bar app. It has NO third-party +# package dependencies (no CocoaPods / Swift Package Manager / npm) — it only +# links against system frameworks (Cocoa) and the bundled Swift runtime, so the +# sole build requirement is Apple's Xcode / command-line tools. +# +# The only change required to build with a modern SDK is raising the macOS +# deployment target. The checked-in project sets MACOSX_DEPLOYMENT_TARGET=10.10, +# which the macOS 14.x SDK no longer supports (linker fails looking for the +# removed 'libarclite_macosx.a'; supported range is 10.13–14.x). We fix this +# WITHOUT editing any source file by overriding the build setting on the +# xcodebuild command line, so nothing is lost on a fresh clone. +# +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" + +# --- Configuration (all paths derived from SCRIPT_DIR) ----------------------- +PROJECT="$SCRIPT_DIR/source/Spf.xcodeproj" +SCHEME="Spf" +CONFIG="Release" +DERIVED="$SCRIPT_DIR/build/DerivedData" +DEPLOYMENT_TARGET="10.13" # lowest target supported by the current SDK +OUTPUT_DIR="${APP_OUTPUT_DIR:-$SCRIPT_DIR}" +APP_NAME="Spf.app" + +echo "==> Spf build starting" +echo " SCRIPT_DIR = $SCRIPT_DIR" +echo " OUTPUT_DIR = $OUTPUT_DIR" + +# --- 1. Verify toolchain ----------------------------------------------------- +# This project pulls in NO installable packages, so there is nothing to +# brew/pod/npm install. The one hard requirement is a working Xcode toolchain. +if ! xcode-select -p >/dev/null 2>&1; then + echo "ERROR: Xcode command-line tools not found. Install Xcode from the App Store" >&2 + echo " (or run 'xcode-select --install') and re-run this script." >&2 + exit 1 +fi +if ! command -v xcodebuild >/dev/null 2>&1; then + echo "ERROR: 'xcodebuild' not on PATH. A full Xcode install is required." >&2 + exit 1 +fi +echo "==> Using $(xcodebuild -version | tr '\n' ' ')" + +if [ ! -e "$PROJECT" ]; then + echo "ERROR: Xcode project not found at $PROJECT" >&2 + exit 1 +fi + +# --- 2. Build ---------------------------------------------------------------- +# Code signing is disabled for a portable, machine-independent build. +echo "==> Building $SCHEME ($CONFIG) with deployment target $DEPLOYMENT_TARGET" +rm -rf "$DERIVED" +xcodebuild \ + -project "$PROJECT" \ + -scheme "$SCHEME" \ + -configuration "$CONFIG" \ + -derivedDataPath "$DERIVED" \ + MACOSX_DEPLOYMENT_TARGET="$DEPLOYMENT_TARGET" \ + CODE_SIGN_IDENTITY="" \ + CODE_SIGNING_ALLOWED=NO \ + CODE_SIGN_ENTITLEMENTS="" \ + clean build + +# --- 3. Stage the built .app ------------------------------------------------- +BUILT_APP="$DERIVED/Build/Products/$CONFIG/$APP_NAME" +if [ ! -d "$BUILT_APP" ]; then + echo "ERROR: expected app not found at $BUILT_APP" >&2 + exit 1 +fi + +mkdir -p "$OUTPUT_DIR" +rm -rf "$OUTPUT_DIR/$APP_NAME" +cp -R "$BUILT_APP" "$OUTPUT_DIR/$APP_NAME" + +echo "==> Build succeeded" +echo " App: $OUTPUT_DIR/$APP_NAME" diff --git a/macos/tannerc-spf/reference/launch.sh b/macos/tannerc-spf/reference/launch.sh new file mode 100644 index 0000000000000000000000000000000000000000..27f3f41577ac84041d933f8d00070f6aeccd3240 --- /dev/null +++ b/macos/tannerc-spf/reference/launch.sh @@ -0,0 +1,43 @@ +#!/usr/bin/env bash +# +# launch.sh — start the Spf menu-bar app. +# +# Spf is an LSUIElement (accessory) app: it has NO dock icon and NO window — +# when it launches it simply adds an icon to the macOS menu bar. It links only +# against system frameworks and its own bundled Swift runtime (loaded via an +# @executable_path/../Frameworks rpath baked into the binary), so no +# DYLD_*/QT_* runtime environment variables are required. +# +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +OUTPUT_DIR="${APP_OUTPUT_DIR:-$SCRIPT_DIR}" +APP_NAME="Spf.app" + +# Locate the built .app relative to the script (checked in likely order). +APP_PATH="" +for cand in \ + "$OUTPUT_DIR/$APP_NAME" \ + "$SCRIPT_DIR/$APP_NAME" \ + "$SCRIPT_DIR/build/DerivedData/Build/Products/Release/$APP_NAME" +do + if [ -d "$cand" ]; then + APP_PATH="$cand" + break + fi +done + +if [ -z "$APP_PATH" ]; then + echo "ERROR: $APP_NAME not found. Run 'bash build.sh' first." >&2 + exit 1 +fi + +echo "==> Launching $APP_PATH" + +# Use 'open -W' so this script's lifetime tracks the running app. As a menu-bar +# app, Spf keeps running until it is quit (via its status-bar menu or a signal). +if [ "$#" -gt 0 ]; then + exec open -W "$APP_PATH" --args "$@" +else + exec open -W "$APP_PATH" +fi diff --git a/macos/tannerc-spf/tests/ax_helpers.py b/macos/tannerc-spf/tests/ax_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..2418d7b8c75891c2d08906848d6a36517cb98135 --- /dev/null +++ b/macos/tannerc-spf/tests/ax_helpers.py @@ -0,0 +1,849 @@ +import os +import re +import time +import warnings +import subprocess +from dataclasses import dataclass, field +from typing import Optional +from 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", +} + + +@dataclass +class 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 None diff --git a/macos/tannerc-spf/tests/conftest.py b/macos/tannerc-spf/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..21a9b7debd04c0633d77a60d8269102790a13e84 --- /dev/null +++ b/macos/tannerc-spf/tests/conftest.py @@ -0,0 +1,584 @@ +""" +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 json +import os +import signal +import subprocess +import tempfile +import 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 _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 ` whose ARGUMENT merely contains the bundle path. + + A running .app's argv0 is /Contents/MacOS/, so we require that inner + executable path. The old bare-substring test (`app_path in args`) also matched the + lingering `open -W ` 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 == /Contents/MacOS/. + 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 ` 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//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//... — 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.fixture +def app_process(app_path): + pid = _launch_app(app_path) + yield pid + _kill_pid(pid) + + +@pytest.fixture +def 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.fixture +def 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")) diff --git a/macos/tannerc-spf/tests/rb_testgen_kit.py b/macos/tannerc-spf/tests/rb_testgen_kit.py new file mode 100644 index 0000000000000000000000000000000000000000..ccbbdd3c6136513161c133fbb4cefcfb0386d55c --- /dev/null +++ b/macos/tannerc-spf/tests/rb_testgen_kit.py @@ -0,0 +1,575 @@ +#!/usr/bin/env python3 +"""RB TestGen Kit (macOS/AX port of the Linux v7.5 kit) — a test's NAVIGATION +DEPTH and JUMP RIGOR are DECLARED (not inferred), uniformly recorded, and +self-auditable. + +DIFFERENCE FROM LINUX: macOS tests are **pytest** (methods on Test* classes taking +the `ax` fixture, plain asserts) — NOT standalone scripts calling R.record(). So the +DECLARATION is a pytest marker on the test method: + + import rb_testgen_kit as kit + + @pytest.mark.rb(depth=1, jump_kind="reach", expect="Preferences window visible") + def test_prefs_opens(self, ax_with_reset): + before = kit.rb_showing(ax_with_reset) + helpers.rb_reach_prefs(ax_with_reset) # a nav helper you name rb_reach_* / rb_enter_* + after = kit.rb_showing(ax_with_reset) + assert kit.rb_reach(before, after, target="Preferences", source="menu bar") + +conftest.py's pytest_runtest_makereport hook reads the marker + the test outcome and +writes {name, passed, depth, jump_kind, tier, expect} so the runner can fold it into +_results.json. The audits below then read those records (+ the test SOURCE). + +jump_kind (verbatim strings — the audit/stats key off them): + "none" no trigger; existence/structure only -> tier 0 + "liveness" only "did not crash / still alive" -> tier 1 (weak; avoid) + "reach" a real surface jump: the TARGET surface's element + APPEARED and the SOURCE surface's element DISAPPEARED -> tier 2 + "transition" a state flip (CHECKED/ENABLED/mode) before->after -> tier 2 + "value" a specific expected value/content was asserted -> tier 3 + +DEPTH is the number of surfaces crossed before the assertion (0 = home/first screen, +1 = one dialog/panel/submenu, 2+ = deeper). A flat-tree read of a deep element is +depth 0 — depth counts surfaces the test actually navigated through. + +REACH PROOF (so "reach" cannot be faked by reading a flat tree): + before = rb_showing(ax) + + 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('')" + python3 -c "import rb_testgen_kit as k; k.rb_lint('')" + python3 -c "import rb_testgen_kit as k; k.rb_lint_sources('')" + python3 -c "import rb_testgen_kit as k; k.rb_audit_depth('','')" +""" +from __future__ import annotations + +import ast +import glob +import json +import os +import re + +JUMP_KINDS = {"none": 0, "liveness": 1, "reach": 2, "transition": 2, "value": 3} + +# Double-axis quota TARGETS (fractions) — goals rb_audit REPORTS, NOT a hard gate. +QUOTAS = { + "existence_max": 0.30, # jump_kind=="none" share of ALL tests + "interactive_min": 0.60, # reach|transition|value share of ALL tests + "depth_ge1_min": 0.40, # depth>=1 share of INTERACTIVE tests + "depth_ge2_min": 0.10, # depth>=2 share of INTERACTIVE tests + "value_min": 0.25, # jump_kind=="value" share of INTERACTIVE tests +} + +# Depth family: a test "crosses a surface" iff it calls a member of the depth family. +# macOS accepts BOTH the naming convention rb_enter_*/rb_reach_* (write your own nav +# helper and NAME it so) AND the existing verifier_helpers/ax_helpers navigation +# functions (whitelist below) — so tests can reuse the mature reveal/navigate helpers. +DEPTH_FWD_RE = re.compile(r"^rb_(enter|reach)[a-z0-9_]*$") +DEPTH_BACK_RE = re.compile(r"^rb_back[a-z0-9_]*$") +# verifier_helpers / ax_helpers navigation functions that OPEN or move to a new surface. +FWD_WHITELIST = { + "ensure_ui_visible", "ensure_panel_open", "open_actions_menu", "open_menu", + "open_settings", "open_preferences", "open_dialog", "open_panel", "open_window", + "navigate_month", "navigate", "switch_tab", "switch_mode", "switch_page", + "select_tab", "reveal_window", "show_panel", "show_menu", +} +BACK_WHITELIST = { + "dismiss_menus", "dismiss_panel", "dismiss_any_dialog", "close_panel", + "close_window", "go_back", +} +# pytest fixtures that themselves navigate into a surface during setup (so a test taking +# one legitimately has depth>=1 without a nav call in its own body). `ax` does NOT navigate. +_NAV_FIXTURES = {"ax_with_reset", "open_panel"} +# MEASURED-TIER verdict families (ported from keliang): a tier2/3 jump_kind must be BACKED +# by its verdict function — transition->rb_flip*, value->rb_value*, reach->rb_reach* — whose +# bool result is the test's assertion. Self-named wrappers count by prefix. +TIER_FLIP_RE = re.compile(r"^rb_flip[a-z0-9_]*$") +TIER_VALUE_RE = re.compile(r"^rb_value[a-z0-9_]*$") +_JK_FAMILY = {"transition": "flip", "value": "value", "reach": "reach"} +# normalize plural (v73prep) / singular module names so a JSON module ("button") and a +# file stem ("buttons") join. +_MODULE_ALIAS = {"menus": "menu", "buttons": "button", "states": "state", + "structures": "structure", "texts": "text", + "computations": "computation", "workflows": "workflow"} + +_DEPTH = 0 # module-global surface counter for rb_enter/rb_back + + +def tier_of(jump_kind: str) -> int: + return JUMP_KINDS.get(jump_kind, 2) + + +def rb_reset_depth() -> None: + global _DEPTH + _DEPTH = 0 + + +def rb_enter(_surface: str = "") -> int: + """Call right after your test navigates into a new surface (dialog/panel/submenu).""" + global _DEPTH + _DEPTH += 1 + return _DEPTH + + +def rb_back() -> int: + global _DEPTH + _DEPTH = max(0, _DEPTH - 1) + return _DEPTH + + +def _walk_tree_nodes(node, out, seen): + """Yield 'role|name' for a macOS AXHelper.tree() dict node (+children).""" + if not isinstance(node, dict) or seen[0] >= 8000: + return + seen[0] += 1 + role = str(node.get("role") or "") + name = str(node.get("name") or node.get("value") or "") + if role or name: + out.add(f"{role}|{name}") + for c in (node.get("children") or []): + _walk_tree_nodes(c, out, seen) + + +def rb_showing(ax, max_depth: int = 12) -> set: + """Snapshot the currently-reachable AX subtree under the app as {"role|name"}. + macOS AX has no AT-SPI SHOWING/VISIBLE state, so we approximate "showing" by the + live AX tree (AXChildren) the app currently exposes — a new window/sheet/popover + adds its elements; a dismissed one removes them. Feed before+after a trigger to + rb_reach() so a 'reach' test proves a REAL surface change, not a flat-tree read. + Safe no-op (empty set) if `ax` cannot produce a tree.""" + out: set = set() + try: + tree = ax.tree(max_depth=max_depth) # AXHelper.tree() -> nested dict + except Exception: + return out + _walk_tree_nodes(tree, out, [0]) + return out + + +def rb_reach(before, after, target: str, source: str | None = None) -> bool: + """True-jump verdict: the TARGET surface's discriminating element newly APPEARED + AND (if given) the SOURCE surface's discriminating element DISAPPEARED. This is + what separates a real surface jump from reading an element that was always there.""" + before = set(before or []) + after = set(after or []) + t = target.lower() + appeared = any(t in k.lower() for k in (after - before)) + if source is None: + return appeared + s = source.lower() + src_before = any(s in k.lower() for k in before) + src_after = any(s in k.lower() for k in after) + return appeared and src_before and not src_after + + +def rb_flip(before, after, expect: str = "") -> bool: + """In-page STATE-FLIP verdict (tier2 `transition`): the observed state actually CHANGED + before->after (a CHECKED/ENABLED/mode/selection value read the two times). Pass its bool + as the test's assertion. Does NOT touch depth — an in-page flip is depth 0 unless you + navigated a surface to reach the control. You MAY write your own `rb_flip_()` 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_()` 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 | " + "{audit_depth|audit_tier} [results_dir]}") diff --git a/macos/tannerc-spf/tests/requirements.txt b/macos/tannerc-spf/tests/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..feef67ce2aadbaa26d12e6b01cff7b8ce89ecb5c --- /dev/null +++ b/macos/tannerc-spf/tests/requirements.txt @@ -0,0 +1,3 @@ +pytest +pytest-check +pyobjc diff --git a/macos/tannerc-spf/tests/test_ax_buttons.py b/macos/tannerc-spf/tests/test_ax_buttons.py new file mode 100644 index 0000000000000000000000000000000000000000..b6affc628dfd4032e2c2e8140264a66e9b2f33f5 --- /dev/null +++ b/macos/tannerc-spf/tests/test_ax_buttons.py @@ -0,0 +1,762 @@ +"""AX control/press tests for Spf — the status item + its menu items are its ONLY controls. + +Spf is an `LSUIElement` (agent) app: no Dock icon, no app menu bar, NO window until an +overlay is created — and therefore NO AXButton / AXCheckBox / AXRadioButton / AXSlider +anywhere in its tree. The pressable "buttons" of this app are the menu-bar status item +(`AXMenuBarItem`, subrole `AXMenuExtra`) and the `AXMenuItem`s it owns. Every test below +therefore presses a REAL control and asserts an OBSERVABLE effect (menu laid out / +overlay window created / overlay removed / state unchanged), not mere existence. +""" +import pytest +import rb_testgen_kit as kit + +# ════════════════════════════════════════════════════════════════════════════════ +# SPF_HELPER_BLOCK (embedded verbatim — the eval harness may copy only test_ax_*.py, +# so this module must be SELF-CONTAINED. Every function verified on the official app.) +# ════════════════════════════════════════════════════════════════════════════════ + +import json +import os +import re +import subprocess +import tempfile +import time + +import Quartz + +# ── Golden model constants (from MainMenu.xib + live AX tree) ──────────────── +OPACITY_ITEMS = ["5% opacity", "10% opacity", "25% opacity", "50% opacity"] +OPACITY_PCT = {"5% opacity": 5, "10% opacity": 10, "25% opacity": 25, "50% opacity": 50} +# Exact menu order in the official app ("" is the separator between Clear and Run test) +MENU_ORDER = ["5% opacity", "10% opacity", "25% opacity", "50% opacity", + "Clear", "", "Run test", "About", "Quit"] +# Big middle-of-screen sample region: below the menu bar, above the Dock. +SAMPLE_REGION = (200, 150, 1500, 700) + + +def screenshot_assert(test_name, description, results_dir=None): + """Screenshot + a SPECIFIC visual description for the VLM judge.""" + results_dir = results_dir or os.environ.get("RESULTS_DIR") or "/tmp/spf_results" + 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=8) + except Exception: + pass + af = os.path.join(ss_dir, "assertions.json") + data = {} + if os.path.exists(af): + try: + with open(af) as f: + data = json.load(f) + except Exception: + data = {} + data[f"{test_name}.png"] = description + with open(af, "w") as f: + json.dump(data, f, indent=2) + + +# ── AX geometry ────────────────────────────────────────────────────────────── + +def _pair(v): + m = re.findall(r"[-\d.]+", str(v)) + return (float(m[-2]), float(m[-1])) if len(m) >= 2 else None + + +def ax_size(ax, eid): + return _pair(ax.get(eid, ["AXSize"]).get("AXSize")) + + +def ax_pos(ax, eid): + return _pair(ax.get(eid, ["AXPosition"]).get("AXPosition")) + + +# ── Status item + menu discovery ───────────────────────────────────────────── + +def status_items(ax): + """Every menu-bar status item the app owns (AXMenuBarItem, subrole AXMenuExtra). + The official app happens to create two; only one carries the Spf menu.""" + return ax.find(role="menu_bar_item", max_results=8, max_depth=3) + + +def spf_status_item(ax): + """The status item that owns the Spf menu; falls back to the widest one.""" + best, best_w = None, -1.0 + for m in status_items(ax): + if ax.find(role="menu", root_id=m.id, max_results=2): + return m + w = (ax_size(ax, m.id) or (0.0, 0.0))[0] + if w > best_w: + best, best_w = m, w + return best + + +def spf_menu(ax): + """The AXMenu holding the opacity / Clear / Run test / About / Quit items.""" + menus = ax.find(role="menu", max_results=6) + for menu in menus: + names = [i.name or "" for i in + ax.find(role="menu_item", root_id=menu.id, max_results=30)] + if any("opacity" in n.lower() or "%" in n for n in names): + return menu + return menus[0] if menus else None + + +def menu_items(ax): + """The Spf menu's items IN ORDER (list of AXElement).""" + menu = spf_menu(ax) + return ax.find(role="menu_item", root_id=menu.id, max_results=40) if menu else [] + + +def item_names(ax): + return [i.name or "" for i in menu_items(ax)] + + +def item_map(ax): + return {i.name: i for i in menu_items(ax) if i.name} + + +def find_item(ax, *keywords): + """Locate a menu item by any keyword (case-insensitive substring) — tolerant of + a recreation naming things slightly differently.""" + for it in menu_items(ax): + low = (it.name or "").lower() + for kw in keywords: + if kw.lower() in low: + return it + return None + + +def item_enabled(ax, name_or_kw): + it = item_map(ax).get(name_or_kw) or find_item(ax, name_or_kw) + return None if it is None else bool(it.enabled) + + +def press_item(ax, name_or_el, settle=1.0): + """Activate a Spf menu item via AXPress (works with the menu closed OR open). + NOTE: AXPress may report failure while still succeeding on status-item menus, + so the return value only means 'the item was found and pressed'.""" + el = name_or_el + if isinstance(name_or_el, str): + el = item_map(ax).get(name_or_el) or find_item(ax, name_or_el) + if el is None: + return False + ax.action(el.id, "AXPress") + time.sleep(settle) + return True + + +def menu_is_open(ax): + """True when the status menu is laid out on screen (closed menus report 0x0).""" + menu = spf_menu(ax) + if menu is None: + return False + sz = ax_size(ax, menu.id) + return bool(sz and sz[0] > 1 and sz[1] > 1) + + +def dismiss_menu(ax): + """Close the status menu if it is open.""" + import verifier_helpers as vh + vh.send_key(vh.KC_ESCAPE) + time.sleep(0.4) + return not menu_is_open(ax) + + +# ── Overlay windows ───────────────────────────────────────────────────────── + +def overlay_windows(ax): + """The screen-polarizing overlay windows the app currently exposes via AX.""" + return ax.find(role="window", max_results=10, max_depth=1) + + +def cg_overlays(pid): + """CoreGraphics facts about the app's large overlay windows: window level + (`layer`), alpha and bounds. Only windows >= 400x300 count (skips status items).""" + opts = Quartz.kCGWindowListOptionAll | Quartz.kCGWindowListExcludeDesktopElements + out = [] + for w in (Quartz.CGWindowListCopyWindowInfo(opts, Quartz.kCGNullWindowID) or []): + if w.get("kCGWindowOwnerPID") != pid: + continue + b = w.get("kCGWindowBounds") or {} + if float(b.get("Width", 0)) >= 400 and float(b.get("Height", 0)) >= 300: + out.append({"layer": int(w.get("kCGWindowLayer", 0)), + "alpha": float(w.get("kCGWindowAlpha", 0)), + "x": float(b.get("X", 0)), "y": float(b.get("Y", 0)), + "w": float(b.get("Width", 0)), "h": float(b.get("Height", 0))}) + return out + + +def main_display_size(): + b = Quartz.CGDisplayBounds(Quartz.CGMainDisplayID()) + return (float(b.size.width), float(b.size.height)) + + +def n_displays(): + err, _ids, cnt = Quartz.CGGetActiveDisplayList(16, None, None) + return int(cnt) if err == 0 else 1 + + +def pid_at_screen_point(x=None, y=None): + """Which process owns the UI element at a screen point. A click-THROUGH overlay + (ignoresMouseEvents) never answers here — the window underneath does.""" + from ApplicationServices import (AXUIElementCopyElementAtPosition, + AXUIElementCreateSystemWide, AXUIElementGetPid) + w, h = main_display_size() + x = w / 2.0 if x is None else x + y = h / 2.0 if y is None else y + err, el = AXUIElementCopyElementAtPosition( + AXUIElementCreateSystemWide(), float(x), float(y), None) + if err != 0 or el is None: + return None + err2, pid = AXUIElementGetPid(el, None) + return int(pid) if err2 == 0 else None + + +def clear_overlays(ax): + """Reset the app to its clean state (no overlay on screen). Call in teardown.""" + for _ in range(3): + if not overlay_windows(ax): + return True + it = find_item(ax, "Clear") + if it is None: + return False + ax.action(it.id, "AXPress") + time.sleep(0.7) + return not overlay_windows(ax) + + +# ── Screen sampling: what the desktop actually LOOKS like through the overlay ─ + +def _cgimage_region(x, y, w, h): + img = Quartz.CGWindowListCreateImage( + Quartz.CGRectMake(x, y, w, h), Quartz.kCGWindowListOptionOnScreenOnly, + Quartz.kCGNullWindowID, Quartz.kCGWindowImageDefault) + if img is not None and Quartz.CGImageGetWidth(img) > 0: + return img + fd, p = tempfile.mkstemp(suffix=".png") + os.close(fd) + try: + subprocess.run(["screencapture", "-x", "-R", f"{x},{y},{w},{h}", p], timeout=10) + from CoreFoundation import (CFURLCreateFromFileSystemRepresentation, + kCFAllocatorDefault) + raw = p.encode() + url = CFURLCreateFromFileSystemRepresentation( + kCFAllocatorDefault, raw, len(raw), False) + src = Quartz.CGImageSourceCreateWithURL(url, None) + return Quartz.CGImageSourceCreateImageAtIndex(src, 0, None) if src else None + finally: + try: + os.unlink(p) + except OSError: + pass + + +def screen_rgb(region=SAMPLE_REGION, step=4): + """Mean (R, G, B) of a screen region, byte-order aware. None if unsamplable.""" + img = _cgimage_region(*region) + if img is None: + return None + prov = Quartz.CGImageGetDataProvider(img) + if prov is None: + return None + buf = bytes(Quartz.CGDataProviderCopyData(prov)) + bpr = Quartz.CGImageGetBytesPerRow(img) + W, H = Quartz.CGImageGetWidth(img), Quartz.CGImageGetHeight(img) + bpp = max(1, Quartz.CGImageGetBitsPerPixel(img) // 8) + little = bool(Quartz.CGImageGetBitmapInfo(img) & Quartz.kCGBitmapByteOrder32Little) + ri, gi, bi = (2, 1, 0) if little else (0, 1, 2) + tot, n = [0, 0, 0], 0 + for row in range(0, H, step): + off = row * bpr + for col in range(0, W, step): + p = off + col * bpp + if p + 2 >= len(buf): + continue + tot[0] += buf[p + ri] + tot[1] += buf[p + gi] + tot[2] += buf[p + bi] + n += 1 + return tuple(round(v / n, 2) for v in tot) if n else None + + +def screen_luma(region=SAMPLE_REGION, step=4): + rgb = screen_rgb(region, step) + return None if rgb is None else round(sum(rgb) / 3.0, 2) + + +# ── depth-family navigation (NAMED so rb_audit_depth sees the surface crossing) ─ + +def rb_enter_status_menu(ax): + """Cross into the status-bar MENU surface: press the Spf status item so its menu + is laid out on screen. Returns True once the menu reports a real size.""" + mbi = spf_status_item(ax) + if mbi is None: + return False + ax.action(mbi.id, "AXPress") + time.sleep(1.0) + if menu_is_open(ax): + return True + ax.click_element_cg(mbi.id) + time.sleep(1.0) + return menu_is_open(ax) + + +def rb_reach_overlay(ax, item="25% opacity"): + """Cross into the OVERLAY WINDOW surface by activating an opacity menu item. + Returns True once the app exposes at least one overlay window.""" + if not press_item(ax, item, settle=1.2): + return False + return len(overlay_windows(ax)) >= 1 + + +# ════════════════════════════════════════════════════════════════════════════════ +# END SPF_HELPER_BLOCK +# ════════════════════════════════════════════════════════════════════════════════ + + +# ── Roles that only exist INSIDE a window. Spf owns no window, so none may appear. +# Both AXHelper spellings are probed so the check cannot pass by a typo'd role. +WINDOW_CONTROL_ROLES = ("button", "checkbox", "check_box", "radio", "radio_button", + "slider", "toolbar", "tool_bar") + +# Golden menu labels -> semantic keywords (visible-label match, EN synonyms as fallback). +# NEVER matched by child index or tree path: a recreation may build the menu differently. +GOLDEN_ITEMS = [ + ("5% opacity", ("5% opacity", "5%")), + ("10% opacity", ("10% opacity", "10%")), + ("25% opacity", ("25% opacity", "25%")), + ("50% opacity", ("50% opacity", "50%")), + ("Clear", ("clear", "remove", "reset", "off")), + ("Run test", ("run test", "test")), + ("About", ("about", "info")), + ("Quit", ("quit", "exit")), +] +CLEAR_KEYWORDS = ("clear", "remove", "reset") + + +def opacity_item(ax, pct): + """The menu item that applies `pct`% opacity, located by its VISIBLE LABEL + ('5% opacity', '5%', '5 % opacity' …) — never by index or AX path.""" + want = int(pct) + exact = item_map(ax).get(f"{want}% opacity") + if exact is not None: + return exact + for it in menu_items(ax): + nm = it.name or "" + if "%" not in nm and "opac" not in nm.lower(): + continue + nums = [int(n) for n in re.findall(r"\d+", nm)] + if nums and nums[0] == want: + return it + return None + + +def opacity_target(ax, pct): + """What to hand press_item()/rb_reach_overlay() for `pct`% opacity.""" + return opacity_item(ax, pct) or f"{int(pct)}% opacity" + + +def clear_item(ax): + """The 'Clear' (remove-overlay) menu item, by visible label + synonyms.""" + return item_map(ax).get("Clear") or find_item(ax, *CLEAR_KEYWORDS) + + +def clear_enabled(ax): + it = clear_item(ax) + return None if it is None else bool(it.enabled) + + +def el_actions(el): + """The AX action names a control offers (what an AXButton test would record).""" + return list(getattr(el, "actions", None) or []) + + +def wait_overlay_count(ax, want, timeout=2.5): + """Poll until the app exposes exactly `want` overlay windows (window-server + bookkeeping is async). Returns the final list either way.""" + deadline = time.time() + timeout + wins = overlay_windows(ax) + while len(wins) != want and time.time() < deadline: + time.sleep(0.25) + wins = overlay_windows(ax) + return wins + + +def wait_menu_closed(ax, timeout=1.5): + """Poll until the status menu is no longer laid out on screen.""" + deadline = time.time() + timeout + while time.time() < deadline: + if not menu_is_open(ax): + return True + time.sleep(0.25) + return not menu_is_open(ax) + + +def describe(elements): + return [(e.role, e.name, bool(e.enabled)) for e in elements] + + +class TestSpfControls: + """Spf's control surface: 1 status item (AXMenuBarItem) + its menu items. + No AXButton exists in this app, so every 'button' test presses one of these.""" + + # ── 1. inventory: a menu-bar-only agent app ──────────────────────────────── + @pytest.mark.rb(depth=0, jump_kind="none", + expect="exactly the control inventory of a menu-bar-only agent app: " + "an enabled AXMenuBarItem status item offering AXPress, and ZERO " + "in-window controls (no button / check box / radio button / slider)") + def test_control_inventory_is_menu_bar_only(self, ax): + items = status_items(ax) + si = spf_status_item(ax) + assert si is not None, ( + "expected >=1 menu-bar status item (AXMenuBarItem, subrole AXMenuExtra) that " + f"carries the Spf menu; found {len(items)} menu_bar_item(s): {describe(items)}") + assert bool(si.enabled), ( + f"expected the Spf status item {si.name!r} to be ENABLED (it is the app's only " + f"entry point); AXEnabled reported {si.enabled!r}") + acts = el_actions(si) + assert "AXPress" in acts, ( + f"expected the status item to expose an action interface containing 'AXPress'; " + f"actions actually offered = {acts}") + assert len(acts) >= 1, f"expected >=1 AX action on the status item, found {acts}" + + wins = overlay_windows(ax) + assert wins == [], ( + "expected 0 windows at launch (Spf is LSUIElement and creates a window only " + f"when an overlay is applied); found {len(wins)}: {describe(wins)}") + for role in WINDOW_CONTROL_ROLES: + found = ax.find(role=role, max_results=20) + assert found == [], ( + f"expected 0 '{role}' controls anywhere in Spf's tree (it owns no window, so " + f"it has no in-window controls — its only controls are the status item and its " + f"menu items); found {len(found)}: {describe(found)}") + + # ── 2. every titled menu item is a real pressable control ───────────────── + @pytest.mark.rb(depth=0, jump_kind="none", + expect="all 8 titled menu items (5%/10%/25%/50% opacity, Clear, Run test, " + "About, Quit) have a name and offer both AXPress and AXPick, and " + "every untitled separator item is disabled") + def test_menu_items_are_named_pressable_controls(self, ax): + items = menu_items(ax) + assert items, ( + "expected the Spf status menu to expose its menu items via AX; found none " + f"(menus seen = {len(ax.find(role='menu', max_results=6))})") + + titled = [i for i in items if (i.name or "").strip()] + assert len(titled) >= 8, ( + f"expected >=8 NAMED (titled) menu items like {MENU_ORDER}; found " + f"{len(titled)} named of {len(items)} total: {describe(items)}") + + no_press = [i.name for i in titled if "AXPress" not in el_actions(i)] + assert not no_press, ( + "expected every titled menu item to offer the 'AXPress' action; these do not: " + f"{no_press} (actions found = {[(i.name, el_actions(i)) for i in titled]})") + no_pick = [i.name for i in titled if "AXPick" not in el_actions(i)] + assert not no_pick, ( + "expected every titled menu item to offer the 'AXPick' action too; these do not: " + f"{no_pick}") + no_act = [i.name for i in titled if len(el_actions(i)) < 1] + assert not no_act, f"expected >=1 AX action per menu item; these have none: {no_act}" + + resolved = {} + for label, kws in GOLDEN_ITEMS: + it = item_map(ax).get(label) or find_item(ax, *kws) + assert it is not None, ( + f"expected a menu item for {label!r} (accepting labels containing any of " + f"{list(kws)}); menu actually contains {item_names(ax)}") + resolved[label] = it.name + assert len(set(resolved.values())) == 8, ( + "expected the 8 golden menu labels to resolve to 8 DISTINCT items; got " + f"{resolved} from menu {item_names(ax)}") + + seps = [i for i in items if not (i.name or "").strip()] + bad_seps = [describe([i])[0] for i in seps if bool(i.enabled)] + assert not bad_seps, ( + "expected every untitled item (the separator between 'Clear' and 'Run test') to " + f"be DISABLED; these untitled items report enabled=True: {bad_seps}") + + # ── 3. pressing the status item ACTS: the menu gets laid out ────────────── + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="AXPress on the status item lays the menu out on screen: its AXSize " + "goes from 0x0 to at least 60x120 and the status item's AXSelected " + "flips False -> True") + def test_status_item_press_opens_menu(self, ax): + si = spf_status_item(ax) + assert si is not None, ( + f"expected a pressable Spf status item; found menu_bar_items=" + f"{describe(status_items(ax))}") + menu = spf_menu(ax) + assert menu is not None, ( + f"expected an AXMenu owned by the status item; menu items seen = {item_names(ax)}") + + size_before = ax_size(ax, menu.id) + sel_before = ax.get(si.id, ["AXSelected"]).get("AXSelected") + + opened = rb_enter_status_menu(ax) + + menu_after = spf_menu(ax) + size_after = ax_size(ax, menu_after.id) if menu_after else None + si_after = spf_status_item(ax) + sel_after = (ax.get(si_after.id, ["AXSelected"]).get("AXSelected") + if si_after else None) + screenshot_assert( + "buttons_status_menu_open", + "The Spf status-bar menu is open, dropped down from a small monochrome " + "sunglasses/polarizer icon at the right-hand end of the macOS menu bar. The menu is " + "a narrow white/dark dropdown listing, top to bottom: '5% opacity', '10% opacity', " + "'25% opacity', '50% opacity', 'Clear' (greyed out / disabled), a thin horizontal " + "separator line, 'Run test', 'About', 'Quit'. No application window and no Dock icon " + "belong to this app, and the desktop behind the menu is NOT darkened.", + os.environ.get("RESULTS_DIR")) + dismiss_menu(ax) + + assert size_before is not None and size_before[0] <= 1 and size_before[1] <= 1, ( + "expected the CLOSED status menu to report a collapsed AXSize of 0x0 before the " + f"press; got {size_before}") + assert opened, ( + "expected AXPress (then a real CG click as fallback) on the status item to OPEN its " + f"menu; the menu still reports AXSize={size_after} (a closed menu reports 0x0)") + assert size_after is not None and size_after[0] >= 60 and size_after[1] >= 120, ( + "expected the OPENED menu to be laid out at >=60x120pt (9 items of ~22pt each, " + f"~105x197 in the official app); got {size_after}") + assert bool(sel_before) is False, ( + f"expected the status item's AXSelected to be False before the press; got {sel_before!r}") + assert bool(sel_after) is True, ( + "expected the status item's AXSelected to flip to True while its menu is open; got " + f"{sel_after!r}") + + # ── 4. pressing '5% opacity' REACHES the overlay-window surface ─────────── + @pytest.mark.rb(depth=1, jump_kind="reach", + expect="pressing '5% opacity' creates the overlay surface: a new AX window " + "appears in the tree (one per display) where the app had none") + def test_press_5pct_creates_overlay_window(self, ax): + target = opacity_target(ax, 5) + assert not isinstance(target, str), ( + f"expected a '5% opacity' menu item; menu contains {item_names(ax)}") + before = kit.rb_showing(ax) + reached = rb_reach_overlay(ax, target) + after = kit.rb_showing(ax) + wins = wait_overlay_count(ax, n_displays()) + n_wins = len(wins) + clear_overlays(ax) + + assert reached, ( + "expected pressing '5% opacity' to make the app expose >=1 overlay window; it " + f"exposes {n_wins}: {describe(wins)}") + assert kit.rb_reach(before, after, target="window"), ( + "expected a NEW 'window' node to appear in Spf's AX tree after pressing " + f"'5% opacity' (reach proof); newly appeared nodes = {sorted(after - before)}") + assert n_wins == n_displays(), ( + f"expected exactly one full-screen overlay window per display " + f"({n_displays()} display(s)); found {n_wins}: {describe(wins)}") + + # ── 5. same for '50% opacity' ───────────────────────────────────────────── + @pytest.mark.rb(depth=1, jump_kind="reach", + expect="pressing '50% opacity' creates the overlay surface: a new AX window " + "appears in the tree, one per display") + def test_press_50pct_creates_overlay_window(self, ax): + target = opacity_target(ax, 50) + assert not isinstance(target, str), ( + f"expected a '50% opacity' menu item; menu contains {item_names(ax)}") + before = kit.rb_showing(ax) + reached = rb_reach_overlay(ax, target) + after = kit.rb_showing(ax) + wins = wait_overlay_count(ax, n_displays()) + n_wins = len(wins) + cg = cg_overlays(ax.get_pid()) + clear_overlays(ax) + + assert reached, ( + "expected pressing '50% opacity' to make the app expose >=1 overlay window; it " + f"exposes {n_wins}: {describe(wins)}") + assert kit.rb_reach(before, after, target="window"), ( + "expected a NEW 'window' node to appear in Spf's AX tree after pressing " + f"'50% opacity' (reach proof); newly appeared nodes = {sorted(after - before)}") + assert n_wins == n_displays(), ( + f"expected one overlay window per display ({n_displays()}); found {n_wins}: " + f"{describe(wins)}") + assert len(cg) >= 1, ( + "expected CoreGraphics to also report >=1 large (>=400x300) window owned by Spf " + f"after pressing '50% opacity'; CG reported {cg}") + + # ── 6. the overlay covers the whole main display ────────────────────────── + @pytest.mark.rb(depth=1, jump_kind="reach", + expect="pressing '10% opacity' creates a new AX window whose AXSize equals " + "the full main-display size (CGDisplayBounds) within 2pt") + def test_press_10pct_overlay_covers_display(self, ax): + target = opacity_target(ax, 10) + assert not isinstance(target, str), ( + f"expected a '10% opacity' menu item; menu contains {item_names(ax)}") + want_w, want_h = main_display_size() + before = kit.rb_showing(ax) + reached = rb_reach_overlay(ax, target) + after = kit.rb_showing(ax) + wins = wait_overlay_count(ax, n_displays()) + sizes = [ax_size(ax, w.id) for w in wins] + clear_overlays(ax) + + assert reached and wins, ( + "expected pressing '10% opacity' to create the overlay window; the app exposes " + f"{len(wins)} window(s): {describe(wins)}") + assert kit.rb_reach(before, after, target="window"), ( + "expected a NEW 'window' node in Spf's AX tree after pressing '10% opacity' " + f"(reach proof); newly appeared nodes = {sorted(after - before)}") + assert sizes and sizes[0] is not None, ( + f"expected the overlay window to report an AXSize; got {sizes}") + got_w, got_h = sizes[0] + assert abs(got_w - want_w) <= 2 and abs(got_h - want_h) <= 2, ( + f"expected the overlay to cover the entire main display ({want_w}x{want_h}, from " + f"CGDisplayBounds) within 2pt; AX reports {got_w}x{got_h}") + + # ── 7. 'Clear' REMOVES the overlay ─────────────────────────────────────── + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="with an overlay up, pressing 'Clear' removes it: AX windows go from " + ">=1 back to 0 and CoreGraphics reports no large Spf window") + def test_clear_removes_overlay(self, ax): + reached = rb_reach_overlay(ax, opacity_target(ax, 25)) + wins_before = wait_overlay_count(ax, n_displays()) + n_before = len(wins_before) + clear_el = clear_item(ax) + clear_en_with_overlay = clear_enabled(ax) + pressed = press_item(ax, clear_el or "Clear", settle=0.9) + wins_after = wait_overlay_count(ax, 0) + cg_after = cg_overlays(ax.get_pid()) + clear_en_after = clear_enabled(ax) + clear_overlays(ax) + + assert reached and n_before >= 1, ( + "precondition: expected '25% opacity' to create >=1 overlay window before testing " + f"'Clear'; found {n_before}: {describe(wins_before)}") + assert clear_en_with_overlay is True, ( + "expected 'Clear' to become ENABLED once an overlay exists; item_enabled reported " + f"{clear_en_with_overlay!r} (menu = {item_names(ax)})") + assert pressed, ( + f"expected to find and press a 'Clear' menu item; menu contains {item_names(ax)}") + assert wins_after == [], ( + "expected pressing 'Clear' to remove EVERY overlay window (AXWindows back to 0); " + f"{len(wins_after)} remain: {describe(wins_after)}") + assert cg_after == [], ( + "expected CoreGraphics to report no large (>=400x300) window owned by Spf after " + f"'Clear'; it still reports {cg_after}") + assert clear_en_after is False, ( + "expected 'Clear' to go back to DISABLED after it removed the overlay; " + f"item_enabled reported {clear_en_after!r}") + + # ── 8. all four opacity presses reuse ONE overlay per display ───────────── + @pytest.mark.rb(depth=1, jump_kind="value", + expect="after each of the four opacity presses in sequence the overlay " + "window count stays exactly n_displays() (1 here) — the app updates " + "its existing overlay instead of stacking new windows") + def test_opacity_presses_do_not_leak_windows(self, ax): + want = n_displays() + reached = rb_reach_overlay(ax, opacity_target(ax, 5)) + counts = [("5% opacity", len(wait_overlay_count(ax, want)))] + for pct in (10, 25, 50): + press_item(ax, opacity_target(ax, pct), settle=0.8) + counts.append((f"{pct}% opacity", len(wait_overlay_count(ax, want)))) + clear_overlays(ax) + + assert reached, ( + "precondition: expected '5% opacity' to create the first overlay window; counts " + f"observed = {counts}") + wrong = [(name, n) for name, n in counts if n != want] + assert not wrong, ( + f"expected the overlay window count to stay exactly {want} (one per display) after " + f"EVERY opacity press — the app must UPDATE its existing overlay, not stack new " + f"windows; deviating presses (item, count) = {wrong}; full sequence = {counts}") + + # ── 9. the DISABLED 'Clear' at launch is inert ──────────────────────────── + @pytest.mark.rb(depth=0, jump_kind="transition", + expect="'Clear' is disabled at launch and pressing it changes nothing: " + "still 0 overlay windows and 'Clear' still disabled") + def test_disabled_clear_at_launch_is_inert(self, ax): + en_before = clear_enabled(ax) + wins_before = overlay_windows(ax) + pressed = press_item(ax, clear_item(ax) or "Clear", settle=0.6) + wins_after = overlay_windows(ax) + en_after = clear_enabled(ax) + + assert en_before is False, ( + "expected 'Clear' to exist but be DISABLED at launch (no overlay to remove yet); " + f"item_enabled reported {en_before!r} — None means no Clear-like item was found " + f"among {item_names(ax)}") + assert wins_before == [], ( + f"precondition: expected 0 overlay windows at launch; found {describe(wins_before)}") + assert pressed, ( + f"expected to find a 'Clear' menu item to press; menu contains {item_names(ax)}") + assert wins_after == [], ( + "expected pressing the DISABLED 'Clear' to have NO effect (no overlay may be " + f"created); the app now exposes {len(wins_after)} window(s): {describe(wins_after)}") + assert en_after is False, ( + "expected 'Clear' to still be DISABLED after being pressed with no overlay present " + f"(state unchanged); item_enabled reported {en_after!r}") + + # ── 10. depth 2: press an item from INSIDE the open menu ───────────────── + @pytest.mark.rb(depth=2, jump_kind="reach", + expect="with the status menu open, activating '25% opacity' from inside it " + "creates a new overlay window in the AX tree and closes the menu") + def test_press_opacity_from_inside_open_menu(self, ax): + opened = rb_enter_status_menu(ax) + before = kit.rb_showing(ax) + reached = rb_reach_overlay(ax, opacity_target(ax, 25)) + after = kit.rb_showing(ax) + wins = wait_overlay_count(ax, n_displays()) + n_wins = len(wins) + closed = wait_menu_closed(ax) + screenshot_assert( + "buttons_overlay_active_25pct", + "The whole desktop is visibly darkened by one uniform semi-transparent black layer " + "at roughly 25% strength: the wallpaper, Dock and any window edges are still clearly " + "visible through the even grey-black tint, with no border, title bar or bright patch " + "anywhere and no colour cast other than darkening. The small monochrome Spf icon is " + "still present at the right-hand end of the macOS menu bar and the status menu is " + "closed.", + os.environ.get("RESULTS_DIR")) + clear_overlays(ax) + dismiss_menu(ax) + + assert opened, ( + "precondition: expected pressing the status item to OPEN its menu before activating " + "an item from inside it; the menu never reported a laid-out AXSize") + assert reached and n_wins >= 1, ( + "expected activating '25% opacity' from inside the OPEN menu to create the overlay " + f"window; the app exposes {n_wins} window(s): {describe(wins)}") + assert kit.rb_reach(before, after, target="window"), ( + "expected a NEW 'window' node to appear in Spf's AX tree after activating " + f"'25% opacity' from the open menu (reach proof); newly appeared nodes = " + f"{sorted(after - before)}") + assert closed, ( + "expected the status menu to CLOSE once one of its items was activated; it still " + f"reports a laid-out AXSize of {ax_size(ax, spf_menu(ax).id) if spf_menu(ax) else None}") + + # ── 11. the status item survives use and stays pressable ───────────────── + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="after an overlay has been applied and cleared, pressing the status " + "item still opens its menu (AXSize laid out again, >=60x120)") + def test_status_item_still_opens_menu_after_use(self, ax): + reached = rb_reach_overlay(ax, opacity_target(ax, 5)) + cleared = clear_overlays(ax) + wins_mid = overlay_windows(ax) + + reopened = rb_enter_status_menu(ax) + menu = spf_menu(ax) + size_after = ax_size(ax, menu.id) if menu else None + names_after = item_names(ax) + dismiss_menu(ax) + + assert reached, ( + "precondition: expected '5% opacity' to create an overlay window before re-testing " + "the status item") + assert cleared and wins_mid == [], ( + "precondition: expected 'Clear' to remove the overlay before re-testing the status " + f"item; {len(wins_mid)} window(s) remain: {describe(wins_mid)}") + assert reopened, ( + "expected the status item to STILL open its menu after an overlay was applied and " + f"cleared; the menu reports AXSize={size_after} (a closed menu reports 0x0)") + assert size_after is not None and size_after[0] >= 60 and size_after[1] >= 120, ( + f"expected the re-opened menu to be laid out at >=60x120pt; got {size_after}") + assert len([n for n in names_after if n.strip()]) >= 8, ( + "expected the re-opened menu to still list all 8 titled items; it lists " + f"{names_after}") diff --git a/macos/tannerc-spf/tests/test_ax_computation.py b/macos/tannerc-spf/tests/test_ax_computation.py new file mode 100644 index 0000000000000000000000000000000000000000..986b6766b28555bfe0c7c8da3072e356e94b9ee0 --- /dev/null +++ b/macos/tannerc-spf/tests/test_ax_computation.py @@ -0,0 +1,684 @@ +"""Spf computation tests — menu percentage -> measured screen darkening. + +Spf has no calculator and no text field. Its input->output computation is + menu item tag N -> NSColor(0,0,0, alpha=N*0.01) full-screen overlay +so the "output" is read by SAMPLING THE SCREEN (screen_rgb / screen_luma) and +comparing the measured luma ratio (after/before) against the golden bands +verified on the official app (recon.md 4.4 / 4.7). +""" +import pytest +import rb_testgen_kit as kit + +# =========================================================================== +# ==== SPF_HELPER_BLOCK (embedded VERBATIM — do not import, tests must be +# ==== self-contained; every function verified against the official Spf.app) +# =========================================================================== + +import json +import os +import re +import subprocess +import tempfile +import time + +import Quartz + +# ── Golden model constants (from MainMenu.xib + live AX tree) ──────────────── +OPACITY_ITEMS = ["5% opacity", "10% opacity", "25% opacity", "50% opacity"] +OPACITY_PCT = {"5% opacity": 5, "10% opacity": 10, "25% opacity": 25, "50% opacity": 50} +# Exact menu order in the official app ("" is the separator between Clear and Run test) +MENU_ORDER = ["5% opacity", "10% opacity", "25% opacity", "50% opacity", + "Clear", "", "Run test", "About", "Quit"] +# Big middle-of-screen sample region: below the menu bar, above the Dock. +SAMPLE_REGION = (200, 150, 1500, 700) + + +def screenshot_assert(test_name, description, results_dir=None): + """Screenshot + a SPECIFIC visual description for the VLM judge.""" + results_dir = results_dir or os.environ.get("RESULTS_DIR") or "/tmp/spf_results" + 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=8) + except Exception: + pass + af = os.path.join(ss_dir, "assertions.json") + data = {} + if os.path.exists(af): + try: + with open(af) as f: + data = json.load(f) + except Exception: + data = {} + data[f"{test_name}.png"] = description + with open(af, "w") as f: + json.dump(data, f, indent=2) + + +# ── AX geometry ────────────────────────────────────────────────────────────── + +def _pair(v): + m = re.findall(r"[-\d.]+", str(v)) + return (float(m[-2]), float(m[-1])) if len(m) >= 2 else None + + +def ax_size(ax, eid): + return _pair(ax.get(eid, ["AXSize"]).get("AXSize")) + + +def ax_pos(ax, eid): + return _pair(ax.get(eid, ["AXPosition"]).get("AXPosition")) + + +# ── Status item + menu discovery ───────────────────────────────────────────── + +def status_items(ax): + """Every menu-bar status item the app owns (AXMenuBarItem, subrole AXMenuExtra). + The official app happens to create two; only one carries the Spf menu.""" + return ax.find(role="menu_bar_item", max_results=8, max_depth=3) + + +def spf_status_item(ax): + """The status item that owns the Spf menu; falls back to the widest one.""" + best, best_w = None, -1.0 + for m in status_items(ax): + if ax.find(role="menu", root_id=m.id, max_results=2): + return m + w = (ax_size(ax, m.id) or (0.0, 0.0))[0] + if w > best_w: + best, best_w = m, w + return best + + +def spf_menu(ax): + """The AXMenu holding the opacity / Clear / Run test / About / Quit items.""" + menus = ax.find(role="menu", max_results=6) + for menu in menus: + names = [i.name or "" for i in + ax.find(role="menu_item", root_id=menu.id, max_results=30)] + if any("opacity" in n.lower() or "%" in n for n in names): + return menu + return menus[0] if menus else None + + +def menu_items(ax): + """The Spf menu's items IN ORDER (list of AXElement).""" + menu = spf_menu(ax) + return ax.find(role="menu_item", root_id=menu.id, max_results=40) if menu else [] + + +def item_names(ax): + return [i.name or "" for i in menu_items(ax)] + + +def item_map(ax): + return {i.name: i for i in menu_items(ax) if i.name} + + +def find_item(ax, *keywords): + """Locate a menu item by any keyword (case-insensitive substring) — tolerant of + a recreation naming things slightly differently.""" + for it in menu_items(ax): + low = (it.name or "").lower() + for kw in keywords: + if kw.lower() in low: + return it + return None + + +def item_enabled(ax, name_or_kw): + it = item_map(ax).get(name_or_kw) or find_item(ax, name_or_kw) + return None if it is None else bool(it.enabled) + + +def press_item(ax, name_or_el, settle=1.0): + """Activate a Spf menu item via AXPress (works with the menu closed OR open). + NOTE: AXPress may report failure while still succeeding on status-item menus, + so the return value only means 'the item was found and pressed'.""" + el = name_or_el + if isinstance(name_or_el, str): + el = item_map(ax).get(name_or_el) or find_item(ax, name_or_el) + if el is None: + return False + ax.action(el.id, "AXPress") + time.sleep(settle) + return True + + +def menu_is_open(ax): + """True when the status menu is laid out on screen (closed menus report 0x0).""" + menu = spf_menu(ax) + if menu is None: + return False + sz = ax_size(ax, menu.id) + return bool(sz and sz[0] > 1 and sz[1] > 1) + + +def dismiss_menu(ax): + """Close the status menu if it is open.""" + import verifier_helpers as vh + vh.send_key(vh.KC_ESCAPE) + time.sleep(0.4) + return not menu_is_open(ax) + + +# ── Overlay windows ───────────────────────────────────────────────────────── + +def overlay_windows(ax): + """The screen-polarizing overlay windows the app currently exposes via AX.""" + return ax.find(role="window", max_results=10, max_depth=1) + + +def cg_overlays(pid): + """CoreGraphics facts about the app's large overlay windows: window level + (`layer`), alpha and bounds. Only windows >= 400x300 count (skips status items).""" + opts = Quartz.kCGWindowListOptionAll | Quartz.kCGWindowListExcludeDesktopElements + out = [] + for w in (Quartz.CGWindowListCopyWindowInfo(opts, Quartz.kCGNullWindowID) or []): + if w.get("kCGWindowOwnerPID") != pid: + continue + b = w.get("kCGWindowBounds") or {} + if float(b.get("Width", 0)) >= 400 and float(b.get("Height", 0)) >= 300: + out.append({"layer": int(w.get("kCGWindowLayer", 0)), + "alpha": float(w.get("kCGWindowAlpha", 0)), + "x": float(b.get("X", 0)), "y": float(b.get("Y", 0)), + "w": float(b.get("Width", 0)), "h": float(b.get("Height", 0))}) + return out + + +def main_display_size(): + b = Quartz.CGDisplayBounds(Quartz.CGMainDisplayID()) + return (float(b.size.width), float(b.size.height)) + + +def n_displays(): + err, _ids, cnt = Quartz.CGGetActiveDisplayList(16, None, None) + return int(cnt) if err == 0 else 1 + + +def pid_at_screen_point(x=None, y=None): + """Which process owns the UI element at a screen point. A click-THROUGH overlay + (ignoresMouseEvents) never answers here — the window underneath does.""" + from ApplicationServices import (AXUIElementCopyElementAtPosition, + AXUIElementCreateSystemWide, AXUIElementGetPid) + w, h = main_display_size() + x = w / 2.0 if x is None else x + y = h / 2.0 if y is None else y + err, el = AXUIElementCopyElementAtPosition( + AXUIElementCreateSystemWide(), float(x), float(y), None) + if err != 0 or el is None: + return None + err2, pid = AXUIElementGetPid(el, None) + return int(pid) if err2 == 0 else None + + +def clear_overlays(ax): + """Reset the app to its clean state (no overlay on screen). Call in teardown.""" + for _ in range(3): + if not overlay_windows(ax): + return True + it = find_item(ax, "Clear") + if it is None: + return False + ax.action(it.id, "AXPress") + time.sleep(0.7) + return not overlay_windows(ax) + + +# ── Screen sampling: what the desktop actually LOOKS like through the overlay ─ + +def _cgimage_region(x, y, w, h): + img = Quartz.CGWindowListCreateImage( + Quartz.CGRectMake(x, y, w, h), Quartz.kCGWindowListOptionOnScreenOnly, + Quartz.kCGNullWindowID, Quartz.kCGWindowImageDefault) + if img is not None and Quartz.CGImageGetWidth(img) > 0: + return img + fd, p = tempfile.mkstemp(suffix=".png") + os.close(fd) + try: + subprocess.run(["screencapture", "-x", "-R", f"{x},{y},{w},{h}", p], timeout=10) + from CoreFoundation import (CFURLCreateFromFileSystemRepresentation, + kCFAllocatorDefault) + raw = p.encode() + url = CFURLCreateFromFileSystemRepresentation( + kCFAllocatorDefault, raw, len(raw), False) + src = Quartz.CGImageSourceCreateWithURL(url, None) + return Quartz.CGImageSourceCreateImageAtIndex(src, 0, None) if src else None + finally: + try: + os.unlink(p) + except OSError: + pass + + +def screen_rgb(region=SAMPLE_REGION, step=4): + """Mean (R, G, B) of a screen region, byte-order aware. None if unsamplable.""" + img = _cgimage_region(*region) + if img is None: + return None + prov = Quartz.CGImageGetDataProvider(img) + if prov is None: + return None + buf = bytes(Quartz.CGDataProviderCopyData(prov)) + bpr = Quartz.CGImageGetBytesPerRow(img) + W, H = Quartz.CGImageGetWidth(img), Quartz.CGImageGetHeight(img) + bpp = max(1, Quartz.CGImageGetBitsPerPixel(img) // 8) + little = bool(Quartz.CGImageGetBitmapInfo(img) & Quartz.kCGBitmapByteOrder32Little) + ri, gi, bi = (2, 1, 0) if little else (0, 1, 2) + tot, n = [0, 0, 0], 0 + for row in range(0, H, step): + off = row * bpr + for col in range(0, W, step): + p = off + col * bpp + if p + 2 >= len(buf): + continue + tot[0] += buf[p + ri] + tot[1] += buf[p + gi] + tot[2] += buf[p + bi] + n += 1 + return tuple(round(v / n, 2) for v in tot) if n else None + + +def screen_luma(region=SAMPLE_REGION, step=4): + rgb = screen_rgb(region, step) + return None if rgb is None else round(sum(rgb) / 3.0, 2) + + +# ── depth-family navigation (NAMED so rb_audit_depth sees the surface crossing) ─ + +def rb_enter_status_menu(ax): + """Cross into the status-bar MENU surface: press the Spf status item so its menu + is laid out on screen. Returns True once the menu reports a real size.""" + mbi = spf_status_item(ax) + if mbi is None: + return False + ax.action(mbi.id, "AXPress") + time.sleep(1.0) + if menu_is_open(ax): + return True + ax.click_element_cg(mbi.id) + time.sleep(1.0) + return menu_is_open(ax) + + +def rb_reach_overlay(ax, item="25% opacity"): + """Cross into the OVERLAY WINDOW surface by activating an opacity menu item. + Returns True once the app exposes at least one overlay window.""" + if not press_item(ax, item, settle=1.2): + return False + return len(overlay_windows(ax)) >= 1 + + +# =========================================================================== +# ==== end SPF_HELPER_BLOCK +# =========================================================================== + +# Golden accept bands per opacity item: (lo, hi, measured_on_official_app). +# ratio = mean screen luma AFTER the overlay / mean screen luma BEFORE it, so +# theory is exactly (1 - pct/100) because the overlay is pure black at alpha=pct/100. +OPACITY_BANDS = { + "5% opacity": (0.90, 0.99, 0.937), + "10% opacity": (0.84, 0.96, 0.890), + "25% opacity": (0.66, 0.84, 0.735), + "50% opacity": (0.40, 0.60, 0.481), +} + + +class TestSpfOpacityComputation: + """input (menu percentage) -> output (measured screen darkening).""" + + # ── 1-4: one test per opacity item ───────────────────────────────────── + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="screen luma ratio 0.90-0.99 after '5% opacity' " + "(theory 0.95; measured 0.937 on the official app)") + def test_5pct_darkens_screen_by_5pct(self, ax): + lo, hi, gold = OPACITY_BANDS["5% opacity"] + base = screen_luma() + assert base is not None and base > 5, f"screen not samplable (luma={base})" + reached = rb_reach_overlay(ax, "5% opacity") + after = screen_luma() + n_win = len(overlay_windows(ax)) + clear_overlays(ax) + assert reached, ( + f"'5% opacity' did not produce an overlay window " + f"(overlay windows={n_win}, expected >= 1)") + assert after is not None, "screen not samplable while the 5% overlay was up" + ratio = after / base + assert lo <= ratio <= hi, ( + f"5% opacity: measured luma ratio {ratio:.3f} " + f"(base={base}, after={after}) outside expected band " + f"{lo:.2f}-{hi:.2f} (theory 0.95, official app measured {gold})") + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="screen luma ratio 0.84-0.96 after '10% opacity' " + "(theory 0.90; measured 0.890 on the official app)") + def test_10pct_darkens_screen_by_10pct(self, ax): + lo, hi, gold = OPACITY_BANDS["10% opacity"] + base = screen_luma() + assert base is not None and base > 5, f"screen not samplable (luma={base})" + reached = rb_reach_overlay(ax, "10% opacity") + after = screen_luma() + n_win = len(overlay_windows(ax)) + clear_overlays(ax) + assert reached, ( + f"'10% opacity' did not produce an overlay window " + f"(overlay windows={n_win}, expected >= 1)") + assert after is not None, "screen not samplable while the 10% overlay was up" + ratio = after / base + assert lo <= ratio <= hi, ( + f"10% opacity: measured luma ratio {ratio:.3f} " + f"(base={base}, after={after}) outside expected band " + f"{lo:.2f}-{hi:.2f} (theory 0.90, official app measured {gold})") + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="screen luma ratio 0.66-0.84 after '25% opacity' " + "(theory 0.75; measured 0.735 on the official app)") + def test_25pct_darkens_screen_by_25pct(self, ax): + lo, hi, gold = OPACITY_BANDS["25% opacity"] + base = screen_luma() + assert base is not None and base > 5, f"screen not samplable (luma={base})" + reached = rb_reach_overlay(ax, "25% opacity") + after = screen_luma() + n_win = len(overlay_windows(ax)) + clear_overlays(ax) + assert reached, ( + f"'25% opacity' did not produce an overlay window " + f"(overlay windows={n_win}, expected >= 1)") + assert after is not None, "screen not samplable while the 25% overlay was up" + ratio = after / base + assert lo <= ratio <= hi, ( + f"25% opacity: measured luma ratio {ratio:.3f} " + f"(base={base}, after={after}) outside expected band " + f"{lo:.2f}-{hi:.2f} (theory 0.75, official app measured {gold})") + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="screen luma ratio 0.40-0.60 after '50% opacity' " + "(theory 0.50; measured 0.481 on the official app)") + def test_50pct_darkens_screen_by_50pct(self, ax): + lo, hi, gold = OPACITY_BANDS["50% opacity"] + base = screen_luma() + assert base is not None and base > 5, f"screen not samplable (luma={base})" + reached = rb_reach_overlay(ax, "50% opacity") + after = screen_luma() + n_win = len(overlay_windows(ax)) + clear_overlays(ax) + assert reached, ( + f"'50% opacity' did not produce an overlay window " + f"(overlay windows={n_win}, expected >= 1)") + assert after is not None, "screen not samplable while the 50% overlay was up" + ratio = after / base + assert lo <= ratio <= hi, ( + f"50% opacity: measured luma ratio {ratio:.3f} " + f"(base={base}, after={after}) outside expected band " + f"{lo:.2f}-{hi:.2f} (theory 0.50, official app measured {gold})") + + # ── 5: the four percentages are strictly ordered ─────────────────────── + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="luma(5%) > luma(10%) > luma(25%) > luma(50%), all below base " + "(official ratios 0.937 > 0.890 > 0.735 > 0.481)") + def test_opacity_ladder_is_strictly_monotonic(self, ax): + base = screen_luma() + assert base is not None and base > 5, f"screen not samplable (luma={base})" + reached = rb_reach_overlay(ax, "5% opacity") + readings = [screen_luma()] + for item in ("10% opacity", "25% opacity", "50% opacity"): + press_item(ax, item, settle=0.9) + readings.append(screen_luma()) + clear_overlays(ax) + assert reached, "'5% opacity' did not produce an overlay window" + assert all(r is not None for r in readings), ( + f"screen not samplable during the opacity ladder: readings={readings}") + ratios = [round(r / base, 3) for r in readings] + assert all(r < base for r in readings), ( + f"every overlay must darken the screen: base={base}, " + f"readings(5,10,25,50%)={readings} ratios={ratios}") + for i in range(3): + assert readings[i] > readings[i + 1], ( + f"opacity ladder not strictly decreasing at step {i}: " + f"readings(5,10,25,50%)={readings} ratios={ratios} (base={base}); " + f"expected luma(5%) > luma(10%) > luma(25%) > luma(50%), " + f"official ratios 0.937 > 0.890 > 0.735 > 0.481") + + # ── 6: the tint is neutral black, not a colour cast ──────────────────── + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="each of R,G,B scaled into 0.40-0.60 by '50% opacity' and the " + "channel-ratio spread <= 0.15 (neutral black, official 0.481)") + def test_50pct_tint_is_neutral_black(self, ax): + lo, hi, gold = OPACITY_BANDS["50% opacity"] + base = screen_rgb() + assert base is not None, "screen not samplable (screen_rgb() returned None)" + assert min(base) >= 4, ( + f"baseline channel too dark to measure a per-channel ratio: base RGB={base} " + f"(need every channel >= 4)") + reached = rb_reach_overlay(ax, "50% opacity") + after = screen_rgb() + clear_overlays(ax) + assert reached, "'50% opacity' did not produce an overlay window" + assert after is not None, "screen not samplable while the 50% overlay was up" + ratios = [round(a / b, 3) for a, b in zip(after, base)] + for name, r in zip("RGB", ratios): + assert lo <= r <= hi, ( + f"channel {name} ratio {r:.3f} outside {lo:.2f}-{hi:.2f} — the 50% " + f"overlay must be BLACK at alpha 0.5, not a colour cast. " + f"base RGB={base}, after RGB={after}, ratios(R,G,B)={ratios} " + f"(official app mean ratio {gold})") + spread = max(ratios) - min(ratios) + assert spread <= 0.15, ( + f"per-channel ratio spread {spread:.3f} > 0.15 → the tint is coloured, not " + f"neutral black. base RGB={base}, after RGB={after}, ratios(R,G,B)={ratios}") + + # ── 7: 'Run test' paints RED ─────────────────────────────────────────── + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="'Run test' overlay makes RED the dominant channel and >=2x its " + "baseline (official (20.1,37.2,50.9) -> (101.7,23.7,32.6) at +0.8s)") + def test_run_test_paints_red_overlay(self, ax): + base = screen_rgb() + assert base is not None, "screen not samplable (screen_rgb() returned None)" + pressed = press_item(ax, "Run test", settle=0.8) + after = screen_rgb() + n_win = len(overlay_windows(ax)) + clear_overlays(ax) + assert pressed, "no 'Run test' menu item found to press" + assert n_win >= 1, ( + f"'Run test' created no overlay window (overlay windows={n_win}, " + f"expected >= {n_displays()})") + assert after is not None, "screen not samplable while the 'Run test' overlay was up" + br, bg, bb = base + ar, ag, ab = after + assert ar > ag and ar > ab, ( + f"'Run test' must tint the screen RED: after RGB={after} — red {ar} is not the " + f"largest channel (green {ag}, blue {ab}). base RGB={base}; official app " + f"measured (20.1,37.2,50.9) -> (101.7,23.7,32.6)") + assert ar >= 2.0 * br, ( + f"'Run test' red channel only {ar} vs baseline {br} (x{ar / max(br, 0.01):.2f}), " + f"expected >= 2x (official x{101.7 / 20.1:.2f}). base RGB={base}, after RGB={after}") + assert ag < bg and ab < bb, ( + f"'Run test' must darken green+blue while boosting red: green {bg}->{ag}, " + f"blue {bb}->{ab} (base RGB={base}, after RGB={after}; official " + f"green 37.2->23.7, blue 50.9->32.6)") + + # ── 8: 'Run test' self-expires after its 4.5 s animation ─────────────── + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="'Run test' overlay removes itself within ~7s: windows 1->0, " + "Clear enabled->disabled, luma back within 3% of baseline") + def test_run_test_overlay_self_expires(self, ax): + base = screen_luma() + assert base is not None and base > 5, f"screen not samplable (luma={base})" + pressed = press_item(ax, "Run test", settle=0.8) + n_win_during = len(overlay_windows(ax)) + clear_during = item_enabled(ax, "Clear") + time.sleep(6.5) + n_win_after = len(overlay_windows(ax)) + clear_after = item_enabled(ax, "Clear") + luma_after = screen_luma() + clear_overlays(ax) + assert pressed, "no 'Run test' menu item found to press" + assert n_win_during >= 1, ( + f"at +0.8s after 'Run test' there must be an overlay window " + f"(measured {n_win_during}, expected >= {n_displays()})") + assert clear_during is True, ( + f"at +0.8s after 'Run test' the 'Clear' item must be ENABLED " + f"(measured enabled={clear_during})") + assert n_win_after == 0, ( + f"at +7.3s the 'Run test' overlay must have removed itself: overlay windows=" + f"{n_win_after}, expected 0 (official app: 1 window at +0.8s, 0 at +6.8s)") + assert clear_after is False, ( + f"after the 'Run test' overlay self-removed, 'Clear' must be DISABLED again " + f"(measured enabled={clear_after})") + assert luma_after is not None, "screen not samplable after the 'Run test' overlay expired" + drift = abs(luma_after - base) / base + assert drift <= 0.03, ( + f"screen did not return to baseline after 'Run test' expired: base luma={base}, " + f"after luma={luma_after} (drift {drift:.3%}, allowed <= 3%)") + + # ── 9: re-selecting an opacity UPDATES the same overlay ──────────────── + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="5% then 50% reuses the SAME overlay window (count stays " + "n_displays()) while the luma ratio drops 0.937 -> 0.481") + def test_reselecting_opacity_updates_same_overlay(self, ax): + base = screen_luma() + assert base is not None and base > 5, f"screen not samplable (luma={base})" + reached = rb_reach_overlay(ax, "5% opacity") + n1 = len(overlay_windows(ax)) + luma1 = screen_luma() + press_item(ax, "50% opacity", settle=0.9) + n2 = len(overlay_windows(ax)) + luma2 = screen_luma() + clear_overlays(ax) + assert reached, "'5% opacity' did not produce an overlay window" + assert luma1 is not None and luma2 is not None, ( + f"screen not samplable during the update test (luma1={luma1}, luma2={luma2})") + nd = n_displays() + assert n1 == nd and n2 == nd, ( + f"re-selecting an opacity must UPDATE the existing overlay, not add one: " + f"windows after 5%={n1}, after 50%={n2}, expected {nd} (one per display) both times") + ratio1, ratio2 = luma1 / base, luma2 / base + assert ratio2 < ratio1 - 0.2, ( + f"switching 5% -> 50% barely changed the screen: ratio(5%)={ratio1:.3f} " + f"(base={base}, luma={luma1}), ratio(50%)={ratio2:.3f} (luma={luma2}); " + f"expected ratio(50%) < ratio(5%) - 0.2 (official 0.481 vs 0.937)") + + # ── 10: 'Clear' restores the screen exactly ──────────────────────────── + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="after 50% overlay + Clear the sampled RGB returns to the " + "pre-overlay RGB within 2 units per channel (official: exact)") + def test_clear_restores_screen_exactly(self, ax): + lo, hi, _gold = OPACITY_BANDS["50% opacity"] + base = screen_rgb() + assert base is not None, "screen not samplable (screen_rgb() returned None)" + base_luma = sum(base) / 3.0 + assert base_luma > 5, f"screen too dark to measure (base RGB={base})" + reached = rb_reach_overlay(ax, "50% opacity") + dark = screen_rgb() + cleared = clear_overlays(ax) + restored = screen_rgb() + n_win = len(overlay_windows(ax)) + assert reached, "'50% opacity' did not produce an overlay window" + assert dark is not None and restored is not None, ( + f"screen not samplable (dark={dark}, restored={restored})") + dark_ratio = (sum(dark) / 3.0) / base_luma + assert dark_ratio <= hi, ( + f"50% overlay did not clearly darken the screen before Clear: ratio " + f"{dark_ratio:.3f} (base RGB={base}, dark RGB={dark}), expected <= {hi:.2f}") + assert cleared and n_win == 0, ( + f"'Clear' did not remove the overlay (clear_overlays={cleared}, " + f"overlay windows still {n_win}, expected 0)") + deltas = [round(r - b, 2) for r, b in zip(restored, base)] + assert max(abs(d) for d in deltas) <= 2.0, ( + f"'Clear' did not restore the screen: base RGB={base}, restored RGB={restored}, " + f"per-channel delta={deltas} (allowed +/-2.0 per channel; the official app " + f"returned to the EXACT pre-overlay RGB)") + + # ── 11: overlay geometry == the whole main display ───────────────────── + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="exactly n_displays() overlay windows at (0,0) sized " + "main_display_size() +/-2 (official (0,0) 1920x1080)") + def test_overlay_covers_entire_display(self, ax): + W, H = main_display_size() + nd = n_displays() + reached = rb_reach_overlay(ax, "25% opacity") + wins = cg_overlays(ax.get_pid()) + clear_overlays(ax) + assert reached, "'25% opacity' did not produce an overlay window" + assert len(wins) == nd, ( + f"expected exactly {nd} full-screen overlay window(s) (one per active display), " + f"got {len(wins)}: {wins}") + for w in wins: + assert abs(w["x"]) <= 2 and abs(w["y"]) <= 2, ( + f"overlay must start at the display origin (0, 0): measured " + f"({w['x']}, {w['y']}) — window={w}") + assert abs(w["w"] - W) <= 2 and abs(w["h"] - H) <= 2, ( + f"overlay must cover the WHOLE display {W:.0f}x{H:.0f} (+/-2): measured " + f"{w['w']:.0f}x{w['h']:.0f} — window={w}") + + # ── 12: the same 50% computation reached THROUGH the open menu ───────── + + @pytest.mark.rb(depth=2, jump_kind="value", + expect="opening the status menu then clicking '50% opacity' inside it " + "gives luma ratio 0.40-0.60 (official 0.481) and closes the menu") + def test_50pct_through_open_status_menu(self, ax): + lo, hi, gold = OPACITY_BANDS["50% opacity"] + base = screen_luma() + assert base is not None and base > 5, f"screen not samplable (luma={base})" + before_showing = kit.rb_showing(ax) + opened = rb_enter_status_menu(ax) # surface 1: the open status menu + reached = rb_reach_overlay(ax, "50% opacity") # surface 2: the overlay window + after = screen_luma() + after_showing = kit.rb_showing(ax) + window_appeared = kit.rb_reach(before_showing, after_showing, target="window") + still_open = menu_is_open(ax) + screenshot_assert( + "computation_50pct_overlay", + "The entire desktop is covered by a uniform half-strength black wash, so the " + "wallpaper looks about half as bright as normal (mean screen luma drops to ~48% " + "of its unobstructed value) while still being clearly visible through the tint. " + "The darkening is even edge-to-edge with no window frame, title bar, border, " + "shadow or dialog anywhere, and no colour cast (grey/black only, not red or " + "blue). The menu bar area at the top shows the Spf status icon and the status " + "menu is closed.", + os.environ.get("RESULTS_DIR")) + if still_open: + dismiss_menu(ax) + clear_overlays(ax) + assert after is not None, "screen not samplable while the 50% overlay was up" + ratio = after / base + assert lo <= ratio <= hi, ( + f"'50% opacity' activated from inside the OPEN status menu: measured luma ratio " + f"{ratio:.3f} (base={base}, after={after}) outside expected band {lo:.2f}-{hi:.2f} " + f"(official app measured {gold}); menu opened={opened}, overlay reached={reached}, " + f"new AX window appeared={window_appeared}") + assert not still_open, ( + f"activating '50% opacity' from inside the open status menu must close the menu " + f"(menu_is_open={still_open} after activation; menu opened={opened})") + + # ── 13: the overlay is click-through ────────────────────────────────── + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="with the 50% overlay up, the element at the screen centre belongs " + "to the app UNDERNEATH, never to Spf (ignoresMouseEvents = true)") + def test_overlay_is_click_through(self, ax): + spf_pid = ax.get_pid() + reached = rb_reach_overlay(ax, "50% opacity") + n_win = len(overlay_windows(ax)) + hit_pid = pid_at_screen_point() + cx, cy = (v / 2.0 for v in main_display_size()) + clear_overlays(ax) + assert reached and n_win >= 1, ( + f"'50% opacity' did not produce an overlay window to test click-through " + f"(overlay windows={n_win})") + assert hit_pid is not None, ( + f"no UI element found at the screen centre ({cx:.0f}, {cy:.0f}) while the 50% " + f"overlay covered it — expected the window UNDERNEATH to answer (Spf pid={spf_pid})") + assert hit_pid != spf_pid, ( + f"the overlay swallowed the hit test at the screen centre ({cx:.0f}, {cy:.0f}): " + f"element owner pid={hit_pid} == Spf pid={spf_pid}; the overlay must set " + f"ignoresMouseEvents = true so the element belongs to whatever is underneath") diff --git a/macos/tannerc-spf/tests/test_ax_menus.py b/macos/tannerc-spf/tests/test_ax_menus.py new file mode 100644 index 0000000000000000000000000000000000000000..603fbeac70c2191f940b070d904b2c7a49cf2af7 --- /dev/null +++ b/macos/tannerc-spf/tests/test_ax_menus.py @@ -0,0 +1,903 @@ +"""AX menu tests for Spf — the status-bar menu is the app's entire UI. + +Spf is an LSUIElement (agent) app: no Dock icon, no main menu bar, no window until an +overlay is created. Its whole UI is ONE NSStatusItem menu with 9 rows, so these menu +tests are the heart of the app: they must prove the menu really OPENS/CLOSES, that its +rows are laid out in the golden order, and that activating a row actually reaches the +overlay-window surface (depth 2 = open the menu, then act from inside it). +""" +import pytest +import rb_testgen_kit as kit + +# ═══════════════════════════════════════════════════════════════════════════════ +# SPF_HELPER_BLOCK (embedded VERBATIM — never imported, this module must be +# self-contained because the eval harness may copy only test_ax_*.py) +# ═══════════════════════════════════════════════════════════════════════════════ + +import json +import os +import re +import subprocess +import tempfile +import time + +import Quartz + +# ── Golden model constants (from MainMenu.xib + live AX tree) ──────────────── +OPACITY_ITEMS = ["5% opacity", "10% opacity", "25% opacity", "50% opacity"] +OPACITY_PCT = {"5% opacity": 5, "10% opacity": 10, "25% opacity": 25, "50% opacity": 50} +# Exact menu order in the official app ("" is the separator between Clear and Run test) +MENU_ORDER = ["5% opacity", "10% opacity", "25% opacity", "50% opacity", + "Clear", "", "Run test", "About", "Quit"] +# Big middle-of-screen sample region: below the menu bar, above the Dock. +SAMPLE_REGION = (200, 150, 1500, 700) + + +def screenshot_assert(test_name, description, results_dir=None): + """Screenshot + a SPECIFIC visual description for the VLM judge.""" + results_dir = results_dir or os.environ.get("RESULTS_DIR") or "/tmp/spf_results" + 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=8) + except Exception: + pass + af = os.path.join(ss_dir, "assertions.json") + data = {} + if os.path.exists(af): + try: + with open(af) as f: + data = json.load(f) + except Exception: + data = {} + data[f"{test_name}.png"] = description + with open(af, "w") as f: + json.dump(data, f, indent=2) + + +# ── AX geometry ────────────────────────────────────────────────────────────── + +def _pair(v): + m = re.findall(r"[-\d.]+", str(v)) + return (float(m[-2]), float(m[-1])) if len(m) >= 2 else None + + +def ax_size(ax, eid): + return _pair(ax.get(eid, ["AXSize"]).get("AXSize")) + + +def ax_pos(ax, eid): + return _pair(ax.get(eid, ["AXPosition"]).get("AXPosition")) + + +# ── Status item + menu discovery ───────────────────────────────────────────── + +def status_items(ax): + """Every menu-bar status item the app owns (AXMenuBarItem, subrole AXMenuExtra). + The official app happens to create two; only one carries the Spf menu.""" + return ax.find(role="menu_bar_item", max_results=8, max_depth=3) + + +def spf_status_item(ax): + """The status item that owns the Spf menu; falls back to the widest one.""" + best, best_w = None, -1.0 + for m in status_items(ax): + if ax.find(role="menu", root_id=m.id, max_results=2): + return m + w = (ax_size(ax, m.id) or (0.0, 0.0))[0] + if w > best_w: + best, best_w = m, w + return best + + +def spf_menu(ax): + """The AXMenu holding the opacity / Clear / Run test / About / Quit items.""" + menus = ax.find(role="menu", max_results=6) + for menu in menus: + names = [i.name or "" for i in + ax.find(role="menu_item", root_id=menu.id, max_results=30)] + if any("opacity" in n.lower() or "%" in n for n in names): + return menu + return menus[0] if menus else None + + +def menu_items(ax): + """The Spf menu's items IN ORDER (list of AXElement).""" + menu = spf_menu(ax) + return ax.find(role="menu_item", root_id=menu.id, max_results=40) if menu else [] + + +def item_names(ax): + return [i.name or "" for i in menu_items(ax)] + + +def item_map(ax): + return {i.name: i for i in menu_items(ax) if i.name} + + +def find_item(ax, *keywords): + """Locate a menu item by any keyword (case-insensitive substring) — tolerant of + a recreation naming things slightly differently.""" + for it in menu_items(ax): + low = (it.name or "").lower() + for kw in keywords: + if kw.lower() in low: + return it + return None + + +def item_enabled(ax, name_or_kw): + it = item_map(ax).get(name_or_kw) or find_item(ax, name_or_kw) + return None if it is None else bool(it.enabled) + + +def press_item(ax, name_or_el, settle=1.0): + """Activate a Spf menu item via AXPress (works with the menu closed OR open). + NOTE: AXPress may report failure while still succeeding on status-item menus, + so the return value only means 'the item was found and pressed'.""" + el = name_or_el + if isinstance(name_or_el, str): + el = item_map(ax).get(name_or_el) or find_item(ax, name_or_el) + if el is None: + return False + ax.action(el.id, "AXPress") + time.sleep(settle) + return True + + +def menu_is_open(ax): + """True when the status menu is laid out on screen (closed menus report 0x0).""" + menu = spf_menu(ax) + if menu is None: + return False + sz = ax_size(ax, menu.id) + return bool(sz and sz[0] > 1 and sz[1] > 1) + + +def dismiss_menu(ax): + """Close the status menu if it is open.""" + import verifier_helpers as vh + vh.send_key(vh.KC_ESCAPE) + time.sleep(0.4) + return not menu_is_open(ax) + + +# ── Overlay windows ───────────────────────────────────────────────────────── + +def overlay_windows(ax): + """The screen-polarizing overlay windows the app currently exposes via AX.""" + return ax.find(role="window", max_results=10, max_depth=1) + + +def cg_overlays(pid): + """CoreGraphics facts about the app's large overlay windows: window level + (`layer`), alpha and bounds. Only windows >= 400x300 count (skips status items).""" + opts = Quartz.kCGWindowListOptionAll | Quartz.kCGWindowListExcludeDesktopElements + out = [] + for w in (Quartz.CGWindowListCopyWindowInfo(opts, Quartz.kCGNullWindowID) or []): + if w.get("kCGWindowOwnerPID") != pid: + continue + b = w.get("kCGWindowBounds") or {} + if float(b.get("Width", 0)) >= 400 and float(b.get("Height", 0)) >= 300: + out.append({"layer": int(w.get("kCGWindowLayer", 0)), + "alpha": float(w.get("kCGWindowAlpha", 0)), + "x": float(b.get("X", 0)), "y": float(b.get("Y", 0)), + "w": float(b.get("Width", 0)), "h": float(b.get("Height", 0))}) + return out + + +def main_display_size(): + b = Quartz.CGDisplayBounds(Quartz.CGMainDisplayID()) + return (float(b.size.width), float(b.size.height)) + + +def n_displays(): + err, _ids, cnt = Quartz.CGGetActiveDisplayList(16, None, None) + return int(cnt) if err == 0 else 1 + + +def pid_at_screen_point(x=None, y=None): + """Which process owns the UI element at a screen point. A click-THROUGH overlay + (ignoresMouseEvents) never answers here — the window underneath does.""" + from ApplicationServices import (AXUIElementCopyElementAtPosition, + AXUIElementCreateSystemWide, AXUIElementGetPid) + w, h = main_display_size() + x = w / 2.0 if x is None else x + y = h / 2.0 if y is None else y + err, el = AXUIElementCopyElementAtPosition( + AXUIElementCreateSystemWide(), float(x), float(y), None) + if err != 0 or el is None: + return None + err2, pid = AXUIElementGetPid(el, None) + return int(pid) if err2 == 0 else None + + +def clear_overlays(ax): + """Reset the app to its clean state (no overlay on screen). Call in teardown.""" + for _ in range(3): + if not overlay_windows(ax): + return True + it = find_item(ax, "Clear") + if it is None: + return False + ax.action(it.id, "AXPress") + time.sleep(0.7) + return not overlay_windows(ax) + + +# ── Screen sampling: what the desktop actually LOOKS like through the overlay ─ + +def _cgimage_region(x, y, w, h): + img = Quartz.CGWindowListCreateImage( + Quartz.CGRectMake(x, y, w, h), Quartz.kCGWindowListOptionOnScreenOnly, + Quartz.kCGNullWindowID, Quartz.kCGWindowImageDefault) + if img is not None and Quartz.CGImageGetWidth(img) > 0: + return img + fd, p = tempfile.mkstemp(suffix=".png") + os.close(fd) + try: + subprocess.run(["screencapture", "-x", "-R", f"{x},{y},{w},{h}", p], timeout=10) + from CoreFoundation import (CFURLCreateFromFileSystemRepresentation, + kCFAllocatorDefault) + raw = p.encode() + url = CFURLCreateFromFileSystemRepresentation( + kCFAllocatorDefault, raw, len(raw), False) + src = Quartz.CGImageSourceCreateWithURL(url, None) + return Quartz.CGImageSourceCreateImageAtIndex(src, 0, None) if src else None + finally: + try: + os.unlink(p) + except OSError: + pass + + +def screen_rgb(region=SAMPLE_REGION, step=4): + """Mean (R, G, B) of a screen region, byte-order aware. None if unsamplable.""" + img = _cgimage_region(*region) + if img is None: + return None + prov = Quartz.CGImageGetDataProvider(img) + if prov is None: + return None + buf = bytes(Quartz.CGDataProviderCopyData(prov)) + bpr = Quartz.CGImageGetBytesPerRow(img) + W, H = Quartz.CGImageGetWidth(img), Quartz.CGImageGetHeight(img) + bpp = max(1, Quartz.CGImageGetBitsPerPixel(img) // 8) + little = bool(Quartz.CGImageGetBitmapInfo(img) & Quartz.kCGBitmapByteOrder32Little) + ri, gi, bi = (2, 1, 0) if little else (0, 1, 2) + tot, n = [0, 0, 0], 0 + for row in range(0, H, step): + off = row * bpr + for col in range(0, W, step): + p = off + col * bpp + if p + 2 >= len(buf): + continue + tot[0] += buf[p + ri] + tot[1] += buf[p + gi] + tot[2] += buf[p + bi] + n += 1 + return tuple(round(v / n, 2) for v in tot) if n else None + + +def screen_luma(region=SAMPLE_REGION, step=4): + rgb = screen_rgb(region, step) + return None if rgb is None else round(sum(rgb) / 3.0, 2) + + +# ── depth-family navigation (NAMED so rb_audit_depth sees the surface crossing) ─ + +def rb_enter_status_menu(ax): + """Cross into the status-bar MENU surface: press the Spf status item so its menu + is laid out on screen. Returns True once the menu reports a real size.""" + mbi = spf_status_item(ax) + if mbi is None: + return False + ax.action(mbi.id, "AXPress") + time.sleep(1.0) + if menu_is_open(ax): + return True + ax.click_element_cg(mbi.id) + time.sleep(1.0) + return menu_is_open(ax) + + +def rb_reach_overlay(ax, item="25% opacity"): + """Cross into the OVERLAY WINDOW surface by activating an opacity menu item. + Returns True once the app exposes at least one overlay window.""" + if not press_item(ax, item, settle=1.2): + return False + return len(overlay_windows(ax)) >= 1 + + +# ═══════════════════════════════════════════════════════════════════════════════ +# END SPF_HELPER_BLOCK — module-local test utilities below +# ═══════════════════════════════════════════════════════════════════════════════ + +RESULTS_DIR = os.environ.get("RESULTS_DIR") + +# A laid-out (open) Spf menu measured 105 x 197 pt on the official app. Accept any +# menu at least this roomy so a recreation with different padding/font still passes. +MIN_OPEN_W = 60.0 +MIN_OPEN_H = 120.0 +MIN_ROW_W = 60.0 +MIN_ROW_H = 10.0 +# Slack for comparing a row rect against the enclosing menu rect (menu padding / +# shadow insets differ between AppKit versions). +RECT_SLACK = 20.0 + + +def wait_until(pred, timeout=3.0, interval=0.25): + """Poll `pred` until it is truthy or `timeout` elapses. Returns the final bool.""" + deadline = time.time() + timeout + while True: + try: + if pred(): + return True + except Exception: + pass + if time.time() >= deadline: + return False + time.sleep(interval) + + +def menu_rect(ax): + """(position, size) of the Spf AXMenu, or (None, None) if the menu is missing.""" + menu = spf_menu(ax) + if menu is None: + return None, None + return ax_pos(ax, menu.id), ax_size(ax, menu.id) + + +def menu_size(ax): + return menu_rect(ax)[1] + + +def status_selected(ax, el_id): + """AXSelected of a status item as a plain bool (absent/unreadable -> False).""" + return bool(ax.get(el_id, ["AXSelected"]).get("AXSelected")) + + +def item_rows(ax): + """[(title, pos, size, element)] for every row of the Spf menu, in tree order.""" + rows = [] + for it in menu_items(ax): + rows.append((it.name or "", ax_pos(ax, it.id), ax_size(ax, it.id), it)) + return rows + + +def pct_of(title): + """Leading integer percentage in a row title ('25% opacity' -> 25), else None.""" + m = re.search(r"(\d+)\s*%", title or "") + return int(m.group(1)) if m else None + + +def neighbours_of(names, title): + """(previous, next) row titles around `title`, '' past either end.""" + if title not in names: + return "", "" + i = names.index(title) + prev = names[i - 1] if i - 1 >= 0 else "" + nxt = names[i + 1] if i + 1 < len(names) else "" + return prev, nxt + + +class TestSpfMenus: + """The Spf status-bar menu: open/close behaviour, golden layout, and the + depth-2 paths that activate a row from INSIDE the open menu.""" + + # ── 1. the menu OPENS from the status item ──────────────────────────────── + @pytest.mark.rb( + depth=1, jump_kind="transition", + expect="Spf AXMenu size goes from 0x0 (closed) to a laid-out rect " + ">= 60x120 pt and the status item's AXSelected flips False -> True") + def test_status_item_press_opens_menu(self, ax): + mbi = spf_status_item(ax) + assert mbi is not None, ( + "expected at least one Spf status item (AXMenuBarItem / AXMenuExtra) in the " + "AX tree, found none; menu_bar_items=" + f"{[(m.role, m.name) for m in status_items(ax)]}") + + before_size = menu_size(ax) + before_selected = status_selected(ax, mbi.id) + assert before_size is not None, ( + "expected the Spf AXMenu to exist in the AX tree even while closed, " + "but no AXMenu with opacity rows was found") + assert before_selected is False, ( + "expected the status item to start UNSELECTED (AXSelected False) before the " + f"menu is opened, got AXSelected={before_selected!r}") + + opened = rb_enter_status_menu(ax) + after_size = menu_size(ax) + after_selected = status_selected(ax, mbi.id) + + assert opened, ( + "expected pressing the Spf status item to OPEN its menu (AXMenu laid out on " + f"screen); menu size before={before_size} after={after_size}, " + f"AXSelected before={before_selected} after={after_selected}") + assert after_size is not None, ( + "expected the open AXMenu to report an AXSize, got None") + assert after_size[0] > before_size[0] and after_size[1] > before_size[1], ( + "expected the AXMenu rect to GROW when the menu opens, got " + f"before={before_size} -> after={after_size}") + assert after_size[0] >= MIN_OPEN_W and after_size[1] >= MIN_OPEN_H, ( + f"expected the open Spf menu to be at least {MIN_OPEN_W}x{MIN_OPEN_H} pt " + f"(official app: 105x197 for 9 rows), got {after_size}") + assert after_selected is True, ( + "expected the status item's AXSelected to flip False -> True while its menu " + f"is open, got before={before_selected} after={after_selected}") + + screenshot_assert( + "menus_status_menu_open", + "The Spf status-bar menu is open, dropped down from the small monochrome " + "Spf icon in the top-right macOS menu bar. The narrow white menu panel " + "lists, top to bottom: '5% opacity', '10% opacity', '25% opacity', " + "'50% opacity', a greyed-out (disabled) 'Clear', a thin horizontal " + "separator line, then 'Run test', 'About' and 'Quit'. The desktop behind " + "the menu is NOT tinted or darkened (no overlay is active).", + RESULTS_DIR) + dismiss_menu(ax) + + # ── 2. Escape CLOSES the menu ──────────────────────────────────────────── + @pytest.mark.rb( + depth=1, jump_kind="transition", + expect="after Escape the Spf AXMenu is no longer laid out (menu_is_open False) " + "and the status item's AXSelected flips True -> False") + def test_escape_closes_menu(self, ax): + mbi = spf_status_item(ax) + assert mbi is not None, ( + "expected a Spf status item (AXMenuBarItem) in the AX tree, found none") + + assert rb_enter_status_menu(ax), ( + "precondition: pressing the status item must open the menu; menu " + f"size={menu_size(ax)}") + assert menu_is_open(ax) is True, ( + f"expected the menu to be OPEN before pressing Escape, size={menu_size(ax)}") + open_selected = status_selected(ax, mbi.id) + assert open_selected is True, ( + "expected AXSelected True on the status item while its menu is open, got " + f"{open_selected!r}") + + dismiss_menu(ax) + wait_until(lambda: not menu_is_open(ax), timeout=2.0) + + assert menu_is_open(ax) is False, ( + "expected Escape to CLOSE the Spf menu (closed menus report ~0x0), but the " + f"AXMenu still reports size={menu_size(ax)}") + wait_until(lambda: status_selected(ax, mbi.id) is False, timeout=2.0) + closed_selected = status_selected(ax, mbi.id) + assert closed_selected is False, ( + "expected the status item's AXSelected to return to False after Escape " + f"closed the menu, got open={open_selected} closed={closed_selected}") + + # ── 3. depth 2: open the menu, then activate '5% opacity' from inside it ── + @pytest.mark.rb( + depth=2, jump_kind="reach", + expect="activating '5% opacity' from inside the OPEN status menu makes an " + "overlay AXWindow appear in the app's AX tree (it owned 0 windows before)") + def test_open_menu_then_5pct_reaches_overlay_window(self, ax): + assert not overlay_windows(ax), ( + "precondition: the app must own no overlay window at launch, found " + f"{len(overlay_windows(ax))}") + assert rb_enter_status_menu(ax), ( + f"precondition: could not open the Spf status menu, size={menu_size(ax)}") + + target = item_map(ax).get("5% opacity") or find_item(ax, "5%") + assert target is not None, ( + "expected a '5% opacity' row inside the open Spf menu, rows found: " + f"{item_names(ax)}") + + before = kit.rb_showing(ax) + reached = rb_reach_overlay(ax, target) + after = kit.rb_showing(ax) + + assert reached, ( + f"expected activating '{target.name}' from inside the open menu to create at " + "least one overlay window, app still exposes " + f"{len(overlay_windows(ax))} window(s)") + assert kit.rb_reach(before, after, target="window"), ( + "expected a NEW 'window|' node in the app's AX tree after activating " + f"'{target.name}' (the full-screen overlay); newly appeared nodes: " + f"{sorted(after - before)}") + assert clear_overlays(ax), ( + "teardown: 'Clear' must remove every overlay, still " + f"{len(overlay_windows(ax))} window(s) left") + + # ── 4. depth 2: same path with '50% opacity' ───────────────────────────── + @pytest.mark.rb( + depth=2, jump_kind="reach", + expect="activating '50% opacity' from inside the OPEN status menu makes an " + "overlay AXWindow appear in the app's AX tree (0 windows before)") + def test_open_menu_then_50pct_reaches_overlay_window(self, ax): + assert not overlay_windows(ax), ( + "precondition: the app must own no overlay window at launch, found " + f"{len(overlay_windows(ax))}") + assert rb_enter_status_menu(ax), ( + f"precondition: could not open the Spf status menu, size={menu_size(ax)}") + + target = item_map(ax).get("50% opacity") or find_item(ax, "50%") + assert target is not None, ( + "expected a '50% opacity' row inside the open Spf menu, rows found: " + f"{item_names(ax)}") + + before = kit.rb_showing(ax) + reached = rb_reach_overlay(ax, target) + after = kit.rb_showing(ax) + + assert reached, ( + f"expected activating '{target.name}' from inside the open menu to create at " + "least one overlay window, app still exposes " + f"{len(overlay_windows(ax))} window(s)") + assert kit.rb_reach(before, after, target="window"), ( + "expected a NEW 'window|' node in the app's AX tree after activating " + f"'{target.name}'; newly appeared nodes: {sorted(after - before)}") + + screenshot_assert( + "menus_50pct_overlay_from_menu", + "The Spf menu has closed and the ENTIRE desktop is now covered by a " + "translucent black overlay at roughly 50% opacity: the wallpaper and any " + "windows are still recognisable but clearly and uniformly darkened, edge to " + "edge. No menu, dialog or window of the app itself is visible.", + RESULTS_DIR) + assert clear_overlays(ax), ( + "teardown: 'Clear' must remove every overlay, still " + f"{len(overlay_windows(ax))} window(s) left") + + # ── 5. depth 2: 'Run test' overlay appears then self-expires ───────────── + @pytest.mark.rb( + depth=2, jump_kind="reach", + expect="'Run test' activated from inside the OPEN menu makes an overlay " + "AXWindow appear, and that overlay REMOVES ITSELF within ~7s with no " + "'Clear' press (the tag-0 animate-out path)") + def test_open_menu_then_run_test_overlay_self_expires(self, ax): + assert not overlay_windows(ax), ( + "precondition: the app must own no overlay window at launch, found " + f"{len(overlay_windows(ax))}") + assert rb_enter_status_menu(ax), ( + f"precondition: could not open the Spf status menu, size={menu_size(ax)}") + + target = item_map(ax).get("Run test") or find_item(ax, "run test", "test") + assert target is not None, ( + f"expected a 'Run test' row inside the open Spf menu, rows found: {item_names(ax)}") + + before = kit.rb_showing(ax) + assert press_item(ax, target, settle=1.0), ( + f"expected to be able to activate '{target.name}' from inside the open menu") + after = kit.rb_showing(ax) + + assert overlay_windows(ax), ( + f"expected '{target.name}' to create a full-screen test overlay window, app " + f"exposes {len(overlay_windows(ax))} window(s)") + assert kit.rb_reach(before, after, target="window"), ( + "expected a NEW 'window|' node in the app's AX tree right after activating " + f"'{target.name}'; newly appeared nodes: {sorted(after - before)}") + + screenshot_assert( + "menus_run_test_overlay", + "Just after choosing 'Run test' from the Spf menu: the menu has closed and " + "the whole desktop is washed with a translucent RED tint (the self-test " + "confirmation overlay) — the wallpaper is still visible through it but " + "everything has a clear red cast. No menu or dialog is open.", + RESULTS_DIR) + + gone = wait_until(lambda: not overlay_windows(ax), timeout=9.0, interval=0.5) + assert gone, ( + "expected the 'Run test' overlay to animate out and REMOVE ITSELF within 9s " + "without any 'Clear' press, but the app still exposes " + f"{len(overlay_windows(ax))} overlay window(s)") + clear_overlays(ax) + + # ── 6. activating an opacity row CLOSES the menu ───────────────────────── + @pytest.mark.rb( + depth=2, jump_kind="transition", + expect="menu_is_open flips True -> False when '25% opacity' is activated from " + "inside the open menu (the menu dismisses itself on selection)") + def test_activating_opacity_closes_menu(self, ax): + assert rb_enter_status_menu(ax), ( + f"precondition: could not open the Spf status menu, size={menu_size(ax)}") + assert menu_is_open(ax) is True, ( + f"expected the menu to be OPEN before selecting a row, size={menu_size(ax)}") + open_size = menu_size(ax) + + target = item_map(ax).get("25% opacity") or find_item(ax, "25%") + assert target is not None, ( + "expected a '25% opacity' row inside the open Spf menu, rows found: " + f"{item_names(ax)}") + assert press_item(ax, target, settle=1.2), ( + f"expected to be able to activate '{target.name}' from inside the open menu") + + wait_until(lambda: not menu_is_open(ax), timeout=2.0) + assert menu_is_open(ax) is False, ( + f"expected the Spf menu to CLOSE itself after '{target.name}' was selected, " + f"but the AXMenu still reports size={menu_size(ax)} " + f"(it was {open_size} while open)") + assert overlay_windows(ax), ( + "expected the selection to also take effect (an overlay window), app " + f"exposes {len(overlay_windows(ax))} window(s)") + assert clear_overlays(ax), ( + "teardown: 'Clear' must remove every overlay, still " + f"{len(overlay_windows(ax))} window(s) left") + + # ── 7. 'Clear' enablement seen from INSIDE the menu ────────────────────── + @pytest.mark.rb( + depth=2, jump_kind="transition", + expect="'Clear' read from inside the open menu is DISABLED at launch and " + "ENABLED after '25% opacity' created an overlay (autoenablesItems=NO, " + "so this is app logic, not AppKit)") + def test_clear_enablement_flips_inside_menu(self, ax): + assert rb_enter_status_menu(ax), ( + f"precondition: could not open the Spf status menu, size={menu_size(ax)}") + clear_before = item_enabled(ax, "Clear") + assert clear_before is not None, ( + f"expected a 'Clear' row inside the open Spf menu, rows found: {item_names(ax)}") + assert clear_before is False, ( + "expected 'Clear' to be DISABLED (greyed out) while no overlay exists, got " + f"enabled={clear_before}; overlay windows={len(overlay_windows(ax))}") + + target = item_map(ax).get("25% opacity") or find_item(ax, "25%") + assert target is not None, ( + "expected a '25% opacity' row inside the open Spf menu, rows found: " + f"{item_names(ax)}") + assert press_item(ax, target, settle=1.2), ( + f"expected to be able to activate '{target.name}' from inside the open menu") + assert overlay_windows(ax), ( + f"expected '{target.name}' to create an overlay window before 'Clear' can " + f"become enabled, app exposes {len(overlay_windows(ax))} window(s)") + + assert rb_enter_status_menu(ax), ( + "could not RE-OPEN the Spf status menu while an overlay is up, " + f"size={menu_size(ax)}") + wait_until(lambda: item_enabled(ax, "Clear") is True, timeout=2.0) + clear_after = item_enabled(ax, "Clear") + assert clear_after is True, ( + "expected 'Clear' to become ENABLED once an overlay exists, got enabled " + f"before={clear_before} after={clear_after} with " + f"{len(overlay_windows(ax))} overlay window(s)") + + screenshot_assert( + "menus_clear_enabled_over_overlay", + "The Spf status-bar menu is open again in the top-right menu bar, this time " + "on top of a desktop that is uniformly darkened by the active 25% black " + "overlay. In the menu the 'Clear' row is now drawn in normal black text " + "(enabled/selectable) instead of greyed out; it sits under the four " + "'N% opacity' rows and above the separator line and the " + "'Run test' / 'About' / 'Quit' rows.", + RESULTS_DIR) + assert clear_overlays(ax), ( + "teardown: 'Clear' must remove every overlay, still " + f"{len(overlay_windows(ax))} window(s) left") + dismiss_menu(ax) + + # ── 8. golden top-to-bottom row order (by AXPosition) ─────────────────── + @pytest.mark.rb( + depth=1, jump_kind="value", + expect="the OPEN menu's rows, sorted by their on-screen AXPosition y, spell " + "exactly ['5% opacity','10% opacity','25% opacity','50% opacity'," + "'Clear','','Run test','About','Quit']") + def test_open_menu_rows_in_golden_visual_order(self, ax): + assert rb_enter_status_menu(ax), ( + f"precondition: could not open the Spf status menu, size={menu_size(ax)}") + rows = item_rows(ax) + assert len(rows) == len(MENU_ORDER), ( + f"expected exactly {len(MENU_ORDER)} rows in the Spf menu ({MENU_ORDER}), " + f"found {len(rows)}: {[r[0] for r in rows]}") + + missing = [r[0] or "" for r in rows if r[1] is None] + assert not missing, ( + "expected every row of the OPEN menu to report an AXPosition (they are laid " + f"out on screen), but these have none: {missing}") + + ordered = [title for title, _pos, _sz, _el in + sorted(rows, key=lambda r: r[1][1])] + assert ordered == MENU_ORDER, ( + "expected the open menu's rows top-to-bottom (sorted by AXPosition y) to be " + f"{MENU_ORDER}, got {ordered}; raw tree order was {[r[0] for r in rows]} " + f"with y values {[r[1][1] for r in rows]}") + dismiss_menu(ax) + + # ── 9. every row is laid out inside the menu rectangle ────────────────── + @pytest.mark.rb( + depth=1, jump_kind="value", + expect="all 9 rows of the OPEN menu report a rect >= 60 pt wide that lies " + "inside the AXMenu's own rect, and every titled row is >= 10 pt tall") + def test_open_menu_row_geometry_inside_menu_rect(self, ax): + assert rb_enter_status_menu(ax), ( + f"precondition: could not open the Spf status menu, size={menu_size(ax)}") + mpos, msize = menu_rect(ax) + assert mpos is not None and msize is not None, ( + "expected the open AXMenu to report AXPosition and AXSize, got " + f"pos={mpos} size={msize}") + assert msize[0] >= MIN_OPEN_W and msize[1] >= MIN_OPEN_H, ( + f"expected the open Spf menu rect to be at least {MIN_OPEN_W}x{MIN_OPEN_H} " + f"pt (official: 105x197), got {msize}") + + rows = item_rows(ax) + assert len(rows) == len(MENU_ORDER), ( + f"expected {len(MENU_ORDER)} rows in the Spf menu, found {len(rows)}: " + f"{[r[0] for r in rows]}") + + mx, my = mpos + mw, mh = msize + narrow, outside, short = [], [], [] + for title, pos, size, _el in rows: + label = title or "" + if pos is None or size is None: + outside.append(f"{label}: no rect (pos={pos} size={size})") + continue + if size[0] < MIN_ROW_W: + narrow.append(f"{label}: width {size[0]}") + if not (mx - RECT_SLACK <= pos[0] <= mx + mw + RECT_SLACK + and my - RECT_SLACK <= pos[1] <= my + mh + RECT_SLACK): + outside.append(f"{label}: pos {pos} not inside menu " + f"({mx},{my})+({mw}x{mh})") + if title.strip() and size[1] < MIN_ROW_H: + short.append(f"{label}: height {size[1]}") + + assert not narrow, ( + f"expected every row of the open menu to be at least {MIN_ROW_W} pt wide " + f"(official: 105 pt, matching the menu width), too narrow: {narrow}") + assert not outside, ( + "expected every row to be laid out INSIDE the AXMenu rect " + f"({mx},{my})+({mw}x{mh}) within {RECT_SLACK} pt of slack, " + f"offenders: {outside}") + assert not short, ( + f"expected every TITLED row to be at least {MIN_ROW_H} pt tall " + f"(official: 22 pt), too short: {short}") + dismiss_menu(ax) + + # ── 10. 'About' presence / enablement / ordering (never pressed) ───────── + @pytest.mark.rb( + depth=1, jump_kind="none", + expect="'About' exists in the open menu, is enabled, offers AXPress, and sits " + "directly between 'Run test' and 'Quit'") + def test_about_item_present_enabled_and_ordered(self, ax): + # NOTE: never pressed — goToAbout: opens https://github.com/tannerc/spf in the + # default browser, which would pollute the shared desktop for every later test. + assert rb_enter_status_menu(ax), ( + f"precondition: could not open the Spf status menu, size={menu_size(ax)}") + names = item_names(ax) + about = item_map(ax).get("About") or find_item(ax, "About") + assert about is not None, ( + f"expected an 'About' row in the Spf menu, rows found: {names}") + assert bool(about.enabled) is True, ( + f"expected the 'About' row to be ENABLED, got enabled={about.enabled!r}") + assert "AXPress" in (about.actions or []), ( + "expected the 'About' row to expose an AXPress action interface, " + f"actions={list(about.actions or [])}") + + prev_row, next_row = neighbours_of(names, about.name) + assert prev_row == "Run test", ( + "expected 'About' to come directly AFTER 'Run test', but the row before it " + f"is {prev_row!r}; full menu order: {names}") + assert next_row == "Quit", ( + "expected 'About' to come directly BEFORE 'Quit', but the row after it is " + f"{next_row!r}; full menu order: {names}") + dismiss_menu(ax) + + # ── 11. 'Quit' presence / enablement / last-in-menu (never pressed) ───── + @pytest.mark.rb( + depth=1, jump_kind="none", + expect="'Quit' exists in the open menu, is enabled, offers AXPress, and is the " + "LAST row of the menu") + def test_quit_item_present_enabled_and_last(self, ax): + # NOTE: never pressed — it would terminate the app under test. + assert rb_enter_status_menu(ax), ( + f"precondition: could not open the Spf status menu, size={menu_size(ax)}") + names = item_names(ax) + quit_it = item_map(ax).get("Quit") or find_item(ax, "Quit") + assert quit_it is not None, ( + f"expected a 'Quit' row in the Spf menu, rows found: {names}") + assert bool(quit_it.enabled) is True, ( + f"expected the 'Quit' row to be ENABLED, got enabled={quit_it.enabled!r}") + assert "AXPress" in (quit_it.actions or []), ( + "expected the 'Quit' row to expose an AXPress action interface, " + f"actions={list(quit_it.actions or [])}") + assert names[-1] == quit_it.name, ( + "expected 'Quit' to be the LAST row of the Spf menu, but the last row is " + f"{names[-1]!r}; full menu order: {names}") + dismiss_menu(ax) + + # ── 12. the separator and the two groups it divides ───────────────────── + @pytest.mark.rb( + depth=1, jump_kind="none", + expect="exactly one untitled (separator) row exists, at index 5, disabled, " + "dividing the 4 opacity rows + 'Clear' from 'Run test'/'About'/'Quit'") + def test_separator_divides_the_two_menu_groups(self, ax): + assert rb_enter_status_menu(ax), ( + f"precondition: could not open the Spf status menu, size={menu_size(ax)}") + items = menu_items(ax) + names = [i.name or "" for i in items] + assert len(items) == len(MENU_ORDER), ( + f"expected {len(MENU_ORDER)} rows in the Spf menu (8 titled + 1 separator), " + f"found {len(items)}: {names}") + + blanks = [i for i, n in enumerate(names) if not n.strip()] + assert len(blanks) == 1, ( + "expected exactly ONE untitled row (the separator) in the Spf menu, found " + f"{len(blanks)} at indices {blanks}; full menu order: {names}") + sep_idx = blanks[0] + assert sep_idx == 5, ( + "expected the separator to be row index 5 (after 'Clear', before " + f"'Run test'), found it at index {sep_idx}; full menu order: {names}") + + sep = items[sep_idx] + assert not sep.enabled, ( + "expected the separator row to be DISABLED (not selectable), got " + f"enabled={sep.enabled!r}") + assert names[:sep_idx] == MENU_ORDER[:5], ( + f"expected the group ABOVE the separator to be {MENU_ORDER[:5]} (four " + f"opacity rows + 'Clear'), got {names[:sep_idx]}") + assert names[sep_idx + 1:] == MENU_ORDER[6:], ( + f"expected the group BELOW the separator to be {MENU_ORDER[6:]}, got " + f"{names[sep_idx + 1:]}") + dismiss_menu(ax) + + # ── 13. the status item stays functional: open -> dismiss -> open ──────── + @pytest.mark.rb( + depth=1, jump_kind="transition", + expect="the menu reports a laid-out rect (>= 60x120) on the FIRST open, ~0x0 " + "after Escape, and a laid-out rect again on the SECOND open") + def test_menu_can_be_reopened_after_dismissal(self, ax): + assert rb_enter_status_menu(ax), ( + "precondition: could not open the Spf status menu the first time, " + f"size={menu_size(ax)}") + first = menu_size(ax) + assert first is not None and first[0] >= MIN_OPEN_W and first[1] >= MIN_OPEN_H, ( + f"expected the FIRST open to lay the menu out at >= {MIN_OPEN_W}x" + f"{MIN_OPEN_H} pt, got {first}") + + dismiss_menu(ax) + wait_until(lambda: not menu_is_open(ax), timeout=2.0) + closed = menu_size(ax) + assert menu_is_open(ax) is False, ( + "expected Escape to close the menu between the two opens, but it still " + f"reports size={closed}") + + assert rb_enter_status_menu(ax), ( + "expected the status item to still work and RE-OPEN its menu after being " + f"dismissed once, size={menu_size(ax)} (first open was {first}, closed " + f"state {closed})") + second = menu_size(ax) + assert second is not None and second[0] >= MIN_OPEN_W and second[1] >= MIN_OPEN_H, ( + f"expected the SECOND open to lay the menu out at >= {MIN_OPEN_W}x" + f"{MIN_OPEN_H} pt as well, got {second} (first was {first})") + dismiss_menu(ax) + + # ── 14. opacity rows carry the golden percentages / no key equivalents ── + @pytest.mark.rb( + depth=1, jump_kind="value", + expect="the OPEN menu's opacity rows parse to exactly [5, 10, 25, 50] percent " + "in ascending order, all enabled and AXPress-able, and NO row has a " + "command-key equivalent (AXMenuItemCmdChar is None for all 9)") + def test_opacity_rows_percentages_and_no_key_equivalents(self, ax): + assert rb_enter_status_menu(ax), ( + f"precondition: could not open the Spf status menu, size={menu_size(ax)}") + items = menu_items(ax) + names = [i.name or "" for i in items] + + found = [p for p in (pct_of(n) for n in names) if p is not None] + assert found == [5, 10, 25, 50], ( + "expected the Spf menu to offer exactly the percentages [5, 10, 25, 50] in " + f"ascending order, got {found} from rows {names}") + + bad_state = [] + for it in items: + if pct_of(it.name or "") is None: + continue + if not it.enabled: + bad_state.append(f"{it.name}: disabled") + if "AXPress" not in (it.actions or []): + bad_state.append(f"{it.name}: actions={list(it.actions or [])}") + assert not bad_state, ( + "expected every 'N% opacity' row to be enabled and expose an AXPress action " + f"interface, offenders: {bad_state}") + + with_keys = [] + for it in items: + cmd = ax.get(it.id, ["AXMenuItemCmdChar"]).get("AXMenuItemCmdChar") + if cmd not in (None, "", 0): + with_keys.append(f"{it.name or ''}: {cmd!r}") + assert not with_keys, ( + "expected NO Spf menu row to declare a command-key equivalent " + f"(AXMenuItemCmdChar None for all {len(items)} rows), but found: {with_keys}") + dismiss_menu(ax) diff --git a/macos/tannerc-spf/tests/test_ax_states.py b/macos/tannerc-spf/tests/test_ax_states.py new file mode 100644 index 0000000000000000000000000000000000000000..c4c81db24bb77866c34b45b9134fc095ddfeeb7d --- /dev/null +++ b/macos/tannerc-spf/tests/test_ax_states.py @@ -0,0 +1,736 @@ +"""AX widget-state tests for Spf — Clear enablement, menu selection, window lifecycle.""" +import pytest +import rb_testgen_kit as kit + +# ══════════════════════════════════════════════════════════════════════════════ +# SPF_HELPER_BLOCK (embedded VERBATIM — never imported; every test module must be +# self-contained because the eval harness may copy only test_ax_*.py). +# ══════════════════════════════════════════════════════════════════════════════ + +import json +import os +import re +import subprocess +import tempfile +import time + +import Quartz + +# ── Golden model constants (from MainMenu.xib + live AX tree) ──────────────── +OPACITY_ITEMS = ["5% opacity", "10% opacity", "25% opacity", "50% opacity"] +OPACITY_PCT = {"5% opacity": 5, "10% opacity": 10, "25% opacity": 25, "50% opacity": 50} +# Exact menu order in the official app ("" is the separator between Clear and Run test) +MENU_ORDER = ["5% opacity", "10% opacity", "25% opacity", "50% opacity", + "Clear", "", "Run test", "About", "Quit"] +# Big middle-of-screen sample region: below the menu bar, above the Dock. +SAMPLE_REGION = (200, 150, 1500, 700) + + +def screenshot_assert(test_name, description, results_dir=None): + """Screenshot + a SPECIFIC visual description for the VLM judge.""" + results_dir = results_dir or os.environ.get("RESULTS_DIR") or "/tmp/spf_results" + 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=8) + except Exception: + pass + af = os.path.join(ss_dir, "assertions.json") + data = {} + if os.path.exists(af): + try: + with open(af) as f: + data = json.load(f) + except Exception: + data = {} + data[f"{test_name}.png"] = description + with open(af, "w") as f: + json.dump(data, f, indent=2) + + +# ── AX geometry ────────────────────────────────────────────────────────────── + +def _pair(v): + m = re.findall(r"[-\d.]+", str(v)) + return (float(m[-2]), float(m[-1])) if len(m) >= 2 else None + + +def ax_size(ax, eid): + return _pair(ax.get(eid, ["AXSize"]).get("AXSize")) + + +def ax_pos(ax, eid): + return _pair(ax.get(eid, ["AXPosition"]).get("AXPosition")) + + +# ── Status item + menu discovery ───────────────────────────────────────────── + +def status_items(ax): + """Every menu-bar status item the app owns (AXMenuBarItem, subrole AXMenuExtra). + The official app happens to create two; only one carries the Spf menu.""" + return ax.find(role="menu_bar_item", max_results=8, max_depth=3) + + +def spf_status_item(ax): + """The status item that owns the Spf menu; falls back to the widest one.""" + best, best_w = None, -1.0 + for m in status_items(ax): + if ax.find(role="menu", root_id=m.id, max_results=2): + return m + w = (ax_size(ax, m.id) or (0.0, 0.0))[0] + if w > best_w: + best, best_w = m, w + return best + + +def spf_menu(ax): + """The AXMenu holding the opacity / Clear / Run test / About / Quit items.""" + menus = ax.find(role="menu", max_results=6) + for menu in menus: + names = [i.name or "" for i in + ax.find(role="menu_item", root_id=menu.id, max_results=30)] + if any("opacity" in n.lower() or "%" in n for n in names): + return menu + return menus[0] if menus else None + + +def menu_items(ax): + """The Spf menu's items IN ORDER (list of AXElement).""" + menu = spf_menu(ax) + return ax.find(role="menu_item", root_id=menu.id, max_results=40) if menu else [] + + +def item_names(ax): + return [i.name or "" for i in menu_items(ax)] + + +def item_map(ax): + return {i.name: i for i in menu_items(ax) if i.name} + + +def find_item(ax, *keywords): + """Locate a menu item by any keyword (case-insensitive substring) — tolerant of + a recreation naming things slightly differently.""" + for it in menu_items(ax): + low = (it.name or "").lower() + for kw in keywords: + if kw.lower() in low: + return it + return None + + +def item_enabled(ax, name_or_kw): + it = item_map(ax).get(name_or_kw) or find_item(ax, name_or_kw) + return None if it is None else bool(it.enabled) + + +def press_item(ax, name_or_el, settle=1.0): + """Activate a Spf menu item via AXPress (works with the menu closed OR open). + NOTE: AXPress may report failure while still succeeding on status-item menus, + so the return value only means 'the item was found and pressed'.""" + el = name_or_el + if isinstance(name_or_el, str): + el = item_map(ax).get(name_or_el) or find_item(ax, name_or_el) + if el is None: + return False + ax.action(el.id, "AXPress") + time.sleep(settle) + return True + + +def menu_is_open(ax): + """True when the status menu is laid out on screen (closed menus report 0x0).""" + menu = spf_menu(ax) + if menu is None: + return False + sz = ax_size(ax, menu.id) + return bool(sz and sz[0] > 1 and sz[1] > 1) + + +def dismiss_menu(ax): + """Close the status menu if it is open.""" + import verifier_helpers as vh + vh.send_key(vh.KC_ESCAPE) + time.sleep(0.4) + return not menu_is_open(ax) + + +# ── Overlay windows ───────────────────────────────────────────────────────── + +def overlay_windows(ax): + """The screen-polarizing overlay windows the app currently exposes via AX.""" + return ax.find(role="window", max_results=10, max_depth=1) + + +def cg_overlays(pid): + """CoreGraphics facts about the app's large overlay windows: window level + (`layer`), alpha and bounds. Only windows >= 400x300 count (skips status items).""" + opts = Quartz.kCGWindowListOptionAll | Quartz.kCGWindowListExcludeDesktopElements + out = [] + for w in (Quartz.CGWindowListCopyWindowInfo(opts, Quartz.kCGNullWindowID) or []): + if w.get("kCGWindowOwnerPID") != pid: + continue + b = w.get("kCGWindowBounds") or {} + if float(b.get("Width", 0)) >= 400 and float(b.get("Height", 0)) >= 300: + out.append({"layer": int(w.get("kCGWindowLayer", 0)), + "alpha": float(w.get("kCGWindowAlpha", 0)), + "x": float(b.get("X", 0)), "y": float(b.get("Y", 0)), + "w": float(b.get("Width", 0)), "h": float(b.get("Height", 0))}) + return out + + +def main_display_size(): + b = Quartz.CGDisplayBounds(Quartz.CGMainDisplayID()) + return (float(b.size.width), float(b.size.height)) + + +def n_displays(): + err, _ids, cnt = Quartz.CGGetActiveDisplayList(16, None, None) + return int(cnt) if err == 0 else 1 + + +def pid_at_screen_point(x=None, y=None): + """Which process owns the UI element at a screen point. A click-THROUGH overlay + (ignoresMouseEvents) never answers here — the window underneath does.""" + from ApplicationServices import (AXUIElementCopyElementAtPosition, + AXUIElementCreateSystemWide, AXUIElementGetPid) + w, h = main_display_size() + x = w / 2.0 if x is None else x + y = h / 2.0 if y is None else y + err, el = AXUIElementCopyElementAtPosition( + AXUIElementCreateSystemWide(), float(x), float(y), None) + if err != 0 or el is None: + return None + err2, pid = AXUIElementGetPid(el, None) + return int(pid) if err2 == 0 else None + + +def clear_overlays(ax): + """Reset the app to its clean state (no overlay on screen). Call in teardown.""" + for _ in range(3): + if not overlay_windows(ax): + return True + it = find_item(ax, "Clear") + if it is None: + return False + ax.action(it.id, "AXPress") + time.sleep(0.7) + return not overlay_windows(ax) + + +# ── Screen sampling: what the desktop actually LOOKS like through the overlay ─ + +def _cgimage_region(x, y, w, h): + img = Quartz.CGWindowListCreateImage( + Quartz.CGRectMake(x, y, w, h), Quartz.kCGWindowListOptionOnScreenOnly, + Quartz.kCGNullWindowID, Quartz.kCGWindowImageDefault) + if img is not None and Quartz.CGImageGetWidth(img) > 0: + return img + fd, p = tempfile.mkstemp(suffix=".png") + os.close(fd) + try: + subprocess.run(["screencapture", "-x", "-R", f"{x},{y},{w},{h}", p], timeout=10) + from CoreFoundation import (CFURLCreateFromFileSystemRepresentation, + kCFAllocatorDefault) + raw = p.encode() + url = CFURLCreateFromFileSystemRepresentation( + kCFAllocatorDefault, raw, len(raw), False) + src = Quartz.CGImageSourceCreateWithURL(url, None) + return Quartz.CGImageSourceCreateImageAtIndex(src, 0, None) if src else None + finally: + try: + os.unlink(p) + except OSError: + pass + + +def screen_rgb(region=SAMPLE_REGION, step=4): + """Mean (R, G, B) of a screen region, byte-order aware. None if unsamplable.""" + img = _cgimage_region(*region) + if img is None: + return None + prov = Quartz.CGImageGetDataProvider(img) + if prov is None: + return None + buf = bytes(Quartz.CGDataProviderCopyData(prov)) + bpr = Quartz.CGImageGetBytesPerRow(img) + W, H = Quartz.CGImageGetWidth(img), Quartz.CGImageGetHeight(img) + bpp = max(1, Quartz.CGImageGetBitsPerPixel(img) // 8) + little = bool(Quartz.CGImageGetBitmapInfo(img) & Quartz.kCGBitmapByteOrder32Little) + ri, gi, bi = (2, 1, 0) if little else (0, 1, 2) + tot, n = [0, 0, 0], 0 + for row in range(0, H, step): + off = row * bpr + for col in range(0, W, step): + p = off + col * bpp + if p + 2 >= len(buf): + continue + tot[0] += buf[p + ri] + tot[1] += buf[p + gi] + tot[2] += buf[p + bi] + n += 1 + return tuple(round(v / n, 2) for v in tot) if n else None + + +def screen_luma(region=SAMPLE_REGION, step=4): + rgb = screen_rgb(region, step) + return None if rgb is None else round(sum(rgb) / 3.0, 2) + + +# ── depth-family navigation (NAMED so rb_audit_depth sees the surface crossing) ─ + +def rb_enter_status_menu(ax): + """Cross into the status-bar MENU surface: press the Spf status item so its menu + is laid out on screen. Returns True once the menu reports a real size.""" + mbi = spf_status_item(ax) + if mbi is None: + return False + ax.action(mbi.id, "AXPress") + time.sleep(1.0) + if menu_is_open(ax): + return True + ax.click_element_cg(mbi.id) + time.sleep(1.0) + return menu_is_open(ax) + + +def rb_reach_overlay(ax, item="25% opacity"): + """Cross into the OVERLAY WINDOW surface by activating an opacity menu item. + Returns True once the app exposes at least one overlay window.""" + if not press_item(ax, item, settle=1.2): + return False + return len(overlay_windows(ax)) >= 1 + + +# ══════════════════════════════════════════════════════════════════════════════ +# END SPF_HELPER_BLOCK — state-test-local readers below +# ══════════════════════════════════════════════════════════════════════════════ + +# Items the golden model reports ENABLED at launch (everything except Clear). +LAUNCH_ENABLED = OPACITY_ITEMS + ["Run test", "About", "Quit"] + + +def enabled_map(ax): + """{title: bool(AXEnabled)} for every TITLED item in the Spf menu.""" + return {i.name: bool(i.enabled) for i in menu_items(ax) if i.name} + + +def separator_items(ax): + """The untitled (separator) rows of the Spf menu.""" + return [i for i in menu_items(ax) if not (i.name or "").strip()] + + +def status_selected(ax): + """The status item's AXSelected — True only while its menu is open.""" + si = spf_status_item(ax) + if si is None: + return None + return ax.get(si.id, ["AXSelected"]).get("AXSelected") + + +def clear_key(mapping): + """The 'Clear' key actually present in an enabled-map (EN or keyword fallback).""" + if "Clear" in mapping: + return "Clear" + for k in mapping: + if "clear" in k.lower() or "清" in k: + return k + return None + + +class TestSpfStates: + """Widget-state verification for the menu-bar-only app Spf. + + The app has exactly one piece of mutable widget state — the `Clear` menu item's + enablement (nib has autoenablesItems="NO", so it is 100% app-authored) — plus the + status-item selection flag and the overlay-window lifecycle. + """ + + # ── 1. launch state of every item ──────────────────────────────────────── + @pytest.mark.rb(depth=0, jump_kind="none", + expect="At launch: 'Clear' is DISABLED; the four opacity items + " + "'Run test' + 'About' + 'Quit' are ENABLED; the separator row " + "is disabled") + def test_launch_enabled_states(self, ax): + items = menu_items(ax) + assert items, ("expected the Spf status menu to expose AXMenuItems in the AX tree " + "at launch, found none (no AXMenu with opacity items)") + emap = enabled_map(ax) + + ck = clear_key(emap) + assert ck is not None, ( + "expected a 'Clear' menu item to exist at launch; menu titles found: " + f"{sorted(emap)}") + assert emap[ck] is False, ( + f"expected menu item {ck!r} state DISABLED (AXEnabled False) at launch — no " + f"overlay exists yet — found AXEnabled={emap[ck]}") + + for name in LAUNCH_ENABLED: + it = item_map(ax).get(name) or find_item(ax, name) + assert it is not None, ( + f"expected menu item {name!r} to exist at launch; menu titles found: " + f"{sorted(emap)}") + assert bool(it.enabled) is True, ( + f"expected menu item {name!r} state ENABLED at launch, found " + f"AXEnabled={it.enabled}") + + seps = separator_items(ax) + assert len(seps) >= 1, ( + "expected at least 1 separator row (untitled AXMenuItem) between 'Clear' and " + f"'Run test'; item titles found: {item_names(ax)}") + for s in seps: + assert bool(s.enabled) is False, ( + "expected every separator row state DISABLED, found a separator with " + f"AXEnabled={s.enabled}") + + # ── 2. Clear becomes ENABLED once an overlay exists ────────────────────── + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="'Clear' AXEnabled False -> True the moment a '25% opacity' " + "overlay window exists") + def test_clear_enables_when_overlay_created(self, ax): + before = item_enabled(ax, "Clear") + assert before is not None, "expected a 'Clear' menu item to exist, found none" + assert before is False, ( + f"expected 'Clear' state DISABLED before any overlay, found AXEnabled={before}") + + reached = rb_reach_overlay(ax, "25% opacity") + assert reached, ( + "expected pressing '25% opacity' to create at least 1 overlay window, found " + f"{len(overlay_windows(ax))} AX windows") + + after = item_enabled(ax, "Clear") + assert after is True, ( + "expected 'Clear' state ENABLED while an overlay exists (setOverlay sets " + f"clearMenuItem.isEnabled = true), found AXEnabled={after} " + f"(before={before}) — a hardcoded-disabled Clear fails here") + + clear_overlays(ax) + + # ── 3. Clear disables again after being used ───────────────────────────── + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="After pressing 'Clear': 'Clear' AXEnabled True -> False and " + "the overlay window count drops to 0") + def test_clear_disables_after_being_pressed(self, ax): + assert rb_reach_overlay(ax, "50% opacity"), ( + "expected pressing '50% opacity' to create at least 1 overlay window, found " + f"{len(overlay_windows(ax))}") + armed = item_enabled(ax, "Clear") + assert armed is True, ( + f"expected 'Clear' state ENABLED with a 50% overlay up, found AXEnabled={armed}") + + assert press_item(ax, "Clear", settle=0.9), ( + f"expected to find and press 'Clear'; menu titles: {item_names(ax)}") + + after = item_enabled(ax, "Clear") + wins = overlay_windows(ax) + assert after is False, ( + "expected 'Clear' state DISABLED again after use (removeOverlay sets " + f"clearMenuItem.isEnabled = false), found AXEnabled={after} (was {armed})") + assert len(wins) == 0, ( + f"expected 0 overlay windows after 'Clear', found {len(wins)}") + + # ── 4. Clear stays enabled while switching opacity ─────────────────────── + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="Switching 5% -> 50% opacity keeps 'Clear' ENABLED and keeps " + "the overlay window count at n_displays() (overlay is updated, " + "not re-created)") + def test_clear_stays_enabled_across_opacity_switch(self, ax): + assert rb_reach_overlay(ax, "5% opacity"), ( + "expected pressing '5% opacity' to create at least 1 overlay window, found " + f"{len(overlay_windows(ax))}") + first = item_enabled(ax, "Clear") + n_first = len(overlay_windows(ax)) + assert first is True, ( + f"expected 'Clear' state ENABLED after '5% opacity', found AXEnabled={first}") + + assert press_item(ax, "50% opacity", settle=0.9), ( + f"expected to find and press '50% opacity'; menu titles: {item_names(ax)}") + + second = item_enabled(ax, "Clear") + n_second = len(overlay_windows(ax)) + assert second is True, ( + "expected 'Clear' to STAY ENABLED after switching to '50% opacity' (an overlay " + f"is still on screen), found AXEnabled={second} (was {first})") + assert n_second == n_displays(), ( + f"expected the overlay window count to stay at n_displays()={n_displays()} " + f"when re-selecting an opacity (existing overlay is updated), found " + f"{n_second} (was {n_first})") + + clear_overlays(ax) + + # ── 5. Clear auto-disables when Run test self-expires ──────────────────── + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="'Run test' overlay self-expires after ~4.5 s: 'Clear' " + "AXEnabled True -> False and window count 1+ -> 0 with no " + "user action") + def test_clear_auto_disables_when_run_test_expires(self, ax): + assert rb_reach_overlay(ax, "Run test"), ( + "expected pressing 'Run test' to create at least 1 overlay window, found " + f"{len(overlay_windows(ax))}") + during = item_enabled(ax, "Clear") + n_during = len(overlay_windows(ax)) + assert during is True, ( + f"expected 'Clear' state ENABLED while the 'Run test' overlay is up, found " + f"AXEnabled={during}") + assert n_during >= 1, ( + f"expected at least 1 'Run test' overlay window, found {n_during}") + + time.sleep(6.5) + + after = item_enabled(ax, "Clear") + n_after = len(overlay_windows(ax)) + assert n_after == 0, ( + "expected the 'Run test' overlay to REMOVE ITSELF after its ~4.5 s fade " + f"(completionHandler calls removeOverlay), found {n_after} windows still up " + f"(was {n_during})") + assert after is False, ( + "expected 'Clear' state DISABLED again once the 'Run test' overlay expired by " + f"itself, found AXEnabled={after} (was {during})") + + # ── 6. status item AXSelected flips while its menu is open ─────────────── + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="Status item AXSelected False -> True when its menu opens -> " + "False again after Escape") + def test_status_item_selected_flips_with_menu(self, ax): + si = spf_status_item(ax) + assert si is not None, ( + "expected the app to own a menu-bar status item (AXMenuBarItem), found none") + + before = status_selected(ax) + assert not before, ( + f"expected the status item state NOT SELECTED before opening its menu, found " + f"AXSelected={before}") + + assert rb_enter_status_menu(ax), ( + "expected pressing the status item to lay out its AXMenu on screen (size goes " + f"0x0 -> real), found menu size {ax_size(ax, spf_menu(ax).id) if spf_menu(ax) else None}") + + during = status_selected(ax) + assert during, ( + "expected the status item state SELECTED (AXSelected True) while its menu is " + f"open, found AXSelected={during} (before={before})") + + dismiss_menu(ax) + after = status_selected(ax) + assert not after, ( + "expected the status item state NOT SELECTED again after Escape closed the " + f"menu, found AXSelected={after} (was {during})") + + # ── 7. window-count lifecycle 0 -> n -> 0 ──────────────────────────────── + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="AX window count 0 at launch -> n_displays() after " + "'10% opacity' -> 0 after Clear; a 'window|' node appears in " + "the AX tree") + def test_window_count_lifecycle(self, ax): + showing_before = kit.rb_showing(ax) + n0 = len(overlay_windows(ax)) + assert n0 == 0, ( + f"expected 0 AX windows at launch (Spf owns no window until an overlay is " + f"created), found {n0}") + + assert rb_reach_overlay(ax, "10% opacity"), ( + "expected pressing '10% opacity' to create at least 1 overlay window, found " + f"{len(overlay_windows(ax))}") + n1 = len(overlay_windows(ax)) + assert n1 == n_displays(), ( + f"expected exactly one overlay window per screen — n_displays()=" + f"{n_displays()} — found {n1}") + + showing_after = kit.rb_showing(ax) + appeared = {k for k in (showing_after - showing_before) if k.startswith("window")} + assert appeared, ( + "expected a new 'window|' node to APPEAR in the AX tree when the overlay was " + f"created; new nodes were {sorted(showing_after - showing_before)[:8]}") + + assert clear_overlays(ax), "expected 'Clear' to remove every overlay window" + n2 = len(overlay_windows(ax)) + assert n2 == 0, ( + f"expected 0 AX windows again after 'Clear' (lifecycle 0 -> {n1} -> 0), " + f"found {n2}") + + # ── 8. overlay is a passive layer, not a normal window ─────────────────── + @pytest.mark.rb(depth=1, jump_kind="value", + expect="Overlay window AXSubrole == 'AXDialog' and AXModal / " + "AXMinimized / AXMain / AXFocused are ALL falsy — it never " + "steals focus or modality") + def test_overlay_window_is_passive_layer(self, ax): + assert rb_reach_overlay(ax, "25% opacity"), ( + "expected pressing '25% opacity' to create at least 1 overlay window, found " + f"{len(overlay_windows(ax))}") + wins = overlay_windows(ax) + assert wins, "expected at least 1 overlay window to inspect, found none" + + attrs = ax.get(wins[0].id, + ["AXSubrole", "AXModal", "AXMinimized", "AXMain", "AXFocused"]) + try: + sub = attrs.get("AXSubrole") + assert sub == "AXDialog", ( + f"expected the overlay window state AXSubrole == 'AXDialog' (borderless " + f"fullSizeContentView window), found {sub!r}") + for name in ("AXModal", "AXMinimized", "AXMain", "AXFocused"): + val = attrs.get(name) + assert not val, ( + f"expected the overlay window state {name} FALSE — the tint layer must " + f"never become modal/minimized/main/focused — found {name}={val!r}; " + f"full attribute read: {attrs}") + finally: + clear_overlays(ax) + + # ── 9. overlay floats above normal windows, alpha 1.0 ──────────────────── + @pytest.mark.rb(depth=1, jump_kind="value", + expect="Every CG overlay window reports layer >= 3 " + "(NSFloatingWindowLevel) and kCGWindowAlpha == 1.0 (the tint " + "lives in backgroundColor, not window alpha)") + def test_overlay_floats_with_full_alpha(self, ax): + assert rb_reach_overlay(ax, "25% opacity"), ( + "expected pressing '25% opacity' to create at least 1 overlay window, found " + f"{len(overlay_windows(ax))}") + try: + ovs = cg_overlays(ax.get_pid()) + assert ovs, ( + "expected CoreGraphics to report at least 1 large (>=400x300) window owned " + f"by the app's pid {ax.get_pid()}, found none") + for o in ovs: + assert o["layer"] >= 3, ( + "expected overlay window state FLOATING — CG layer >= 3 " + f"(NSFloatingWindowLevel, source sets level = .floating) — found " + f"layer={o['layer']} for window {o}") + assert abs(o["alpha"] - 1.0) <= 0.01, ( + "expected overlay window state kCGWindowAlpha == 1.0 (opacity is " + f"carried by the black backgroundColor, not the window alpha), found " + f"alpha={o['alpha']} for window {o}") + finally: + clear_overlays(ax) + + # ── 10. overlay is click-through ───────────────────────────────────────── + @pytest.mark.rb(depth=1, jump_kind="value", + expect="With a full-screen 50% overlay up, the element at screen " + "centre belongs to ANOTHER pid (ignoresMouseEvents = true), " + "never to Spf and never None") + def test_overlay_is_click_through(self, ax): + spf_pid = ax.get_pid() + assert rb_reach_overlay(ax, "50% opacity"), ( + "expected pressing '50% opacity' to create at least 1 overlay window, found " + f"{len(overlay_windows(ax))}") + try: + hit = pid_at_screen_point() + assert hit is not None, ( + "expected some process to own the UI element at screen centre through the " + "click-through overlay, found None (nothing answered the hit-test)") + assert hit != spf_pid, ( + "expected the overlay state CLICK-THROUGH (ignoresMouseEvents = true) so " + f"the hit-test at screen centre resolves to another process, found the " + f"app's own pid {hit} — the overlay is swallowing mouse events") + finally: + clear_overlays(ax) + + # ── 11. Clear enablement read from INSIDE the open menu, twice ─────────── + @pytest.mark.rb(depth=2, jump_kind="transition", + expect="Read from inside the OPEN status menu: 'Clear' DISABLED first " + "time, then ENABLED after a '25% opacity' overlay was created " + "from that same menu") + def test_clear_enablement_seen_from_open_menu(self, ax): + assert rb_enter_status_menu(ax), ( + "expected pressing the status item to open the Spf menu (menu AXSize goes " + "0x0 -> real), the menu never reported a real size") + + first = item_enabled(ax, "Clear") + assert first is False, ( + "expected 'Clear' state DISABLED as rendered inside the freshly opened menu, " + f"found AXEnabled={first}") + + assert rb_reach_overlay(ax, "25% opacity"), ( + "expected activating '25% opacity' from inside the open menu to create at " + f"least 1 overlay window, found {len(overlay_windows(ax))}") + + if menu_is_open(ax): + dismiss_menu(ax) + assert rb_enter_status_menu(ax), ( + "expected the status menu to re-open for the second enablement read, the menu " + "never reported a real size") + + second = item_enabled(ax, "Clear") + screenshot_assert( + "states_clear_enabled_with_overlay", + "The Spf menu is open, dropped down from its small monochrome icon in the " + "top-right menu bar, over a visibly darkened (25% black tinted) desktop. The " + "menu lists 5% opacity, 10% opacity, 25% opacity, 50% opacity, then Clear, a " + "separator line, Run test, About and Quit. The 'Clear' row is now drawn in " + "normal black/active text (selectable) rather than the greyed-out disabled " + "text it showed before any overlay existed; every opacity row is also active.", + os.environ.get("RESULTS_DIR")) + try: + assert second is True, ( + "expected 'Clear' state ENABLED as rendered inside the re-opened menu now " + f"that an overlay exists, found AXEnabled={second} (first read was {first})") + finally: + clear_overlays(ax) + dismiss_menu(ax) + + # ── 12. the app never exposes a standard window ────────────────────────── + @pytest.mark.rb(depth=1, jump_kind="none", + expect="No AX window at launch, get_main_window() is None, and STILL " + "no AX window while the status menu is open — the menu is not " + "backed by a window") + def test_app_never_exposes_a_standard_window(self, ax): + n0 = len(overlay_windows(ax)) + assert n0 == 0, ( + "expected 0 AX windows at launch for this LSUIElement menu-bar-only app, " + f"found {n0}") + main = ax.get_main_window() + assert main is None, ( + f"expected no main window state at launch (AXWindows empty), found window " + f"id {main!r}") + + assert rb_enter_status_menu(ax), ( + "expected pressing the status item to open the Spf menu, the menu never " + "reported a real size") + try: + n1 = len(overlay_windows(ax)) + assert n1 == 0, ( + "expected STILL 0 AX windows while the status menu is open — an NSMenu is " + f"not backed by an AX window — found {n1}") + main_open = ax.get_main_window() + assert main_open is None, ( + f"expected get_main_window() to stay None while the menu is open, found " + f"window id {main_open!r}") + finally: + dismiss_menu(ax) + + # ── 13. enabled states are re-readable and stable ──────────────────────── + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="With an overlay up, two enabled-maps read 0.5 s apart are " + "identical, and they differ from the launch map in EXACTLY one " + "key: 'Clear'") + def test_enabled_map_stable_and_only_clear_changes(self, ax): + launch = enabled_map(ax) + assert launch, ( + "expected a non-empty {title: AXEnabled} map at launch, found no titled menu " + "items") + + assert rb_reach_overlay(ax, "25% opacity"), ( + "expected pressing '25% opacity' to create at least 1 overlay window, found " + f"{len(overlay_windows(ax))}") + try: + first = enabled_map(ax) + time.sleep(0.5) + second = enabled_map(ax) + assert first == second, ( + "expected the enabled-state map to be STABLE across two reads 0.5 s apart, " + f"found first={first} second={second}") + + ck = clear_key(first) + assert ck is not None, ( + f"expected a 'Clear' item in the overlay-up map, keys were {sorted(first)}") + changed = {k for k in set(first) | set(launch) + if first.get(k) != launch.get(k)} + assert changed == {ck}, ( + f"expected exactly one item's enabled state to differ from launch — {ck!r} " + f"(False -> True) — found changed keys {sorted(changed)}; launch={launch} " + f"overlay={first}") + assert first[ck] is True and launch.get(ck) is False, ( + f"expected {ck!r} AXEnabled False at launch and True with an overlay up, " + f"found launch={launch.get(ck)} overlay={first[ck]}") + finally: + clear_overlays(ax) diff --git a/macos/tannerc-spf/tests/test_ax_structure.py b/macos/tannerc-spf/tests/test_ax_structure.py new file mode 100644 index 0000000000000000000000000000000000000000..7126bf824dd8e10ed515cb57610e37523347342c --- /dev/null +++ b/macos/tannerc-spf/tests/test_ax_structure.py @@ -0,0 +1,705 @@ +"""AX structure tests for Spf — validates the agent-app widget tree. + +Golden model: verifier/recon.md (every fact verified on the running official app). +The app is an LSUIElement agent app: NO Dock icon, NO main menu bar, NO window until an +overlay is created. Its whole UI is one status-bar menu with 9 items. + +Because there is no window to reveal (recon §2), this module deliberately does NOT call +ax_helpers.ensure_ui_visible() / the ax_with_reset fixture: they hunt for a popover/window +"panel" this app does not own, burn 4-8 s of the 30 s budget and can leave a menu open +(recon §6). Depth-1 tests reveal their own surface with the named nav helpers +rb_enter_status_menu() (menu surface) and rb_reach_overlay() (overlay-window surface). +""" + +import pytest +import rb_testgen_kit as kit + +# ───────────────────────────────────────────────────────────────────────────── +# SPF_HELPER_BLOCK — embedded VERBATIM (never imported: the eval harness may copy +# only test_ax_*.py, so this module must be SELF-CONTAINED). +# ───────────────────────────────────────────────────────────────────────────── + +import json +import os +import re +import subprocess +import tempfile +import time + +import Quartz + +# ── Golden model constants (from MainMenu.xib + live AX tree) ──────────────── +OPACITY_ITEMS = ["5% opacity", "10% opacity", "25% opacity", "50% opacity"] +OPACITY_PCT = {"5% opacity": 5, "10% opacity": 10, "25% opacity": 25, "50% opacity": 50} +# Exact menu order in the official app ("" is the separator between Clear and Run test) +MENU_ORDER = ["5% opacity", "10% opacity", "25% opacity", "50% opacity", + "Clear", "", "Run test", "About", "Quit"] +# Big middle-of-screen sample region: below the menu bar, above the Dock. +SAMPLE_REGION = (200, 150, 1500, 700) + + +def screenshot_assert(test_name, description, results_dir=None): + """Screenshot + a SPECIFIC visual description for the VLM judge.""" + results_dir = results_dir or os.environ.get("RESULTS_DIR") or "/tmp/spf_results" + 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=8) + except Exception: + pass + af = os.path.join(ss_dir, "assertions.json") + data = {} + if os.path.exists(af): + try: + with open(af) as f: + data = json.load(f) + except Exception: + data = {} + data[f"{test_name}.png"] = description + with open(af, "w") as f: + json.dump(data, f, indent=2) + + +# ── AX geometry ────────────────────────────────────────────────────────────── + +def _pair(v): + m = re.findall(r"[-\d.]+", str(v)) + return (float(m[-2]), float(m[-1])) if len(m) >= 2 else None + + +def ax_size(ax, eid): + return _pair(ax.get(eid, ["AXSize"]).get("AXSize")) + + +def ax_pos(ax, eid): + return _pair(ax.get(eid, ["AXPosition"]).get("AXPosition")) + + +# ── Status item + menu discovery ───────────────────────────────────────────── + +def status_items(ax): + """Every menu-bar status item the app owns (AXMenuBarItem, subrole AXMenuExtra). + The official app happens to create two; only one carries the Spf menu.""" + return ax.find(role="menu_bar_item", max_results=8, max_depth=3) + + +def spf_status_item(ax): + """The status item that owns the Spf menu; falls back to the widest one.""" + best, best_w = None, -1.0 + for m in status_items(ax): + if ax.find(role="menu", root_id=m.id, max_results=2): + return m + w = (ax_size(ax, m.id) or (0.0, 0.0))[0] + if w > best_w: + best, best_w = m, w + return best + + +def spf_menu(ax): + """The AXMenu holding the opacity / Clear / Run test / About / Quit items.""" + menus = ax.find(role="menu", max_results=6) + for menu in menus: + names = [i.name or "" for i in + ax.find(role="menu_item", root_id=menu.id, max_results=30)] + if any("opacity" in n.lower() or "%" in n for n in names): + return menu + return menus[0] if menus else None + + +def menu_items(ax): + """The Spf menu's items IN ORDER (list of AXElement).""" + menu = spf_menu(ax) + return ax.find(role="menu_item", root_id=menu.id, max_results=40) if menu else [] + + +def item_names(ax): + return [i.name or "" for i in menu_items(ax)] + + +def item_map(ax): + return {i.name: i for i in menu_items(ax) if i.name} + + +def find_item(ax, *keywords): + """Locate a menu item by any keyword (case-insensitive substring) — tolerant of + a recreation naming things slightly differently.""" + for it in menu_items(ax): + low = (it.name or "").lower() + for kw in keywords: + if kw.lower() in low: + return it + return None + + +def item_enabled(ax, name_or_kw): + it = item_map(ax).get(name_or_kw) or find_item(ax, name_or_kw) + return None if it is None else bool(it.enabled) + + +def press_item(ax, name_or_el, settle=1.0): + """Activate a Spf menu item via AXPress (works with the menu closed OR open). + NOTE: AXPress may report failure while still succeeding on status-item menus, + so the return value only means 'the item was found and pressed'.""" + el = name_or_el + if isinstance(name_or_el, str): + el = item_map(ax).get(name_or_el) or find_item(ax, name_or_el) + if el is None: + return False + ax.action(el.id, "AXPress") + time.sleep(settle) + return True + + +def menu_is_open(ax): + """True when the status menu is laid out on screen (closed menus report 0x0).""" + menu = spf_menu(ax) + if menu is None: + return False + sz = ax_size(ax, menu.id) + return bool(sz and sz[0] > 1 and sz[1] > 1) + + +def dismiss_menu(ax): + """Close the status menu if it is open.""" + import verifier_helpers as vh + vh.send_key(vh.KC_ESCAPE) + time.sleep(0.4) + return not menu_is_open(ax) + + +# ── Overlay windows ───────────────────────────────────────────────────────── + +def overlay_windows(ax): + """The screen-polarizing overlay windows the app currently exposes via AX.""" + return ax.find(role="window", max_results=10, max_depth=1) + + +def cg_overlays(pid): + """CoreGraphics facts about the app's large overlay windows: window level + (`layer`), alpha and bounds. Only windows >= 400x300 count (skips status items).""" + opts = Quartz.kCGWindowListOptionAll | Quartz.kCGWindowListExcludeDesktopElements + out = [] + for w in (Quartz.CGWindowListCopyWindowInfo(opts, Quartz.kCGNullWindowID) or []): + if w.get("kCGWindowOwnerPID") != pid: + continue + b = w.get("kCGWindowBounds") or {} + if float(b.get("Width", 0)) >= 400 and float(b.get("Height", 0)) >= 300: + out.append({"layer": int(w.get("kCGWindowLayer", 0)), + "alpha": float(w.get("kCGWindowAlpha", 0)), + "x": float(b.get("X", 0)), "y": float(b.get("Y", 0)), + "w": float(b.get("Width", 0)), "h": float(b.get("Height", 0))}) + return out + + +def main_display_size(): + b = Quartz.CGDisplayBounds(Quartz.CGMainDisplayID()) + return (float(b.size.width), float(b.size.height)) + + +def n_displays(): + err, _ids, cnt = Quartz.CGGetActiveDisplayList(16, None, None) + return int(cnt) if err == 0 else 1 + + +def pid_at_screen_point(x=None, y=None): + """Which process owns the UI element at a screen point. A click-THROUGH overlay + (ignoresMouseEvents) never answers here — the window underneath does.""" + from ApplicationServices import (AXUIElementCopyElementAtPosition, + AXUIElementCreateSystemWide, AXUIElementGetPid) + w, h = main_display_size() + x = w / 2.0 if x is None else x + y = h / 2.0 if y is None else y + err, el = AXUIElementCopyElementAtPosition( + AXUIElementCreateSystemWide(), float(x), float(y), None) + if err != 0 or el is None: + return None + err2, pid = AXUIElementGetPid(el, None) + return int(pid) if err2 == 0 else None + + +def clear_overlays(ax): + """Reset the app to its clean state (no overlay on screen). Call in teardown.""" + for _ in range(3): + if not overlay_windows(ax): + return True + it = find_item(ax, "Clear") + if it is None: + return False + ax.action(it.id, "AXPress") + time.sleep(0.7) + return not overlay_windows(ax) + + +# ── Screen sampling: what the desktop actually LOOKS like through the overlay ─ + +def _cgimage_region(x, y, w, h): + img = Quartz.CGWindowListCreateImage( + Quartz.CGRectMake(x, y, w, h), Quartz.kCGWindowListOptionOnScreenOnly, + Quartz.kCGNullWindowID, Quartz.kCGWindowImageDefault) + if img is not None and Quartz.CGImageGetWidth(img) > 0: + return img + fd, p = tempfile.mkstemp(suffix=".png") + os.close(fd) + try: + subprocess.run(["screencapture", "-x", "-R", f"{x},{y},{w},{h}", p], timeout=10) + from CoreFoundation import (CFURLCreateFromFileSystemRepresentation, + kCFAllocatorDefault) + raw = p.encode() + url = CFURLCreateFromFileSystemRepresentation( + kCFAllocatorDefault, raw, len(raw), False) + src = Quartz.CGImageSourceCreateWithURL(url, None) + return Quartz.CGImageSourceCreateImageAtIndex(src, 0, None) if src else None + finally: + try: + os.unlink(p) + except OSError: + pass + + +def screen_rgb(region=SAMPLE_REGION, step=4): + """Mean (R, G, B) of a screen region, byte-order aware. None if unsamplable.""" + img = _cgimage_region(*region) + if img is None: + return None + prov = Quartz.CGImageGetDataProvider(img) + if prov is None: + return None + buf = bytes(Quartz.CGDataProviderCopyData(prov)) + bpr = Quartz.CGImageGetBytesPerRow(img) + W, H = Quartz.CGImageGetWidth(img), Quartz.CGImageGetHeight(img) + bpp = max(1, Quartz.CGImageGetBitsPerPixel(img) // 8) + little = bool(Quartz.CGImageGetBitmapInfo(img) & Quartz.kCGBitmapByteOrder32Little) + ri, gi, bi = (2, 1, 0) if little else (0, 1, 2) + tot, n = [0, 0, 0], 0 + for row in range(0, H, step): + off = row * bpr + for col in range(0, W, step): + p = off + col * bpp + if p + 2 >= len(buf): + continue + tot[0] += buf[p + ri] + tot[1] += buf[p + gi] + tot[2] += buf[p + bi] + n += 1 + return tuple(round(v / n, 2) for v in tot) if n else None + + +def screen_luma(region=SAMPLE_REGION, step=4): + rgb = screen_rgb(region, step) + return None if rgb is None else round(sum(rgb) / 3.0, 2) + + +# ── depth-family navigation (NAMED so rb_audit_depth sees the surface crossing) ─ + +def rb_enter_status_menu(ax): + """Cross into the status-bar MENU surface: press the Spf status item so its menu + is laid out on screen. Returns True once the menu reports a real size.""" + mbi = spf_status_item(ax) + if mbi is None: + return False + ax.action(mbi.id, "AXPress") + time.sleep(1.0) + if menu_is_open(ax): + return True + ax.click_element_cg(mbi.id) + time.sleep(1.0) + return menu_is_open(ax) + + +def rb_reach_overlay(ax, item="25% opacity"): + """Cross into the OVERLAY WINDOW surface by activating an opacity menu item. + Returns True once the app exposes at least one overlay window.""" + if not press_item(ax, item, settle=1.2): + return False + return len(overlay_windows(ax)) >= 1 + + +# ───────────────────────────────────────────────────────────────────────────── +# END SPF_HELPER_BLOCK — module-local structure helpers below +# ───────────────────────────────────────────────────────────────────────────── + +# The AX root element's role (AXApplication -> "application" after ROLE_MAP fallback). +APP_ROLE = "application" +SS_DIR = os.environ.get("RESULTS_DIR") + + +def app_element(ax): + """The AXApplication root element itself (depth 0 of the app's AX tree).""" + hits = ax.find(role=APP_ROLE, max_results=1, max_depth=0) + return hits[0] if hits else None + + +def opacity_item(ax, title, items=None): + """Locate an opacity item by SEMANTICS (visible label), never by child index: + exact title first, then 'starts with %' after stripping spaces — so + '25 % Opacity' / '25% 不透明度' still match and '5%' never matches '25%'.""" + items = menu_items(ax) if items is None else items + for it in items: + if (it.name or "") == title: + return it + pct = OPACITY_PCT.get(title) + if pct is None: + return None + for it in items: + if (it.name or "").replace(" ", "").lower().startswith(f"{pct}%"): + return it + return None + + +def _rect(ax, eid): + """(x, y, w, h) or None for an AX element.""" + p, s = ax_pos(ax, eid), ax_size(ax, eid) + return None if (p is None or s is None) else (p[0], p[1], s[0], s[1]) + + +def _inside(inner, outer, tol=8.0): + """True when rect `inner` sits inside rect `outer` (tolerance in points).""" + ix, iy, iw, ih = inner + ox, oy, ow, oh = outer + return (ix >= ox - tol and iy >= oy - tol + and ix + iw <= ox + ow + tol and iy + ih <= oy + oh + tol) + + +def _largest_window(ax, wins): + """The biggest AX window by area (the full-screen overlay), with its rect.""" + best, best_rect, best_area = None, None, -1.0 + for w in wins: + r = _rect(ax, w.id) + area = 0.0 if r is None else r[2] * r[3] + if area > best_area: + best, best_rect, best_area = w, r, area + return best, best_rect + + +class TestSpfStructure: + """Presence/shape of the agent app's AX tree + the two surfaces it can reach.""" + + # ── 1-8: structure / existence (flat tree, already present at launch) ──── + + @pytest.mark.rb(depth=0, jump_kind="none", expect="") + def test_agent_app_shape_extras_menubar_and_no_window(self, ax): + """Agent app (LSUIElement): AXExtrasMenuBar readable, no window at launch.""" + app_el = app_element(ax) + assert app_el is not None, ( + "Expected the AXApplication root element (role 'application') to be " + f"readable via AX; ax.find(role={APP_ROLE!r}) returned nothing") + attr_names = ax.attribute_names() + vals = ax.get(app_el.id, ["AXExtrasMenuBar", "AXMenuBar", "AXRole"]) + extras = vals.get("AXExtrasMenuBar") + bars = ax.find(role="menu_bar", max_results=4, max_depth=2) + assert extras is not None or bars, ( + "Expected the app to own a status-bar surface: AXExtrasMenuBar should read " + "as a non-None AXUIElement (or at least one role='menu_bar' element should " + f"exist). Got AXExtrasMenuBar={extras!r}, menu_bar elements={len(bars)}, " + f"app AXMenuBar={vals.get('AXMenuBar')!r} (unreadable on an agent app), " + f"app attribute names={sorted(attr_names)}") + wins = overlay_windows(ax) + assert len(wins) == 0, ( + "Expected 0 AX windows at launch (an agent app owns no window until an " + f"overlay is created); found {len(wins)}: " + f"{[(w.role, w.name, _rect(ax, w.id)) for w in wins]}") + + @pytest.mark.rb(depth=0, jump_kind="none", expect="") + def test_status_item_exists_and_is_pressable(self, ax): + """>= 1 AXMenuBarItem status item, subrole AXMenuExtra, offering AXPress.""" + items = status_items(ax) + assert len(items) >= 1, ( + "Expected at least 1 menu-bar status item (role 'menu_bar_item'); found " + f"{len(items)}. The whole UI of this app hangs off its status item.") + bad_subrole, no_press = [], [] + for it in items: + sub = ax.get(it.id, ["AXSubrole"]).get("AXSubrole") + sub_s = "" if sub is None else str(sub) + if sub_s.strip() and "menuextra" not in sub_s.lower(): + bad_subrole.append((it.name, sub_s)) + if "AXPress" not in (it.actions or []): + no_press.append((it.name, list(it.actions or []))) + assert not bad_subrole, ( + "Expected every status item's AXSubrole to be 'AXMenuExtra' (or absent); " + f"offenders (name, subrole): {bad_subrole}") + assert not no_press, ( + "Expected every status item to offer the 'AXPress' action; offenders " + f"(name, actions): {no_press}") + owner = spf_status_item(ax) + assert owner is not None, ( + "Expected to identify the status item that carries the app menu " + f"(spf_status_item); got None from {len(items)} status item(s)") + screenshot_assert( + "structure_status_item", + "The app has NO Dock icon and NO window on screen. In the right-hand side " + "of the macOS menu bar at the very top of the display there is a small " + "monochrome (template) status-bar icon for this app, sitting among the " + "other system menu-bar extras. No application menu bar (File/Edit/View) " + "belongs to this app.", + SS_DIR) + + @pytest.mark.rb(depth=0, jump_kind="none", expect="") + def test_status_item_menubar_geometry(self, ax): + """The menu-owning status item is laid out in the top menu-bar strip.""" + owner = spf_status_item(ax) + assert owner is not None, ( + "Expected a status item owning the app menu; spf_status_item returned None") + rect = _rect(ax, owner.id) + assert rect is not None, ( + "Expected the status item to report AXPosition + AXSize (a laid-out " + f"menu-bar item); got position={ax_pos(ax, owner.id)!r}, " + f"size={ax_size(ax, owner.id)!r}") + x, y, w, h = rect + assert w >= 8, ( + f"Expected the status item to be at least 8 pt wide (official: 38 pt for " + f"the menu-owning item); got width={w} from rect={rect}") + assert 15 <= h <= 40, ( + "Expected a menu-bar-height status item (15..40 pt, official: ~22 pt); got " + f"height={h} from rect={rect}") + assert y <= 5, ( + "Expected the status item to sit in the top menu-bar strip (AXPosition.y " + f"<= 5, official: y=0); got y={y} from rect={rect}") + + @pytest.mark.rb(depth=0, jump_kind="none", expect="") + def test_menu_has_nine_items(self, ax): + """The status menu holds exactly 9 items (8 titled + 1 separator).""" + menu = spf_menu(ax) + assert menu is not None, ( + "Expected an AXMenu carrying the opacity items; found menus=" + f"{[m.name for m in ax.find(role='menu', max_results=6)]}") + items = menu_items(ax) + assert len(items) == 9, ( + "Expected exactly 9 menu items (5%/10%/25%/50% opacity, Clear, separator, " + f"Run test, About, Quit); found {len(items)}: " + f"{[i.name for i in items]}") + + @pytest.mark.rb(depth=0, jump_kind="none", expect="") + def test_menu_item_titles_in_exact_order(self, ax): + """Item titles equal the golden MENU_ORDER, in order.""" + names = item_names(ax) + assert names == MENU_ORDER, ( + f"Expected menu titles in this exact order {MENU_ORDER} " + f"('' is the separator between Clear and Run test); found {names}") + + @pytest.mark.rb(depth=0, jump_kind="none", expect="") + def test_separator_at_index_five_and_titled_items(self, ax): + """Index 5 is a disabled, untitled separator; the other 8 items are titled.""" + items = menu_items(ax) + assert len(items) >= 9, ( + "Expected >= 9 menu items so index 5 can be the separator; found " + f"{len(items)}: {[i.name for i in items]}") + sep = items[5] + sep_name = sep.name or "" + assert sep_name == "", ( + "Expected the item at index 5 to be the separator with an EMPTY title; " + f"found {sep_name!r}. Full order: {[i.name for i in items]}") + assert bool(sep.enabled) is False, ( + "Expected the separator at index 5 to be disabled (AXEnabled False); " + f"found enabled={sep.enabled!r}") + titled = [i for idx, i in enumerate(items[:9]) if idx != 5] + untitled = [idx for idx, i in enumerate(items[:9]) + if idx != 5 and not (i.name or "").strip()] + assert not untitled, ( + "Expected the 8 non-separator items to all have non-empty titles; empty at " + f"index/indices {untitled}. Full order: {[i.name for i in items]}") + assert len(titled) == 8, ( + f"Expected 8 titled items besides the separator; found {len(titled)}: " + f"{[i.name for i in titled]}") + + @pytest.mark.rb(depth=0, jump_kind="none", expect="") + def test_every_titled_item_offers_press_and_pick(self, ax): + """Every titled item is actionable through BOTH AXPress and AXPick.""" + items = [i for i in menu_items(ax) if (i.name or "").strip()] + assert len(items) >= 8, ( + "Expected >= 8 titled menu items to check actions on; found " + f"{len(items)}: {[i.name for i in items]}") + missing = [(i.name, list(i.actions or [])) for i in items + if not {"AXPress", "AXPick"}.issubset(set(i.actions or []))] + assert not missing, ( + "Expected every titled menu item to expose BOTH 'AXPress' and 'AXPick' " + f"actions; offenders (title, actions): {missing}") + + @pytest.mark.rb(depth=0, jump_kind="none", expect="") + def test_four_opacity_items_with_percentages(self, ax): + """All four opacity items exist and their labels carry 5%/10%/25%/50%.""" + items = menu_items(ax) + found, bad = {}, [] + for title in OPACITY_ITEMS: + it = opacity_item(ax, title, items) + if it is None: + bad.append((title, None)) + continue + label = (it.name or "") + found[title] = label + if f"{OPACITY_PCT[title]}%" not in label.replace(" ", ""): + bad.append((title, label)) + assert not bad, ( + "Expected 4 opacity items whose labels contain their exact percentage " + f"followed by '%' ({[f'{p}%' for p in OPACITY_PCT.values()]}); " + f"missing/mismatched (expected, actual): {bad}. " + f"Menu titles seen: {[i.name for i in items]}") + assert len(found) == 4, ( + f"Expected all 4 of {OPACITY_ITEMS}; matched {found}") + + # ── 9-12: interactive — the surfaces a hollow recreation cannot reach ──── + + @pytest.mark.rb( + depth=1, jump_kind="transition", + expect="pressing the status item lays the AXMenu out: AXSize grows from 0x0 " + "(closed) to >=60x120 (official 105x197) and >= 8 menu items each gain " + "a real row rect (official 105x22) inside the menu bounds; Escape " + "collapses it back to 0x0") + def test_menu_open_lays_out_rows(self, ax): + """depth 1: open the status menu; its AXMenu + rows gain real geometry.""" + menu = spf_menu(ax) + assert menu is not None, ( + "Expected an AXMenu on the status item before opening it; found menus=" + f"{[m.name for m in ax.find(role='menu', max_results=6)]}") + before = ax_size(ax, menu.id) or (0.0, 0.0) + + opened = rb_enter_status_menu(ax) + + menu = spf_menu(ax) or menu + after = ax_size(ax, menu.id) or (0.0, 0.0) + mrect = _rect(ax, menu.id) + rows = [] + for it in menu_items(ax): + r = _rect(ax, it.id) + if r is None: + continue + if r[2] >= 60 and r[3] >= 10 and (mrect is None or _inside(r, mrect)): + rows.append((it.name, r)) + + screenshot_assert( + "structure_menu_open_layout", + "The app's status menu is OPEN, dropped down from its small monochrome " + "icon in the top-right menu bar. The menu is a narrow vertical popup " + "(about 105x197 points) listing exactly these rows top to bottom: " + "'5% opacity', '10% opacity', '25% opacity', '50% opacity', 'Clear' " + "(greyed out / disabled), then a thin horizontal separator line, then " + "'Run test', 'About', 'Quit'. No keyboard shortcuts are shown on the " + "right of any row. The desktop behind the menu is NOT tinted or darkened, " + "and there is no application window.", + SS_DIR) + dismiss_menu(ax) + + assert opened, ( + "Expected pressing the status item to lay out its menu (menu AXSize > 1x1); " + f"menu size stayed {after} (was {before} before the press)") + assert before[0] <= 2 and before[1] <= 2, ( + "Expected the CLOSED menu to report a ~0x0 AXSize before the press; got " + f"{before}") + assert after[0] >= 60 and after[1] >= 120, ( + "Expected the OPEN menu to report AXSize width >= 60 and height >= 120 " + f"(official 105x197); got {after} (before the press: {before})") + assert len(rows) >= 8, ( + "Expected >= 8 menu items to lay out a real row (width >= 60, height >= 10) " + f"inside the open menu rect {mrect}; only {len(rows)} did: {rows}") + + @pytest.mark.rb( + depth=1, jump_kind="value", + expect="activating '25% opacity' creates a borderless overlay AX window at " + "AXPosition (0,0) +-2 with AXSize exactly the main display size " + "(official 1920x1080 == CGDisplayBounds(main)) +-2") + def test_overlay_covers_whole_main_display(self, ax): + """depth 1: the overlay window's rect equals the whole main display.""" + target = opacity_item(ax, "25% opacity") or "25% opacity" + reached = rb_reach_overlay(ax, target) + if not reached: + time.sleep(0.8) + wins = overlay_windows(ax) + win, rect = _largest_window(ax, wins) + disp_w, disp_h = main_display_size() + screenshot_assert( + "structure_overlay_full_screen", + "A translucent black overlay now covers the ENTIRE main display, edge to " + "edge, including behind the menu bar area: the whole desktop looks " + "uniformly dimmed/darkened (about 25% black) while the wallpaper and any " + "other app windows are still clearly visible through it. The overlay has " + "no title bar, no borders, no buttons and no visible controls.", + SS_DIR) + clear_overlays(ax) + + assert len(wins) >= 1, ( + "Expected >= 1 overlay AX window after activating '25% opacity'; the app " + f"exposed {len(wins)} window(s) (reach helper returned {reached})") + assert rect is not None, ( + "Expected the overlay window to report AXPosition + AXSize; got " + f"position={ax_pos(ax, win.id)!r}, size={ax_size(ax, win.id)!r}") + x, y, w, h = rect + assert abs(x) <= 2 and abs(y) <= 2, ( + f"Expected the overlay window at AXPosition (0, 0) +-2; got ({x}, {y}) " + f"[full rect {rect}]") + assert abs(w - disp_w) <= 2 and abs(h - disp_h) <= 2, ( + f"Expected the overlay AXSize to equal the main display size " + f"({disp_w} x {disp_h}) +-2 — it must cover the whole screen; got " + f"({w} x {h}) [full rect {rect}]") + + @pytest.mark.rb( + depth=1, jump_kind="value", + expect="one overlay window per screen: len(overlay AX windows) == " + "n_displays() (1 here, since the source loops 'for screen in " + "NSScreen.screens'), and each is a full-screen-sized window") + def test_one_overlay_window_per_display(self, ax): + """depth 1: overlay count equals the number of active displays.""" + target = opacity_item(ax, "10% opacity") or "10% opacity" + reached = rb_reach_overlay(ax, target) + if not reached: + time.sleep(0.8) + wins = overlay_windows(ax) + expected = n_displays() + rects = [(w.name, _rect(ax, w.id)) for w in wins] + big = [r for _n, r in rects + if r is not None and r[2] >= 400 and r[3] >= 300] + screenshot_assert( + "structure_overlay_per_display", + "Every attached display is dimmed by its own full-screen translucent " + "black overlay (a light ~10% tint here): the desktop is slightly darker " + "than normal but the wallpaper is fully readable through it. No extra " + "window frame, panel or dialog appeared — just the tint.", + SS_DIR) + clear_overlays(ax) + + assert len(wins) == expected, ( + f"Expected exactly one overlay window per screen: {expected} overlay AX " + f"window(s) for {expected} active display(s); found {len(wins)}: {rects} " + f"(reach helper returned {reached})") + assert len(big) == expected, ( + f"Expected all {expected} overlay window(s) to be full-screen sized " + f"(>= 400x300); only {len(big)} were: {rects}") + + @pytest.mark.rb( + depth=1, jump_kind="reach", + expect="activating '50% opacity' adds a NEW 'window' node to the app's AX " + "tree (rb_showing gains a window|... key that was absent before), " + "proving the overlay is a genuinely new surface, not a pre-existing node") + def test_overlay_is_a_new_ax_surface(self, ax): + """depth 1: prove the overlay window is a NEW surface via rb_showing/rb_reach.""" + before = kit.rb_showing(ax) + win_before = [k for k in before if k.lower().startswith("window|")] + + target = opacity_item(ax, "50% opacity") or "50% opacity" + reached = rb_reach_overlay(ax, target) + if not reached: + time.sleep(0.8) + after = kit.rb_showing(ax) + jumped = kit.rb_reach(before, after, target="window") + new_keys = sorted(after - before) + + screenshot_assert( + "structure_overlay_new_surface", + "The whole screen is now heavily dimmed by a full-screen translucent " + "black overlay (about 50% black): the desktop wallpaper and icons are " + "still visible but clearly darkened, roughly half as bright as normal. " + "The overlay is borderless and covers everything edge to edge; no dialog, " + "sheet or titled window is visible.", + SS_DIR) + clear_overlays(ax) + + assert not win_before, ( + "Expected NO 'window' node in the app's AX tree before activating an " + f"opacity item; found {win_before}") + assert reached, ( + "Expected activating '50% opacity' to expose an overlay window; the reach " + f"helper returned False. AX keys added by the press: {new_keys}") + assert jumped, ( + "Expected a REAL surface jump: a new 'window' node must appear in the AX " + "tree after activating '50% opacity' (kit.rb_reach(before, after, " + f"target='window')). Keys newly present: {new_keys}; window keys before: " + f"{win_before}") diff --git a/macos/tannerc-spf/tests/test_ax_text.py b/macos/tannerc-spf/tests/test_ax_text.py new file mode 100644 index 0000000000000000000000000000000000000000..73bef561213c69f9000ced72a27c8bd283fc0fd0 --- /dev/null +++ b/macos/tannerc-spf/tests/test_ax_text.py @@ -0,0 +1,597 @@ +"""AX text tests for Spf — the app's only visible text is its title + 9 menu titles. + +Spf is an LSUIElement menu-bar-only app: no window, no labels, no status bar, no +document text. Every user-visible string lives either on the AX application element +(its title) or on the 9 AXMenuItems of the single status-bar menu. These tests pin +those EXACT strings, so a recreation reading "5%" instead of "5% opacity", "Reset" +instead of "Clear", or "Exit" instead of "Quit" fails. +""" + +import pytest +import rb_testgen_kit as kit + +# =========================================================================== +# SPF_HELPER_BLOCK (embedded VERBATIM — never imported: the eval harness may +# copy only test_ax_*.py, so every test module must be self-contained) +# =========================================================================== + +import json +import os +import re +import subprocess +import tempfile +import time + +import Quartz + +# ── Golden model constants (from MainMenu.xib + live AX tree) ──────────────── +OPACITY_ITEMS = ["5% opacity", "10% opacity", "25% opacity", "50% opacity"] +OPACITY_PCT = {"5% opacity": 5, "10% opacity": 10, "25% opacity": 25, "50% opacity": 50} +# Exact menu order in the official app ("" is the separator between Clear and Run test) +MENU_ORDER = ["5% opacity", "10% opacity", "25% opacity", "50% opacity", + "Clear", "", "Run test", "About", "Quit"] +# Big middle-of-screen sample region: below the menu bar, above the Dock. +SAMPLE_REGION = (200, 150, 1500, 700) + + +def screenshot_assert(test_name, description, results_dir=None): + """Screenshot + a SPECIFIC visual description for the VLM judge.""" + results_dir = results_dir or os.environ.get("RESULTS_DIR") or "/tmp/spf_results" + 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=8) + except Exception: + pass + af = os.path.join(ss_dir, "assertions.json") + data = {} + if os.path.exists(af): + try: + with open(af) as f: + data = json.load(f) + except Exception: + data = {} + data[f"{test_name}.png"] = description + with open(af, "w") as f: + json.dump(data, f, indent=2) + + +# ── AX geometry ────────────────────────────────────────────────────────────── + +def _pair(v): + m = re.findall(r"[-\d.]+", str(v)) + return (float(m[-2]), float(m[-1])) if len(m) >= 2 else None + + +def ax_size(ax, eid): + return _pair(ax.get(eid, ["AXSize"]).get("AXSize")) + + +def ax_pos(ax, eid): + return _pair(ax.get(eid, ["AXPosition"]).get("AXPosition")) + + +# ── Status item + menu discovery ───────────────────────────────────────────── + +def status_items(ax): + """Every menu-bar status item the app owns (AXMenuBarItem, subrole AXMenuExtra). + The official app happens to create two; only one carries the Spf menu.""" + return ax.find(role="menu_bar_item", max_results=8, max_depth=3) + + +def spf_status_item(ax): + """The status item that owns the Spf menu; falls back to the widest one.""" + best, best_w = None, -1.0 + for m in status_items(ax): + if ax.find(role="menu", root_id=m.id, max_results=2): + return m + w = (ax_size(ax, m.id) or (0.0, 0.0))[0] + if w > best_w: + best, best_w = m, w + return best + + +def spf_menu(ax): + """The AXMenu holding the opacity / Clear / Run test / About / Quit items.""" + menus = ax.find(role="menu", max_results=6) + for menu in menus: + names = [i.name or "" for i in + ax.find(role="menu_item", root_id=menu.id, max_results=30)] + if any("opacity" in n.lower() or "%" in n for n in names): + return menu + return menus[0] if menus else None + + +def menu_items(ax): + """The Spf menu's items IN ORDER (list of AXElement).""" + menu = spf_menu(ax) + return ax.find(role="menu_item", root_id=menu.id, max_results=40) if menu else [] + + +def item_names(ax): + return [i.name or "" for i in menu_items(ax)] + + +def item_map(ax): + return {i.name: i for i in menu_items(ax) if i.name} + + +def find_item(ax, *keywords): + """Locate a menu item by any keyword (case-insensitive substring) — tolerant of + a recreation naming things slightly differently.""" + for it in menu_items(ax): + low = (it.name or "").lower() + for kw in keywords: + if kw.lower() in low: + return it + return None + + +def item_enabled(ax, name_or_kw): + it = item_map(ax).get(name_or_kw) or find_item(ax, name_or_kw) + return None if it is None else bool(it.enabled) + + +def press_item(ax, name_or_el, settle=1.0): + """Activate a Spf menu item via AXPress (works with the menu closed OR open). + NOTE: AXPress may report failure while still succeeding on status-item menus, + so the return value only means 'the item was found and pressed'.""" + el = name_or_el + if isinstance(name_or_el, str): + el = item_map(ax).get(name_or_el) or find_item(ax, name_or_el) + if el is None: + return False + ax.action(el.id, "AXPress") + time.sleep(settle) + return True + + +def menu_is_open(ax): + """True when the status menu is laid out on screen (closed menus report 0x0).""" + menu = spf_menu(ax) + if menu is None: + return False + sz = ax_size(ax, menu.id) + return bool(sz and sz[0] > 1 and sz[1] > 1) + + +def dismiss_menu(ax): + """Close the status menu if it is open.""" + import verifier_helpers as vh + vh.send_key(vh.KC_ESCAPE) + time.sleep(0.4) + return not menu_is_open(ax) + + +# ── Overlay windows ───────────────────────────────────────────────────────── + +def overlay_windows(ax): + """The screen-polarizing overlay windows the app currently exposes via AX.""" + return ax.find(role="window", max_results=10, max_depth=1) + + +def cg_overlays(pid): + """CoreGraphics facts about the app's large overlay windows: window level + (`layer`), alpha and bounds. Only windows >= 400x300 count (skips status items).""" + opts = Quartz.kCGWindowListOptionAll | Quartz.kCGWindowListExcludeDesktopElements + out = [] + for w in (Quartz.CGWindowListCopyWindowInfo(opts, Quartz.kCGNullWindowID) or []): + if w.get("kCGWindowOwnerPID") != pid: + continue + b = w.get("kCGWindowBounds") or {} + if float(b.get("Width", 0)) >= 400 and float(b.get("Height", 0)) >= 300: + out.append({"layer": int(w.get("kCGWindowLayer", 0)), + "alpha": float(w.get("kCGWindowAlpha", 0)), + "x": float(b.get("X", 0)), "y": float(b.get("Y", 0)), + "w": float(b.get("Width", 0)), "h": float(b.get("Height", 0))}) + return out + + +def main_display_size(): + b = Quartz.CGDisplayBounds(Quartz.CGMainDisplayID()) + return (float(b.size.width), float(b.size.height)) + + +def n_displays(): + err, _ids, cnt = Quartz.CGGetActiveDisplayList(16, None, None) + return int(cnt) if err == 0 else 1 + + +def pid_at_screen_point(x=None, y=None): + """Which process owns the UI element at a screen point. A click-THROUGH overlay + (ignoresMouseEvents) never answers here — the window underneath does.""" + from ApplicationServices import (AXUIElementCopyElementAtPosition, + AXUIElementCreateSystemWide, AXUIElementGetPid) + w, h = main_display_size() + x = w / 2.0 if x is None else x + y = h / 2.0 if y is None else y + err, el = AXUIElementCopyElementAtPosition( + AXUIElementCreateSystemWide(), float(x), float(y), None) + if err != 0 or el is None: + return None + err2, pid = AXUIElementGetPid(el, None) + return int(pid) if err2 == 0 else None + + +def clear_overlays(ax): + """Reset the app to its clean state (no overlay on screen). Call in teardown.""" + for _ in range(3): + if not overlay_windows(ax): + return True + it = find_item(ax, "Clear") + if it is None: + return False + ax.action(it.id, "AXPress") + time.sleep(0.7) + return not overlay_windows(ax) + + +# ── Screen sampling: what the desktop actually LOOKS like through the overlay ─ + +def _cgimage_region(x, y, w, h): + img = Quartz.CGWindowListCreateImage( + Quartz.CGRectMake(x, y, w, h), Quartz.kCGWindowListOptionOnScreenOnly, + Quartz.kCGNullWindowID, Quartz.kCGWindowImageDefault) + if img is not None and Quartz.CGImageGetWidth(img) > 0: + return img + fd, p = tempfile.mkstemp(suffix=".png") + os.close(fd) + try: + subprocess.run(["screencapture", "-x", "-R", f"{x},{y},{w},{h}", p], timeout=10) + from CoreFoundation import (CFURLCreateFromFileSystemRepresentation, + kCFAllocatorDefault) + raw = p.encode() + url = CFURLCreateFromFileSystemRepresentation( + kCFAllocatorDefault, raw, len(raw), False) + src = Quartz.CGImageSourceCreateWithURL(url, None) + return Quartz.CGImageSourceCreateImageAtIndex(src, 0, None) if src else None + finally: + try: + os.unlink(p) + except OSError: + pass + + +def screen_rgb(region=SAMPLE_REGION, step=4): + """Mean (R, G, B) of a screen region, byte-order aware. None if unsamplable.""" + img = _cgimage_region(*region) + if img is None: + return None + prov = Quartz.CGImageGetDataProvider(img) + if prov is None: + return None + buf = bytes(Quartz.CGDataProviderCopyData(prov)) + bpr = Quartz.CGImageGetBytesPerRow(img) + W, H = Quartz.CGImageGetWidth(img), Quartz.CGImageGetHeight(img) + bpp = max(1, Quartz.CGImageGetBitsPerPixel(img) // 8) + little = bool(Quartz.CGImageGetBitmapInfo(img) & Quartz.kCGBitmapByteOrder32Little) + ri, gi, bi = (2, 1, 0) if little else (0, 1, 2) + tot, n = [0, 0, 0], 0 + for row in range(0, H, step): + off = row * bpr + for col in range(0, W, step): + p = off + col * bpp + if p + 2 >= len(buf): + continue + tot[0] += buf[p + ri] + tot[1] += buf[p + gi] + tot[2] += buf[p + bi] + n += 1 + return tuple(round(v / n, 2) for v in tot) if n else None + + +def screen_luma(region=SAMPLE_REGION, step=4): + rgb = screen_rgb(region, step) + return None if rgb is None else round(sum(rgb) / 3.0, 2) + + +# ── depth-family navigation (NAMED so rb_audit_depth sees the surface crossing) ─ + +def rb_enter_status_menu(ax): + """Cross into the status-bar MENU surface: press the Spf status item so its menu + is laid out on screen. Returns True once the menu reports a real size.""" + mbi = spf_status_item(ax) + if mbi is None: + return False + ax.action(mbi.id, "AXPress") + time.sleep(1.0) + if menu_is_open(ax): + return True + ax.click_element_cg(mbi.id) + time.sleep(1.0) + return menu_is_open(ax) + + +def rb_reach_overlay(ax, item="25% opacity"): + """Cross into the OVERLAY WINDOW surface by activating an opacity menu item. + Returns True once the app exposes at least one overlay window.""" + if not press_item(ax, item, settle=1.2): + return False + return len(overlay_windows(ax)) >= 1 + + +# =========================================================================== +# END SPF_HELPER_BLOCK +# =========================================================================== + +# Text-widget roles this app must NOT expose (AXHelper.ROLE_MAP maps AXStaticText -> +# "label", AXTextField -> "text_field", AXTextArea -> "text_area"; the raw spellings +# are listed too so a differently-mapped framework is still caught). +TEXT_WIDGET_ROLES = { + "label", "static_text", "statictext", "text", "text_field", "textfield", + "text_area", "textarea", "text_view", "textview", +} + +APP_TITLE = "Spf" +TITLED_ITEMS = [t for t in MENU_ORDER if t] # the 8 real strings (no separator) + + +def _all_elements(ax, root_id=None): + """Every element of the app's AX tree (role-agnostic walk — no index/path match).""" + return ax.find(root_id=root_id, max_results=200) + + +def _app_element_id(ax): + """The AXApplication root's element id (semantic: role == application).""" + root = ax.tree(max_depth=0) + return (root.get("role") if isinstance(root, dict) else None), \ + (root.get("id") if isinstance(root, dict) else None) + + +def _titles_by_position(ax): + """Menu titles ordered by on-screen y (top -> bottom). Falls back to tree order + when the menu is closed and reports no geometry.""" + rows = [] + for idx, it in enumerate(menu_items(ax)): + pos = ax_pos(ax, it.id) + rows.append(((pos[1] if pos else 0.0), idx, it.name or "")) + return [name for _y, _i, name in sorted(rows, key=lambda r: (r[0], r[1]))] + + +class TestSpfText: + """All user-visible text of Spf: the AX application title + the 9 menu titles.""" + + # ── 1. the app's own name ──────────────────────────────────────────────── + @pytest.mark.rb(depth=0, jump_kind="value", expect='AXApplication AXTitle == "Spf"') + def test_application_title_is_spf(self, ax): + role, app_id = _app_element_id(ax) + assert app_id is not None, ( + f"could not read the AX application element (root role={role!r})") + assert role == "application", ( + f"AX root role: expected 'application', got {role!r}") + raw = ax.get(app_id, ["AXTitle"]).get("AXTitle") + title = "" if raw is None else str(raw) + assert title == APP_TITLE, ( + f"AX application title: expected {APP_TITLE!r}, got {title!r}") + + # ── 2. the whole ordered title list ───────────────────────────────────── + @pytest.mark.rb(depth=0, jump_kind="value", + expect='menu titles == ["5% opacity", "10% opacity", "25% opacity", ' + '"50% opacity", "Clear", "", "Run test", "About", "Quit"]') + def test_menu_titles_exact_order(self, ax): + titles = item_names(ax) + assert titles == MENU_ORDER, ( + "menu titles differ from the golden text.\n" + f" expected ({len(MENU_ORDER)}): {MENU_ORDER}\n" + f" actual ({len(titles)}): {titles}") + + # ── 3. the four opacity strings + their numbers ───────────────────────── + @pytest.mark.rb(depth=0, jump_kind="value", + expect='titles "5% opacity"/"10% opacity"/"25% opacity"/"50% opacity" ' + 'with embedded numbers 5, 10, 25, 50 in that order') + def test_opacity_titles_and_numbers(self, ax): + titles = item_names(ax) + opacity_titles = [t for t in titles if "%" in t or "opacity" in t.lower()] + assert len(opacity_titles) == len(OPACITY_ITEMS), ( + f"expected {len(OPACITY_ITEMS)} opacity titles {OPACITY_ITEMS}, " + f"found {len(opacity_titles)}: {opacity_titles} (all titles: {titles})") + parsed = [] + for got, want in zip(opacity_titles, OPACITY_ITEMS): + assert got == want, ( + f"opacity title text: expected {want!r}, got {got!r} " + f"(full opacity list: {opacity_titles})") + m = re.search(r"(\d+)", got) + assert m is not None, f"no number inside opacity title {got!r}" + parsed.append(int(m.group(1))) + assert len(got) == len(want), ( + f"character count of {got!r} is {len(got)}, expected {len(want)} " + f"for {want!r} (stray padding or a different label)") + expected_pcts = [OPACITY_PCT[t] for t in OPACITY_ITEMS] + assert parsed == expected_pcts, ( + f"embedded opacity numbers: expected {expected_pcts}, got {parsed}") + + # ── 4. "Clear" (not Reset/Remove/Off) ─────────────────────────────────── + @pytest.mark.rb(depth=0, jump_kind="value", expect='the removal item title == "Clear"') + def test_clear_item_title(self, ax): + titles = item_names(ax) + assert "Clear" in item_map(ax), ( + f"no menu item titled 'Clear' — titles are {titles} " + "(a recreation must not rename it to Reset/Remove/Off)") + it = find_item(ax, "clear", "reset", "remove", "off", "清除", "清空") + assert it is not None and (it.name or "") == "Clear", ( + f"removal item title: expected 'Clear', got " + f"{(it.name if it else None)!r} (all titles: {titles})") + + # ── 5. "Run test" (exact case, single space) ───────────────────────────── + @pytest.mark.rb(depth=0, jump_kind="value", expect='the test item title == "Run test"') + def test_run_test_item_title(self, ax): + titles = item_names(ax) + it = find_item(ax, "run test", "test", "测试", "运行") + assert it is not None, f"no test item found — titles are {titles}" + got = it.name or "" + assert got == "Run test", ( + f"test item title: expected 'Run test' (exact case, single space), " + f"got {got!r} (all titles: {titles})") + assert "Run test" in item_map(ax), ( + f"'Run test' missing from the title set {sorted(item_map(ax))}") + + # ── 6. "About" — literal title is load-bearing (goToAbout compares it) ── + @pytest.mark.rb(depth=0, jump_kind="value", + expect='the about item title == "About", enabled, offers AXPress') + def test_about_item_title_is_load_bearing(self, ax): + titles = item_names(ax) + it = find_item(ax, "about", "关于") + assert it is not None, f"no about item found — titles are {titles}" + got = it.name or "" + # goToAbout() only opens https://github.com/tannerc/spf when + # `sender.title == "About"`, so any other spelling breaks the feature. + assert got == "About", ( + f"about item title: expected 'About' (the handler compares " + f"sender.title == \"About\" before opening the URL), got {got!r} " + f"(all titles: {titles})") + assert bool(it.enabled), "the 'About' item must be enabled" + assert "AXPress" in (it.actions or []), ( + f"'About' offers no AXPress action; actions={it.actions}") + # NEVER pressed: pressing it launches an external browser. + + # ── 7. "Quit" (not Exit / Quit Spf) ───────────────────────────────────── + @pytest.mark.rb(depth=0, jump_kind="value", expect='the quit item title == "Quit"') + def test_quit_item_title(self, ax): + titles = item_names(ax) + it = find_item(ax, "quit", "exit", "terminate", "退出") + assert it is not None, f"no quit item found — titles are {titles}" + got = it.name or "" + assert got == "Quit", ( + f"quit item title: expected 'Quit' (not 'Exit' / 'Quit Spf'), " + f"got {got!r} (all titles: {titles})") + assert titles and titles[-1] == "Quit", ( + f"'Quit' must be the LAST menu title; last is {titles[-1]!r}") + # NEVER pressed. + + # ── 8. text shape: 8 non-empty titles + 1 empty separator, all distinct ── + @pytest.mark.rb(depth=0, jump_kind="none", + expect="9 items: exactly 1 empty title (separator at index 5), " + "8 non-empty and all 9 entries distinct") + def test_title_text_shape(self, ax): + titles = item_names(ax) + assert len(titles) == 9, ( + f"expected 9 menu entries (8 titled + 1 separator), got {len(titles)}: {titles}") + empties = [i for i, t in enumerate(titles) if not t.strip()] + assert len(empties) == 1, ( + f"expected exactly ONE empty title (the separator), got {len(empties)} " + f"at indices {empties}: {titles}") + assert empties[0] == 5, ( + f"the empty separator must be at index 5, found it at {empties[0]}: {titles}") + non_empty = [t for t in titles if t.strip()] + assert len(non_empty) == 8, ( + f"expected 8 titles WITH text, got {len(non_empty)}: {non_empty}") + assert len(set(titles)) == 9, ( + f"all 9 entries must be distinct, got {len(set(titles))} unique: {titles}") + for t in non_empty: + assert t == t.strip(), f"title {t!r} carries stray whitespace padding" + got_chars = sum(len(t) for t in titles) + want_chars = sum(len(t) for t in MENU_ORDER) + assert got_chars == want_chars, ( + f"total character count of all titles: expected {want_chars} " + f"(from {MENU_ORDER}), got {got_chars} (from {titles})") + + # ── 9. no other text surface exists (no window => no labels) ──────────── + @pytest.mark.rb(depth=0, jump_kind="none", + expect="no static_text / label / text_field / text_area element " + "anywhere in the app tree") + def test_no_other_text_surface(self, ax): + roles = [(el.role or "") for el in _all_elements(ax)] + offenders = sorted({r for r in roles if r.lower() in TEXT_WIDGET_ROLES}) + assert not offenders, ( + f"menu-bar-only app must expose NO text widgets, found roles {offenders} " + f"(all roles present: {sorted(set(roles))})") + text_els = ax.find_text_elements(max_results=50) + bad = [(el.role, el.text) for el in text_els + if (el.role or "").lower() in TEXT_WIDGET_ROLES] + assert not bad, ( + f"text content found on label/text widgets outside the menu: {bad}") + # Sanity: the text that DOES exist lives on the app + its menu items. + with_text = [(el.role, el.text) for el in text_els] + assert with_text, ( + "no text-bearing element at all — expected the app title plus the " + f"{len(TITLED_ITEMS)} menu titles {TITLED_ITEMS}") + + # ── 10. titles while the menu is OPEN on screen (depth 1) ─────────────── + @pytest.mark.rb(depth=1, jump_kind="value", + expect='the OPEN menu reads top-to-bottom ["5% opacity", "10% opacity", ' + '"25% opacity", "50% opacity", "Clear", "", "Run test", ' + '"About", "Quit"]') + def test_open_menu_titles_top_to_bottom(self, ax): + try: + opened = rb_enter_status_menu(ax) + ordered = _titles_by_position(ax) + screenshot_assert( + "text_menu_titles_open", + "The open Spf status menu drops down from the small monochrome icon in " + "the top-right macOS menu bar. It shows nine rows in this exact order: " + "'5% opacity', '10% opacity', '25% opacity', '50% opacity', a " + "greyed-out/disabled 'Clear', a thin horizontal separator line, " + "'Run test', 'About', and 'Quit'. No other window or label is visible; " + "the desktop behind the menu is untinted.", + os.environ.get("RESULTS_DIR")) + finally: + dismiss_menu(ax) + assert opened, ( + "pressing the Spf status item did not lay its menu out on screen " + "(menu still reports a 0x0 size)") + assert ordered == MENU_ORDER, ( + "titles read off the OPEN menu (sorted by screen y) differ from the golden text.\n" + f" expected: {MENU_ORDER}\n" + f" actual: {ordered}") + + # ── 11. the overlay window is UNTITLED (depth 1) ──────────────────────── + @pytest.mark.rb(depth=1, jump_kind="value", + expect='the overlay window AXTitle is "" / None and it holds no ' + 'static_text child (bare tint layer, not a titled window)') + def test_overlay_window_is_untitled(self, ax): + try: + reached = rb_reach_overlay(ax, "25% opacity") + wins = overlay_windows(ax) + titles, child_roles = [], [] + for w in wins: + raw = ax.get(w.id, ["AXTitle"]).get("AXTitle") + titles.append("" if raw is None else str(raw)) + child_roles += [(el.role or "") for el in _all_elements(ax, root_id=w.id)] + screenshot_assert( + "text_overlay_untitled", + "The whole desktop is covered by a uniform 25% black tint created by " + "Spf; the wallpaper and icons stay visible through it. The overlay has " + "NO title bar, NO window title text, and no labels or buttons of any " + "kind — it is a bare borderless tint layer. The menu bar at the top is " + "not covered.", + os.environ.get("RESULTS_DIR")) + finally: + clear_overlays(ax) + assert reached and wins, ( + "activating '25% opacity' exposed no overlay window via AX " + f"(reached={reached}, windows={len(wins)})") + for t in titles: + assert not t.strip(), ( + f"overlay window title: expected '' (untitled borderless layer), got {t!r}") + offenders = sorted({r for r in child_roles if r.lower() in TEXT_WIDGET_ROLES}) + assert not offenders, ( + f"overlay window must contain no text widgets, found roles {offenders} " + f"(all child roles: {sorted(set(child_roles))})") + + # ── 12. icon-only status item, text lives in its menu (depth 1) ───────── + @pytest.mark.rb(depth=1, jump_kind="value", + expect='status item has no non-empty AXValue, while its OPEN menu ' + 'carries all 8 strings ["5% opacity", "10% opacity", ' + '"25% opacity", "50% opacity", "Clear", "Run test", "About", ' + '"Quit"]') + def test_status_item_icon_only_menu_carries_text(self, ax): + mbi = spf_status_item(ax) + assert mbi is not None, "the app owns no menu-bar status item" + raw = ax.get(mbi.id, ["AXValue"]).get("AXValue") + val = raw if isinstance(raw, str) else "" + assert not val.strip(), ( + f"the status item must be ICON-ONLY (no text value), but AXValue is {val!r}") + try: + opened = rb_enter_status_menu(ax) + open_titles = item_names(ax) + finally: + dismiss_menu(ax) + assert opened, ( + "pressing the status item did not open its menu on screen " + f"(titles seen: {open_titles})") + missing = [t for t in TITLED_ITEMS if t not in open_titles] + assert not missing, ( + f"the open menu is missing these exact strings: {missing}\n" + f" expected all of: {TITLED_ITEMS}\n" + f" actual titles: {open_titles}") diff --git a/macos/tannerc-spf/tests/testcase_counts.json b/macos/tannerc-spf/tests/testcase_counts.json new file mode 100644 index 0000000000000000000000000000000000000000..aeef0bbee3b8f48018e4ab5420e00ef69c4ac485 --- /dev/null +++ b/macos/tannerc-spf/tests/testcase_counts.json @@ -0,0 +1,33 @@ +{ + "ax_total": 75, + "vlm_total": 6, + "ax_by_lane": { + "test_ax_buttons.py": 11, + "test_ax_computation.py": 13, + "test_ax_menus.py": 14, + "test_ax_states.py": 13, + "test_ax_structure.py": 12, + "test_ax_text.py": 12 + }, + "vlm_by_dir": { + "buttons": 1, + "computation": 1, + "menus": 1, + "states": 1, + "structure": 2, + "text": 0 + }, + "vlm_names": [ + "buttons_status_menu_open.png", + "computation_50pct_overlay.png", + "menus_run_test_overlay.png", + "states_clear_enabled_with_overlay.png", + "structure_menu_open_layout.png", + "structure_status_item.png" + ], + "frozen_at": "stage2_finalize", + "vlm_pruned_offline_rejudge": [ + "buttons_overlay_active_25pct.png", + "menus_status_menu_open.png" + ] +} \ No newline at end of file diff --git a/macos/tannerc-spf/tests/verifier_helpers.py b/macos/tannerc-spf/tests/verifier_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..ce369cdae8db3a7427890d1636f8f5a3201dbef1 --- /dev/null +++ b/macos/tannerc-spf/tests/verifier_helpers.py @@ -0,0 +1,753 @@ +""" +verifier_helpers.py — High-level AX testing patterns for macOS app verification. + +v6 core library. Encodes all robust testing patterns as reusable functions +so verifier agents call high-level APIs instead of building from scratch. + +Depends on: ax_helpers.py (AXHelper class) +""" + +import datetime +import os +import re +import signal +import subprocess +import time +from collections import Counter + +# --------------------------------------------------------------------------- +# Key codes (macOS virtual key codes) +# --------------------------------------------------------------------------- +KC_LEFT_ARROW = 123 +KC_RIGHT_ARROW = 124 +KC_UP_ARROW = 126 +KC_DOWN_ARROW = 125 +KC_SPACE = 49 +KC_RETURN = 36 +KC_TAB = 48 +KC_ESCAPE = 53 +KC_Q = 12 +KC_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": , "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)" + ) diff --git a/macos/tannerc-spf/vlm_assertions.json b/macos/tannerc-spf/vlm_assertions.json new file mode 100644 index 0000000000000000000000000000000000000000..634a8f69de6578e4e942cdce01b2f3f5d2ffd2ea --- /dev/null +++ b/macos/tannerc-spf/vlm_assertions.json @@ -0,0 +1,101 @@ +{ + "schema_version": 2, + "instance_id": "macos/tannerc-spf", + "grading": { + "mode": "deferred", + "model": null, + "scored_separately": true + }, + "totals": { + "assertions": 6, + "with_verdict": 0, + "calibrated": 0, + "usable": null, + "scored_records": 0, + "unbacked_records": 0 + }, + "assertions": [ + { + "id": "buttons_status_menu_open.png", + "screenshot": "buttons_status_menu_open.png", + "assertion": "The Spf status-bar menu is open, dropped down from a small monochrome sunglasses/polarizer icon at the right-hand end of the macOS menu bar. The menu is a narrow white/dark dropdown listing, top to bottom: '5% opacity', '10% opacity', '25% opacity', '50% opacity', 'Clear' (greyed out / disabled), a thin horizontal separator line, 'Run test', 'About', 'Quit'. No application window and no Dock icon belong to this app, and the desktop behind the menu is NOT darkened.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "buttons_status_menu_open.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "computation_50pct_overlay.png", + "screenshot": "computation_50pct_overlay.png", + "assertion": "The entire desktop is covered by a uniform half-strength black wash, so the wallpaper looks about half as bright as normal (mean screen luma drops to ~48% of its unobstructed value) while still being clearly visible through the tint. The darkening is even edge-to-edge with no window frame, title bar, border, shadow or dialog anywhere, and no colour cast (grey/black only, not red or blue). The menu bar area at the top shows the Spf status icon and the status menu is closed.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "computation_50pct_overlay.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "menus_run_test_overlay.png", + "screenshot": "menus_run_test_overlay.png", + "assertion": "Just after choosing 'Run test' from the Spf menu: the menu has closed and the whole desktop is washed with a translucent RED tint (the self-test confirmation overlay) — the wallpaper is still visible through it but everything has a clear red cast. No menu or dialog is open.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "menus_run_test_overlay.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "states_clear_enabled_with_overlay.png", + "screenshot": "states_clear_enabled_with_overlay.png", + "assertion": "The Spf menu is open, dropped down from its small monochrome icon in the top-right menu bar, over a visibly darkened (25% black tinted) desktop. The menu lists 5% opacity, 10% opacity, 25% opacity, 50% opacity, then Clear, a separator line, Run test, About and Quit. The 'Clear' row is now drawn in normal black/active text (selectable) rather than the greyed-out disabled text it showed before any overlay existed; every opacity row is also active.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "states_clear_enabled_with_overlay.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "structure_status_item.png", + "screenshot": "structure_status_item.png", + "assertion": "The app has NO Dock icon and NO window on screen. In the right-hand side of the macOS menu bar at the very top of the display there is a small monochrome (template) status-bar icon for this app, sitting among the other system menu-bar extras. No application menu bar (File/Edit/View) belongs to this app.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "structure_status_item.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "structure_menu_open_layout.png", + "screenshot": "structure_menu_open_layout.png", + "assertion": "The app's status menu is OPEN, dropped down from its small monochrome icon in the top-right menu bar. The menu is a narrow vertical popup (about 105x197 points) listing exactly these rows top to bottom: '5% opacity', '10% opacity', '25% opacity', '50% opacity', 'Clear' (greyed out / disabled), then a thin horizontal separator line, then 'Run test', 'About', 'Quit'. No keyboard shortcuts are shown on the right of any row. The desktop behind the menu is NOT tinted or darkened, and there is no application window.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "structure_menu_open_layout.png", + "rigor": null, + "verdict": null, + "calibration": null + } + ], + "merged_from_files": 6, + "source_shapes": { + "dict_str": 6 + } +} \ No newline at end of file diff --git a/macos/ttlapp-time-to-leave/LICENSE b/macos/ttlapp-time-to-leave/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..f288702d2fa16d3cdf0035b15a9fcbc552cd88e7 --- /dev/null +++ b/macos/ttlapp-time-to-leave/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. 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 work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a 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 visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation 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 to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients 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 to +produce it from the Program, in the form of source code under the +terms 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 independent +works, 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 not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-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 excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the 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 install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional 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 you +add to a covered work, you may (if authorized by the copyright holders of +that 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 "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form 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 expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered 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 automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent 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 anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain 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 limiting +any implied license or other defenses to infringement that may +otherwise 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 or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES 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 OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy 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 greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + 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 GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/macos/ttlapp-time-to-leave/instance.json b/macos/ttlapp-time-to-leave/instance.json new file mode 100644 index 0000000000000000000000000000000000000000..c5f7b956a2a75fa542f434b6a378e6289be1d498 --- /dev/null +++ b/macos/ttlapp-time-to-leave/instance.json @@ -0,0 +1,10 @@ +{ + "schema_version": 1, + "instance_id": "macos/ttlapp-time-to-leave", + "platform": "macos", + "repo": "https://github.com/TTLApp/time-to-leave", + "commit": "6a471d9d4effa626bc88dad5ba39d5db6638cb63", + "patches": [], + "package": null, + "license": null +} \ No newline at end of file diff --git a/macos/ttlapp-time-to-leave/reference/build.sh b/macos/ttlapp-time-to-leave/reference/build.sh new file mode 100644 index 0000000000000000000000000000000000000000..49755b9d00827fd306f08a36addc39fb4f22b265 --- /dev/null +++ b/macos/ttlapp-time-to-leave/reference/build.sh @@ -0,0 +1,141 @@ +#!/usr/bin/env bash +# +# Standalone build script for "Time to Leave" (Electron desktop app, macOS). +# +# Reproduces the full build from a clean checkout: +# npm install -> fix extract-zip for Node >= 24 -> package universal .app +# +# The only non-obvious step is the extract-zip fix: on Node >= 24 the version of +# extract-zip pinned by Electron's toolchain silently truncates archive +# extraction (it stops after a handful of entries), so both Electron's binary +# download and electron-packager's stitching produce broken/empty app bundles. +# We replace extract-zip's implementation with a thin wrapper around macOS' +# native `ditto`, which extracts Electron zips correctly (symlinks, perms, etc). +# +# Usage: bash build.sh +# Output: "$SCRIPT_DIR/release-builds/Time to Leave-darwin-universal/Time to Leave.app" +# and a copy in "${APP_OUTPUT_DIR:-$SCRIPT_DIR}". + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd "$SCRIPT_DIR" + +APP_NAME="Time to Leave" +APP_BUNDLE="${APP_NAME}.app" +PACKAGED_DIR="release-builds/${APP_NAME}-darwin-universal" +OUTPUT_DIR="${APP_OUTPUT_DIR:-$SCRIPT_DIR}" + +log() { printf '\n==> %s\n' "$*"; } + +# --------------------------------------------------------------------------- +# 1. Toolchain: make sure Node.js / npm are available. +# --------------------------------------------------------------------------- +if ! command -v node >/dev/null 2>&1; then + log "Node.js not found - installing via Homebrew" + if command -v brew >/dev/null 2>&1; then + brew install node + else + echo "ERROR: node is required but not installed, and Homebrew is unavailable." >&2 + exit 1 + fi +fi +log "Using node $(node --version) / npm $(npm --version)" + +# --------------------------------------------------------------------------- +# 2. Install JS dependencies. +# (The repo's own preinstall/prepare lifecycle scripts run automatically. +# Dependency install-scripts may be blocked by a machine-level npm policy; +# that is fine - we redo the only one that matters, Electron's, below.) +# --------------------------------------------------------------------------- +log "Installing npm dependencies" +npm install + +# --------------------------------------------------------------------------- +# 3. Fix extract-zip so it works on modern Node. +# All consumers (electron, @electron/get, @electron/packager) resolve to this +# single hoisted copy, so overwriting it once repairs the whole toolchain. +# --------------------------------------------------------------------------- +EXTRACT_ZIP="node_modules/extract-zip/index.js" +if [ -f "$EXTRACT_ZIP" ]; then + log "Patching extract-zip to use native 'ditto'" + cat > "$EXTRACT_ZIP" <<'EXTRACT_ZIP_JS' +'use strict' +// Drop-in replacement for extract-zip. +// +// The upstream yauzl/lazyEntries implementation silently stops reading after a +// few entries on Node >= 24, producing a truncated extraction. Electron .app +// zips therefore come out empty/broken. macOS' `ditto` extracts PKZip archives +// natively while preserving symlinks and permissions, which Electron bundles +// require. This keeps the exact same module signature: an async function +// (zipPath, opts) where opts.dir is the (absolute) destination directory. +const { execFile } = require('child_process') +const fs = require('fs').promises +const path = require('path') + +module.exports = async function (zipPath, opts) { + opts = opts || {} + if (!opts.dir || !path.isAbsolute(opts.dir)) { + throw new Error('Target directory is expected to be absolute') + } + await fs.mkdir(opts.dir, { recursive: true }) + const dir = await fs.realpath(opts.dir) + await new Promise((resolve, reject) => { + execFile('/usr/bin/ditto', ['-x', '-k', zipPath, dir], { maxBuffer: 1024 * 1024 * 64 }, (err) => { + if (err) reject(err) + else resolve() + }) + }) +} +EXTRACT_ZIP_JS +else + echo "WARNING: $EXTRACT_ZIP not found; skipping patch (npm layout changed?)." >&2 +fi + +# --------------------------------------------------------------------------- +# 4. Ensure Electron's own binary is properly downloaded/extracted. +# Electron's postinstall may have been skipped or run through the broken +# extractor; redo it now with the repaired extract-zip. This makes +# node_modules/electron usable (e.g. `npm start`) and warms the download +# cache that packaging reuses. Non-fatal: packaging downloads independently. +# --------------------------------------------------------------------------- +if [ -f node_modules/electron/install.js ]; then + log "(Re)installing Electron binary" + rm -rf node_modules/electron/dist node_modules/electron/path.txt + if ! node node_modules/electron/install.js; then + echo "WARNING: Electron binary install step failed; continuing (packager downloads its own copy)." >&2 + fi +fi + +# --------------------------------------------------------------------------- +# 5. Package the universal macOS .app. +# Mirrors the repo's `npm run package:mac` (electron-packager, darwin +# universal). Code signing is intentionally disabled/absent for an +# unsigned local build. +# --------------------------------------------------------------------------- +log "Packaging macOS app (darwin universal)" +npm run package:mac + +APP_PATH="$SCRIPT_DIR/$PACKAGED_DIR/$APP_BUNDLE" +if [ ! -d "$APP_PATH" ]; then + echo "ERROR: expected app bundle not found at: $APP_PATH" >&2 + exit 1 +fi + +# --------------------------------------------------------------------------- +# 6. Publish the artifact to the requested output directory. +# --------------------------------------------------------------------------- +mkdir -p "$OUTPUT_DIR" +if [ "$(cd "$OUTPUT_DIR" && pwd)" != "$SCRIPT_DIR" ]; then + log "Copying app bundle to $OUTPUT_DIR" + rm -rf "$OUTPUT_DIR/$APP_BUNDLE" + cp -R "$APP_PATH" "$OUTPUT_DIR/" +else + log "Copying app bundle to project root" + rm -rf "$SCRIPT_DIR/$APP_BUNDLE" + cp -R "$APP_PATH" "$SCRIPT_DIR/" +fi + +log "Build complete" +echo " Packaged: $APP_PATH" +echo " Copied to: $OUTPUT_DIR/$APP_BUNDLE" diff --git a/macos/ttlapp-time-to-leave/reference/launch.sh b/macos/ttlapp-time-to-leave/reference/launch.sh new file mode 100644 index 0000000000000000000000000000000000000000..7c4984e1ecd2bc2cf438d764689e8712e921b622 --- /dev/null +++ b/macos/ttlapp-time-to-leave/reference/launch.sh @@ -0,0 +1,54 @@ +#!/usr/bin/env bash +# +# Launch script for "Time to Leave" (Electron desktop app, macOS). +# +# Locates the built .app relative to this script and runs it. Works standalone, +# without build.sh having been sourced. +# +# Usage: bash launch.sh [args passed through to the app] + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" + +APP_NAME="Time to Leave" +APP_BUNDLE="${APP_NAME}.app" + +# Search order: explicit output dir, project root (build.sh's default copy), +# then the raw electron-packager output directory. +CANDIDATES=() +if [ -n "${APP_OUTPUT_DIR:-}" ]; then + CANDIDATES+=("$APP_OUTPUT_DIR/$APP_BUNDLE") +fi +CANDIDATES+=( + "$SCRIPT_DIR/$APP_BUNDLE" + "$SCRIPT_DIR/release-builds/${APP_NAME}-darwin-universal/$APP_BUNDLE" +) + +APP_PATH="" +for candidate in "${CANDIDATES[@]}"; do + if [ -d "$candidate" ]; then + APP_PATH="$candidate" + break + fi +done + +if [ -z "$APP_PATH" ]; then + echo "ERROR: could not find '$APP_BUNDLE'. Looked in:" >&2 + for candidate in "${CANDIDATES[@]}"; do echo " - $candidate" >&2; done + echo "Run 'bash build.sh' first." >&2 + exit 1 +fi + +BIN="$APP_PATH/Contents/MacOS/$APP_NAME" +if [ ! -x "$BIN" ]; then + echo "ERROR: app executable not found or not executable: $BIN" >&2 + exit 1 +fi + +echo "Launching: $APP_PATH" + +# Run the bundled binary directly so stdout/stderr and any CLI args ("$@") +# pass straight through. Electron ships its own frameworks via @rpath, so no +# DYLD_* / plugin-path environment is required. +exec "$BIN" --force-renderer-accessibility "$@" diff --git a/macos/ttlapp-time-to-leave/tests/ax_helpers.py b/macos/ttlapp-time-to-leave/tests/ax_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..2418d7b8c75891c2d08906848d6a36517cb98135 --- /dev/null +++ b/macos/ttlapp-time-to-leave/tests/ax_helpers.py @@ -0,0 +1,849 @@ +import os +import re +import time +import warnings +import subprocess +from dataclasses import dataclass, field +from typing import Optional +from 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", +} + + +@dataclass +class 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 None diff --git a/macos/ttlapp-time-to-leave/tests/conftest.py b/macos/ttlapp-time-to-leave/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..21a9b7debd04c0633d77a60d8269102790a13e84 --- /dev/null +++ b/macos/ttlapp-time-to-leave/tests/conftest.py @@ -0,0 +1,584 @@ +""" +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 json +import os +import signal +import subprocess +import tempfile +import 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 _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 ` whose ARGUMENT merely contains the bundle path. + + A running .app's argv0 is /Contents/MacOS/, so we require that inner + executable path. The old bare-substring test (`app_path in args`) also matched the + lingering `open -W ` 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 == /Contents/MacOS/. + 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 ` 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//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//... — 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.fixture +def app_process(app_path): + pid = _launch_app(app_path) + yield pid + _kill_pid(pid) + + +@pytest.fixture +def 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.fixture +def 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")) diff --git a/macos/ttlapp-time-to-leave/tests/rb_testgen_kit.py b/macos/ttlapp-time-to-leave/tests/rb_testgen_kit.py new file mode 100644 index 0000000000000000000000000000000000000000..ccbbdd3c6136513161c133fbb4cefcfb0386d55c --- /dev/null +++ b/macos/ttlapp-time-to-leave/tests/rb_testgen_kit.py @@ -0,0 +1,575 @@ +#!/usr/bin/env python3 +"""RB TestGen Kit (macOS/AX port of the Linux v7.5 kit) — a test's NAVIGATION +DEPTH and JUMP RIGOR are DECLARED (not inferred), uniformly recorded, and +self-auditable. + +DIFFERENCE FROM LINUX: macOS tests are **pytest** (methods on Test* classes taking +the `ax` fixture, plain asserts) — NOT standalone scripts calling R.record(). So the +DECLARATION is a pytest marker on the test method: + + import rb_testgen_kit as kit + + @pytest.mark.rb(depth=1, jump_kind="reach", expect="Preferences window visible") + def test_prefs_opens(self, ax_with_reset): + before = kit.rb_showing(ax_with_reset) + helpers.rb_reach_prefs(ax_with_reset) # a nav helper you name rb_reach_* / rb_enter_* + after = kit.rb_showing(ax_with_reset) + assert kit.rb_reach(before, after, target="Preferences", source="menu bar") + +conftest.py's pytest_runtest_makereport hook reads the marker + the test outcome and +writes {name, passed, depth, jump_kind, tier, expect} so the runner can fold it into +_results.json. The audits below then read those records (+ the test SOURCE). + +jump_kind (verbatim strings — the audit/stats key off them): + "none" no trigger; existence/structure only -> tier 0 + "liveness" only "did not crash / still alive" -> tier 1 (weak; avoid) + "reach" a real surface jump: the TARGET surface's element + APPEARED and the SOURCE surface's element DISAPPEARED -> tier 2 + "transition" a state flip (CHECKED/ENABLED/mode) before->after -> tier 2 + "value" a specific expected value/content was asserted -> tier 3 + +DEPTH is the number of surfaces crossed before the assertion (0 = home/first screen, +1 = one dialog/panel/submenu, 2+ = deeper). A flat-tree read of a deep element is +depth 0 — depth counts surfaces the test actually navigated through. + +REACH PROOF (so "reach" cannot be faked by reading a flat tree): + before = rb_showing(ax) + + 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('')" + python3 -c "import rb_testgen_kit as k; k.rb_lint('')" + python3 -c "import rb_testgen_kit as k; k.rb_lint_sources('')" + python3 -c "import rb_testgen_kit as k; k.rb_audit_depth('','')" +""" +from __future__ import annotations + +import ast +import glob +import json +import os +import re + +JUMP_KINDS = {"none": 0, "liveness": 1, "reach": 2, "transition": 2, "value": 3} + +# Double-axis quota TARGETS (fractions) — goals rb_audit REPORTS, NOT a hard gate. +QUOTAS = { + "existence_max": 0.30, # jump_kind=="none" share of ALL tests + "interactive_min": 0.60, # reach|transition|value share of ALL tests + "depth_ge1_min": 0.40, # depth>=1 share of INTERACTIVE tests + "depth_ge2_min": 0.10, # depth>=2 share of INTERACTIVE tests + "value_min": 0.25, # jump_kind=="value" share of INTERACTIVE tests +} + +# Depth family: a test "crosses a surface" iff it calls a member of the depth family. +# macOS accepts BOTH the naming convention rb_enter_*/rb_reach_* (write your own nav +# helper and NAME it so) AND the existing verifier_helpers/ax_helpers navigation +# functions (whitelist below) — so tests can reuse the mature reveal/navigate helpers. +DEPTH_FWD_RE = re.compile(r"^rb_(enter|reach)[a-z0-9_]*$") +DEPTH_BACK_RE = re.compile(r"^rb_back[a-z0-9_]*$") +# verifier_helpers / ax_helpers navigation functions that OPEN or move to a new surface. +FWD_WHITELIST = { + "ensure_ui_visible", "ensure_panel_open", "open_actions_menu", "open_menu", + "open_settings", "open_preferences", "open_dialog", "open_panel", "open_window", + "navigate_month", "navigate", "switch_tab", "switch_mode", "switch_page", + "select_tab", "reveal_window", "show_panel", "show_menu", +} +BACK_WHITELIST = { + "dismiss_menus", "dismiss_panel", "dismiss_any_dialog", "close_panel", + "close_window", "go_back", +} +# pytest fixtures that themselves navigate into a surface during setup (so a test taking +# one legitimately has depth>=1 without a nav call in its own body). `ax` does NOT navigate. +_NAV_FIXTURES = {"ax_with_reset", "open_panel"} +# MEASURED-TIER verdict families (ported from keliang): a tier2/3 jump_kind must be BACKED +# by its verdict function — transition->rb_flip*, value->rb_value*, reach->rb_reach* — whose +# bool result is the test's assertion. Self-named wrappers count by prefix. +TIER_FLIP_RE = re.compile(r"^rb_flip[a-z0-9_]*$") +TIER_VALUE_RE = re.compile(r"^rb_value[a-z0-9_]*$") +_JK_FAMILY = {"transition": "flip", "value": "value", "reach": "reach"} +# normalize plural (v73prep) / singular module names so a JSON module ("button") and a +# file stem ("buttons") join. +_MODULE_ALIAS = {"menus": "menu", "buttons": "button", "states": "state", + "structures": "structure", "texts": "text", + "computations": "computation", "workflows": "workflow"} + +_DEPTH = 0 # module-global surface counter for rb_enter/rb_back + + +def tier_of(jump_kind: str) -> int: + return JUMP_KINDS.get(jump_kind, 2) + + +def rb_reset_depth() -> None: + global _DEPTH + _DEPTH = 0 + + +def rb_enter(_surface: str = "") -> int: + """Call right after your test navigates into a new surface (dialog/panel/submenu).""" + global _DEPTH + _DEPTH += 1 + return _DEPTH + + +def rb_back() -> int: + global _DEPTH + _DEPTH = max(0, _DEPTH - 1) + return _DEPTH + + +def _walk_tree_nodes(node, out, seen): + """Yield 'role|name' for a macOS AXHelper.tree() dict node (+children).""" + if not isinstance(node, dict) or seen[0] >= 8000: + return + seen[0] += 1 + role = str(node.get("role") or "") + name = str(node.get("name") or node.get("value") or "") + if role or name: + out.add(f"{role}|{name}") + for c in (node.get("children") or []): + _walk_tree_nodes(c, out, seen) + + +def rb_showing(ax, max_depth: int = 12) -> set: + """Snapshot the currently-reachable AX subtree under the app as {"role|name"}. + macOS AX has no AT-SPI SHOWING/VISIBLE state, so we approximate "showing" by the + live AX tree (AXChildren) the app currently exposes — a new window/sheet/popover + adds its elements; a dismissed one removes them. Feed before+after a trigger to + rb_reach() so a 'reach' test proves a REAL surface change, not a flat-tree read. + Safe no-op (empty set) if `ax` cannot produce a tree.""" + out: set = set() + try: + tree = ax.tree(max_depth=max_depth) # AXHelper.tree() -> nested dict + except Exception: + return out + _walk_tree_nodes(tree, out, [0]) + return out + + +def rb_reach(before, after, target: str, source: str | None = None) -> bool: + """True-jump verdict: the TARGET surface's discriminating element newly APPEARED + AND (if given) the SOURCE surface's discriminating element DISAPPEARED. This is + what separates a real surface jump from reading an element that was always there.""" + before = set(before or []) + after = set(after or []) + t = target.lower() + appeared = any(t in k.lower() for k in (after - before)) + if source is None: + return appeared + s = source.lower() + src_before = any(s in k.lower() for k in before) + src_after = any(s in k.lower() for k in after) + return appeared and src_before and not src_after + + +def rb_flip(before, after, expect: str = "") -> bool: + """In-page STATE-FLIP verdict (tier2 `transition`): the observed state actually CHANGED + before->after (a CHECKED/ENABLED/mode/selection value read the two times). Pass its bool + as the test's assertion. Does NOT touch depth — an in-page flip is depth 0 unless you + navigated a surface to reach the control. You MAY write your own `rb_flip_()` 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_()` 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 | " + "{audit_depth|audit_tier} [results_dir]}") diff --git a/macos/ttlapp-time-to-leave/tests/requirements.txt b/macos/ttlapp-time-to-leave/tests/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..feef67ce2aadbaa26d12e6b01cff7b8ce89ecb5c --- /dev/null +++ b/macos/ttlapp-time-to-leave/tests/requirements.txt @@ -0,0 +1,3 @@ +pytest +pytest-check +pyobjc diff --git a/macos/ttlapp-time-to-leave/tests/test_ax_buttons.py b/macos/ttlapp-time-to-leave/tests/test_ax_buttons.py new file mode 100644 index 0000000000000000000000000000000000000000..83d96dcc65511276c52f663975058e5fcee3b497 --- /dev/null +++ b/macos/ttlapp-time-to-leave/tests/test_ax_buttons.py @@ -0,0 +1,402 @@ +"""AX BUTTON-interaction tests for **Time to Leave** (Electron calendar / work-hour logger). + +Every assertion here mirrors a before/after pair that was OBSERVED on the reference app +(see ``recon.md`` → ``## BUTTONS``). Two facts from recon drive the whole module: + +* ``AXPress`` is a **NO-OP** on every in-page control (the nav buttons are + ````, the +/- entry cells are ``
``). Every in-page + button is therefore driven with a real CGEvent click through + ``test_ax_common.cg_click`` (or its wrappers ``nav_month`` / ``nav_day`` / + ``switch_view`` / ``goto_current_*``). ``ax_press`` is used only where recon proved it + works: alert-sheet buttons and native window close buttons. +* nothing is hard-coded to a date: the expected month/day headers, the ``Working days`` + count and the ``On`` value are all COMPUTED from ``datetime.date.today()`` via the + shared helpers, so the suite holds on a weekday or a weekend. + +No test asserts "the button exists" or "the app did not crash" — each one asserts the +CONSEQUENCE of pressing the button. The main calendar window is visible immediately +after launch (recon ``REVEAL_STEPS``), so no reveal step is needed; the ``ax`` fixture +launches the app and hands over the ``AXHelper``. +""" + +from __future__ import annotations + +import datetime +import os +import sys +import time + +import pytest + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +import rb_testgen_kit as kit # noqa: E402 +import test_ax_common as T # noqa: E402 + + +# ── module-local (non-navigating) parsing helpers ──────────────────────────── +def _parse_month_title(title): + """``"September 2026"`` → ``(2026, 9)``; ``None`` when unparsable.""" + if not title: + return None + parts = str(title).strip().split() + if len(parts) != 2 or parts[0] not in T.MONTH_NAMES: + return None + try: + return int(parts[1]), T.MONTH_NAMES.index(parts[0]) + 1 + except ValueError: + return None + + +def _incrementor_map(ax, win): + """First value of each named date segment in a window, e.g. + ``{'Month': '08', 'Day': '03', 'Year': '2026'}`` (document order = Start Date).""" + out = {} + for e in T.walk(ax, win, 2000): + if e.role != "incrementor": + continue + nm = (e.name or "").strip() + if nm and nm not in out: + out[nm] = "" if e.value is None else str(e.value) + return out + + +def _day_number_in_band(ax, y): + """The day-number label of the calendar row whose band starts at ``y``.""" + for _x, text in T.band_labels(ax, y): + s = str(text).strip() + if s.isdigit(): + return int(s) + return None + + +# ── month-view toolbar buttons ────────────────────────────────────────────── +class TestMonthNavigationButtons: + """`Previous Month` / `Next Month` / `Go to Current Month` (help text = name).""" + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="month title becomes the previous month") + def test_previous_month_button(self, ax): + try: + assert T.ensure_month_view(ax), ( + "could not reach the Month view; buttons seen: %r" % (T.button_names(ax),)) + assert T.goto_current_month(ax), ( + "no 'Go to Current Month' button; buttons seen: %r" % (T.button_names(ax),)) + start = T.month_title(ax) + assert start == T.expected_month_title(), ( + "month title at launch/current is %r, expected %r" + % (start, T.expected_month_title())) + + assert T.nav_month(ax, "backward"), ( + "no 'Previous Month' button; buttons seen: %r" % (T.button_names(ax),)) + observed = T.month_title(ax) + expected = T.expected_month_title( + T.shifted_month(datetime.date.today(), -1)) + assert kit.rb_value(observed, expected), ( + "after 'Previous Month' the title is %r, expected %r (started at %r)" + % (observed, expected, start)) + finally: + T.goto_current_month(ax) + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="month title becomes the next month") + def test_next_month_button(self, ax): + try: + assert T.ensure_month_view(ax), ( + "could not reach the Month view; buttons seen: %r" % (T.button_names(ax),)) + assert T.goto_current_month(ax), ( + "no 'Go to Current Month' button; buttons seen: %r" % (T.button_names(ax),)) + start = T.month_title(ax) + assert start == T.expected_month_title(), ( + "month title at launch/current is %r, expected %r" + % (start, T.expected_month_title())) + + assert T.nav_month(ax, "forward"), ( + "no 'Next Month' button; buttons seen: %r" % (T.button_names(ax),)) + observed = T.month_title(ax) + expected = T.expected_month_title( + T.shifted_month(datetime.date.today(), +1)) + assert kit.rb_value(observed, expected), ( + "after 'Next Month' the title is %r, expected %r (started at %r)" + % (observed, expected, start)) + finally: + T.goto_current_month(ax) + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="back to the current month title after backward+forward") + def test_month_navigation_round_trip(self, ax): + try: + assert T.ensure_month_view(ax), ( + "could not reach the Month view; buttons seen: %r" % (T.button_names(ax),)) + assert T.goto_current_month(ax), ( + "no 'Go to Current Month' button; buttons seen: %r" % (T.button_names(ax),)) + + assert T.nav_month(ax, "backward"), "no 'Previous Month' button" + assert T.nav_month(ax, "forward"), "no 'Next Month' button" + + observed = T.month_title(ax) + expected = T.expected_month_title() + assert kit.rb_value(observed, expected), ( + "after Previous Month + Next Month the title is %r, expected the " + "current month %r" % (observed, expected)) + finally: + T.goto_current_month(ax) + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="current month title restored after navigating two months forward") + def test_go_to_current_month_button(self, ax): + try: + assert T.ensure_month_view(ax), ( + "could not reach the Month view; buttons seen: %r" % (T.button_names(ax),)) + assert T.nav_month(ax, "forward"), "no 'Next Month' button (click 1)" + assert T.nav_month(ax, "forward"), "no 'Next Month' button (click 2)" + drifted = T.month_title(ax) + assert drifted != T.expected_month_title(), ( + "two 'Next Month' clicks left the title at %r — it never moved off the " + "current month %r" % (drifted, T.expected_month_title())) + + assert T.goto_current_month(ax), "no 'Go to Current Month' button" + observed = T.month_title(ax) + expected = T.expected_month_title() + assert kit.rb_value(observed, expected), ( + "after 'Go to Current Month' the title is %r, expected %r (was %r)" + % (observed, expected, drifted)) + finally: + T.goto_current_month(ax) + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="Working days footer equals the Mon-Fri count of the newly shown month") + def test_month_nav_updates_working_days(self, ax): + try: + assert T.ensure_month_view(ax), ( + "could not reach the Month view; buttons seen: %r" % (T.button_names(ax),)) + assert T.nav_month(ax, "forward"), "no 'Next Month' button" + + title = T.month_title(ax) + ym = _parse_month_title(title) + assert ym is not None, "month title after 'Next Month' is unparsable: %r" % (title,) + year, month = ym + + observed = T.footer_value(ax, "Working days") + expected = str(T.weekdays_in_month(year, month)) + assert kit.rb_value(observed, expected), ( + "'Working days' shows %r for %r, expected %r (Mon-Fri days in %d-%02d)" + % (observed, title, expected, year, month)) + finally: + T.goto_current_month(ax) + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="'On' equals the month length for a month that is not the current one") + def test_month_nav_updates_on_value(self, ax): + try: + assert T.ensure_month_view(ax), ( + "could not reach the Month view; buttons seen: %r" % (T.button_names(ax),)) + assert T.nav_month(ax, "forward"), "no 'Next Month' button" + + title = T.month_title(ax) + ym = _parse_month_title(title) + assert ym is not None, "month title after 'Next Month' is unparsable: %r" % (title,) + year, month = ym + assert title != T.expected_month_title(), ( + "'Next Month' did not leave the current month (title %r)" % (title,)) + + observed = T.footer_value(ax, "On") + expected = str(T.month_length(year, month)) + assert kit.rb_value(observed, expected), ( + "'On' shows %r for the non-current month %r, expected the month length %r" + % (observed, title, expected)) + finally: + T.goto_current_month(ax) + + +# ── Switch View + the day-view toolbar buttons ────────────────────────────── +class TestDayViewButtons: + """`Switch View` crosses into the Day view, where the month arrows are replaced + by `Previous Day` / `Next Day` / `Go to Current Day`.""" + + @pytest.mark.rb(depth=1, jump_kind="reach", + expect="Day view: 'Previous Day' appears and 'Previous Month' disappears") + def test_switch_view_button_enters_day_view(self, ax): + try: + assert T.ensure_month_view(ax), ( + "could not reach the Month view; buttons seen: %r" % (T.button_names(ax),)) + before = kit.rb_showing(ax) + + assert T.rb_enter_day_view(ax), ( + "'Switch View' did not enter the Day view; buttons seen: %r" + % (T.button_names(ax),)) + after = kit.rb_showing(ax) + + T.screenshot_assert( + "buttons_switch_view_day_view", + "Time to Leave in DAY view after pressing the Switch View button: a " + "small ~500x500 window whose header shows one full date (e.g. " + "'Sunday, August 9, 2026') between a '<' Previous Day arrow and a '>' " + "Next Day arrow plus a calendar 'Go to Current Day' icon; below it " + "either the text 'Not a working day' or Entry #1/Entry #2 time rows, " + "then a MONTH BALANCE 00:00 / OVERALL BALANCE 00:00 strip and a wide " + "dark 'Punch time' bar with a fingerprint icon at the bottom. The month " + "calendar table with Day/Total columns and the 'August 2026'-style " + "month title are GONE.", + T.results_dir()) + + assert kit.rb_reach(before, after, + target="Previous Day", source="Previous Month"), ( + "Switch View did not cross into the Day view: 'Previous Day' did not " + "appear and/or 'Previous Month' did not disappear; buttons now: %r" + % (T.button_names(ax),)) + finally: + T.ensure_month_view(ax) + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="day header becomes yesterday's date") + def test_previous_day_button(self, ax): + try: + assert T.rb_enter_day_view(ax), ( + "could not reach the Day view; buttons seen: %r" % (T.button_names(ax),)) + start = T.day_title(ax) + assert start == T.expected_day_title(), ( + "day header on entering the Day view is %r, expected today %r" + % (start, T.expected_day_title())) + + assert T.nav_day(ax, "backward"), ( + "no 'Previous Day' button; buttons seen: %r" % (T.button_names(ax),)) + observed = T.day_title(ax) + expected = T.expected_day_title( + datetime.date.today() - datetime.timedelta(days=1)) + assert kit.rb_value(observed, expected), ( + "after 'Previous Day' the header is %r, expected yesterday %r " + "(started at %r)" % (observed, expected, start)) + finally: + T.goto_current_day(ax) + T.ensure_month_view(ax) + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="day header back to today after backward+forward") + def test_next_day_button_round_trip(self, ax): + try: + assert T.rb_enter_day_view(ax), ( + "could not reach the Day view; buttons seen: %r" % (T.button_names(ax),)) + assert T.nav_day(ax, "backward"), "no 'Previous Day' button" + assert T.nav_day(ax, "forward"), ( + "no 'Next Day' button; buttons seen: %r" % (T.button_names(ax),)) + + observed = T.day_title(ax) + expected = T.expected_day_title() + assert kit.rb_value(observed, expected), ( + "after Previous Day + Next Day the header is %r, expected today %r" + % (observed, expected)) + finally: + T.goto_current_day(ax) + T.ensure_month_view(ax) + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="day header returns to today after two backward steps") + def test_go_to_current_day_button(self, ax): + try: + assert T.rb_enter_day_view(ax), ( + "could not reach the Day view; buttons seen: %r" % (T.button_names(ax),)) + assert T.nav_day(ax, "backward"), "no 'Previous Day' button (click 1)" + assert T.nav_day(ax, "backward"), "no 'Previous Day' button (click 2)" + drifted = T.day_title(ax) + expected = T.expected_day_title() + assert drifted != expected, ( + "two 'Previous Day' clicks left the header at today (%r) — it never moved" + % (drifted,)) + + assert T.goto_current_day(ax), ( + "no 'Go to Current Day' button; buttons seen: %r" % (T.button_names(ax),)) + observed = T.day_title(ax) + assert kit.rb_value(observed, expected), ( + "after 'Go to Current Day' the header is %r, expected today %r (was %r)" + % (observed, expected, drifted)) + finally: + T.ensure_month_view(ax) + + +# ── per-row entry buttons ("+" / "-") ─────────────────────────────────────── +class TestEntryButtons: + """The `+` / `-` cells of a working-day row (AXHelp 'Add entry' / 'Remove entry').""" + + @pytest.mark.rb(depth=0, jump_kind="transition", + expect="'+' adds two time fields and '-' removes them again") + def test_add_and_remove_entry_buttons(self, ax): + extra_pair = False + try: + assert T.ensure_month_view(ax), ( + "could not reach the Month view; buttons seen: %r" % (T.button_names(ax),)) + + n0 = T.count_timefields(ax) + assert n0 >= 40, ( + "only %d time fields in the month view — the calendar table did not " + "render" % n0) + + plus = T.find_by_help(ax, "Add entry", T.main_window(ax)) + assert plus, "no cell with AXHelp 'Add entry' in the month view" + assert T.cg_click(plus[0]), "could not click the first 'Add entry' (+) cell" + extra_pair = True + time.sleep(1.4) + + n1 = T.count_timefields(ax) + assert kit.rb_flip(n0, n1), ( + "the '+' (Add entry) cell changed nothing: time-field count stayed at %d" + % n0) + assert n1 == n0 + 2, ( + "'+' produced %d time fields, expected %d (= %d + 2 for one extra entry " + "pair)" % (n1, n0 + 2, n0)) + + minus = T.find_by_help(ax, "Remove entry", T.main_window(ax)) + assert minus, "no cell with AXHelp 'Remove entry' in the month view" + assert T.cg_click(minus[0]), "could not click the first 'Remove entry' (-) cell" + time.sleep(1.4) + + n2 = T.count_timefields(ax) + if n2 == n0: + extra_pair = False + assert n2 == n0, ( + "'-' left %d time fields, expected the original %d (counts: n0=%d, " + "n1=%d, n2=%d)" % (n2, n0, n0, n1, n2)) + finally: + if extra_pair: + back = T.find_by_help(ax, "Remove entry", T.main_window(ax)) + if back: + T.cg_click(back[0]) + time.sleep(1.4) + T.ensure_month_view(ax) + + +# ── buttons that open a secondary window / an alert ───────────────────────── + + + + + + + +class TestPunchButton: + """`Punch time` is enabled only for the current month on a working day, so the + date-safe assertion is: off the current month it is ALWAYS disabled.""" + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="Punch time button is disabled when a non-current month is displayed") + def test_punch_button_disabled_off_current_month(self, ax): + try: + assert T.ensure_month_view(ax), ( + "could not reach the Month view; buttons seen: %r" % (T.button_names(ax),)) + assert T.nav_month(ax, "forward"), "no 'Next Month' button" + + title = T.month_title(ax) + assert title != T.expected_month_title(), ( + "'Next Month' did not leave the current month (title %r)" % (title,)) + + btn = T.punch_button(ax) + assert btn is not None, ( + "no 'Punch time' button in the month view; buttons seen: %r" + % (T.button_names(ax),)) + + observed = str(bool(btn.enabled)) + assert kit.rb_value(observed, "False"), ( + "'Punch time' enabled == %s while %r (a non-current month) is displayed; " + "expected False" % (observed, title)) + finally: + T.goto_current_month(ax) diff --git a/macos/ttlapp-time-to-leave/tests/test_ax_common.py b/macos/ttlapp-time-to-leave/tests/test_ax_common.py new file mode 100644 index 0000000000000000000000000000000000000000..91f047f05217256159922765e65a21d98303c9ae --- /dev/null +++ b/macos/ttlapp-time-to-leave/tests/test_ax_common.py @@ -0,0 +1,993 @@ +"""Shared AX helpers for the Time to Leave test suite. + +NOT a test module — it contains no ``test_*`` functions, only helpers that every +``test_ax_*.py`` imports. It is named ``test_ax_common.py`` so it is deployed +alongside the real test modules; the runner reports it as a 0-test module. + +Every helper here was verified against the running official app. Two facts drive +the design: + +* The app is Chromium-backed, so ``AXPress`` is a **no-op** on in-page controls + (```` buttons, bootstrap tabs, toggle switches). In-page + controls must be driven with a real CGEvent click at the element's centre + (:func:`cg_click`). Native surfaces (menu bar items, ``NSAlert`` sheet + buttons, window close buttons) *do* respond to ``AXPress``. +* ``AXHelper`` element ids are ``hash(ref)`` and can collide, so every scoped + lookup here walks ``el.ref`` directly instead of passing ``root_id``. +""" + +from __future__ import annotations + +import datetime +import json +import os +import re +import subprocess +import time + +import ApplicationServices as _AS +import Quartz + +# ── key codes (CGEvent virtual key codes) ─────────────────────────────────── +KC_DELETE = 51 +KC_ESCAPE = 53 +KC_RETURN = 36 +KC_TAB = 48 +KC_COMMA = 43 +KC_LEFT = 123 +KC_RIGHT = 124 + +MONTH_NAMES = [ + "January", "February", "March", "April", "May", "June", + "July", "August", "September", "October", "November", "December", +] +WEEKDAY_ABBR = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] + +MONTH_TITLE_RE = re.compile(r"^(%s)\s+\d{4}$" % "|".join(MONTH_NAMES)) +DAY_TITLE_RE = re.compile(r"^[A-Z][a-z]+,\s+[A-Z][a-z]+\s+\d{1,2},\s+\d{4}$") +HHMM_RE = re.compile(r"^-?\d{1,3}:\d{2}$") + +# Menu-item label keywords. macOS renames a "Preferences…" item to "Settings…", +# so the preferences entry must be matched by keyword, never by exact label. +PREFS_KEYWORDS = ("setting", "preference") +WAIVER_KEYWORDS = ("waiver", "waive") +QUIT_KEYWORDS = ("exit", "quit") + + +# ── low level: geometry ───────────────────────────────────────────────────── +def frame(el): + """(x, y, w, h) in screen pixels for an AXElement, or None.""" + if el is None: + return None + ref = getattr(el, "ref", el) + e1, pos = _AS.AXUIElementCopyAttributeValue(ref, "AXPosition", None) + e2, size = _AS.AXUIElementCopyAttributeValue(ref, "AXSize", None) + if e1 or e2 or pos is None or size is None: + return None + ok1, p = _AS.AXValueGetValue(pos, _AS.kAXValueCGPointType, None) + ok2, s = _AS.AXValueGetValue(size, _AS.kAXValueCGSizeType, None) + if not ok1 or not ok2: + return None + return (int(p.x), int(p.y), int(s.width), int(s.height)) + + +def center(el): + f = frame(el) + if f is None: + return None + return (f[0] + f[2] / 2.0, f[1] + f[3] / 2.0) + + +def attr(el, name, default=None): + ref = getattr(el, "ref", el) + try: + err, val = _AS.AXUIElementCopyAttributeValue(ref, name, None) + return val if err == 0 else default + except Exception: + return default + + +def help_text(el): + v = attr(el, "AXHelp") + return None if v is None else str(v) + + +def subrole(el): + v = attr(el, "AXSubrole") + return None if v is None else str(v) + + +def is_focused(el): + return bool(attr(el, "AXFocused", False)) + + +# ── low level: input ──────────────────────────────────────────────────────── +def click_at(x, y, dwell=0.45): + pt = Quartz.CGPointMake(x, y) + down = Quartz.CGEventCreateMouseEvent( + None, Quartz.kCGEventLeftMouseDown, pt, Quartz.kCGMouseButtonLeft) + up = Quartz.CGEventCreateMouseEvent( + None, Quartz.kCGEventLeftMouseUp, pt, Quartz.kCGMouseButtonLeft) + Quartz.CGEventSetFlags(down, 0) # a latched Cmd would turn this into Cmd-click + Quartz.CGEventSetFlags(up, 0) + Quartz.CGEventPost(Quartz.kCGHIDEventTap, down) + time.sleep(0.05) + Quartz.CGEventPost(Quartz.kCGHIDEventTap, up) + time.sleep(dwell) + + +def cg_click(el, dwell=0.45): + """Real mouse click at the element's centre. The ONLY thing that drives + in-page (Chromium) controls in this app.""" + c = center(el) + if c is None: + return False + click_at(c[0], c[1], dwell) + return True + + +def ax_press(el): + """AXPress — works for native menu items / sheet buttons / window buttons.""" + if el is None: + return False + try: + return _AS.AXUIElementPerformAction(getattr(el, "ref", el), "AXPress") == 0 + except Exception: + return False + + +def scroll_into_view(el): + """AXScrollToVisible. Needed for controls clipped by a scrolling window + (e.g. the Preferences "Reset" button, whose frame height is 1 until scrolled).""" + if el is None: + return False + try: + return _AS.AXUIElementPerformAction( + getattr(el, "ref", el), "AXScrollToVisible") == 0 + except Exception: + return False + + +def send_key(keycode, modifiers=None): + src = Quartz.CGEventSourceCreate(Quartz.kCGEventSourceStateHIDSystemState) + down = Quartz.CGEventCreateKeyboardEvent(src, keycode, True) + up = Quartz.CGEventCreateKeyboardEvent(src, keycode, False) + flags = 0 + for m in (modifiers or []): + flags |= { + "cmd": Quartz.kCGEventFlagMaskCommand, + "shift": Quartz.kCGEventFlagMaskShift, + "alt": Quartz.kCGEventFlagMaskAlternate, + "ctrl": Quartz.kCGEventFlagMaskControl, + }.get(m, 0) + Quartz.CGEventSetFlags(down, flags) + # The UP event must carry NO flags: posting an up whose flags still hold e.g. Command + # leaves the session flag state latched, and every later unflagged synthetic key event + # inherits it (turning plain typing into Cmd+). + Quartz.CGEventSetFlags(up, 0) + Quartz.CGEventPost(Quartz.kCGHIDEventTap, down) + time.sleep(0.03) + Quartz.CGEventPost(Quartz.kCGHIDEventTap, up) + time.sleep(0.25) + + +MODIFIER_KEYCODES = (55, 54, 56, 60, 58, 61, 59, 62) # cmd L/R, shift L/R, opt L/R, ctrl L/R + + +def modifier_flags(): + """The session-wide CGEvent modifier state (what unflagged synthetic events inherit).""" + return Quartz.CGEventSourceFlagsState( + Quartz.kCGEventSourceStateCombinedSessionState) + + +def clear_modifiers(): + """Release any modifier that is stuck DOWN in the session's CGEvent flag state. + + Why this is needed: posting a key event whose flags carry e.g. Command leaves the + session flag state carrying Command, and nothing clears it afterwards. Synthetic + keyboard events created without explicit flags INHERIT that state, so every later + ``type_str`` call silently turns into Cmd+ and types nothing at all -- mouse + clicks keep working, which makes it look like the typing target is wrong rather than + like a stuck modifier. Measured on this app: flags 0x20100000 (Command latched) -> + time field reads back 0.0/0.0/0.0; after this call -> 8.0/0.0/1.0 for the same input. + """ + src = Quartz.CGEventSourceCreate(Quartz.kCGEventSourceStateHIDSystemState) + for kc in MODIFIER_KEYCODES: + up = Quartz.CGEventCreateKeyboardEvent(src, kc, False) + Quartz.CGEventSetFlags(up, 0) + Quartz.CGEventPost(Quartz.kCGHIDEventTap, up) + time.sleep(0.015) + time.sleep(0.15) + return modifier_flags() + + +def type_str(s, delay=0.06): + """Type unicode characters into whatever currently has DOM focus.""" + clear_modifiers() + for ch in s: + for down in (True, False): + ev = Quartz.CGEventCreateKeyboardEvent(None, 0, down) + Quartz.CGEventKeyboardSetUnicodeString(ev, len(ch), ch) + Quartz.CGEventSetFlags(ev, 0) # never inherit a latched modifier + Quartz.CGEventPost(Quartz.kCGHIDEventTap, ev) + time.sleep(0.012) + time.sleep(delay) + + +# ── tree walking (ref-based, collision-free) ──────────────────────────────── +def walk(ax, root_el=None, limit=4000): + """Yield every AXElement under root_el (app root when None).""" + root = getattr(root_el, "ref", None) if root_el is not None else ax._app_ref + if root is None: + return [] + out = [] + budget = [limit] + + def rec(ref): + if budget[0] <= 0: + return + budget[0] -= 1 + try: + out.append(ax._ref_to_element(ref)) + except Exception: + return + err, kids = _AS.AXUIElementCopyAttributeValue(ref, "AXChildren", None) + if err == 0 and kids: + for k in kids: + rec(k) + + rec(root) + return out + + +def find_all(ax, root_el=None, role=None, name=None, value=None, limit=4000): + res = [] + for el in walk(ax, root_el, limit): + if role is not None and el.role != role: + continue + if name is not None and (el.name or "") != name: + continue + if value is not None and (el.value or "") != value: + continue + res.append(el) + return res + + +def find_by_help(ax, text, root_el=None, limit=4000): + """Elements whose AXHelp equals `text`, sorted top-to-bottom, left-to-right. + + The app puts its HTML ``title=`` tooltips on AXHelp, so this is the semantic + locator for the +/- entry cells, the entry-scroll arrows, the waiver trigger + cell and the footer balance cells.""" + out = [] + for el in walk(ax, root_el, limit): + h = help_text(el) + if h is not None and h == text: + f = frame(el) + if f is not None: + out.append((f[1], f[0], el)) + out.sort(key=lambda t: (t[0], t[1])) + return [t[2] for t in out] + + +def sorted_by_position(els): + dec = [] + for el in els: + f = frame(el) + if f is not None: + dec.append((f[1], f[0], el)) + dec.sort(key=lambda t: (t[0], t[1])) + return [t[2] for t in dec] + + +def dedup_by_frame(els): + """The AX tree exposes the same DOM button several times (row / column / cell + wrappers). Collapse duplicates by (role, name, frame).""" + seen, out = set(), [] + for el in els: + key = (el.role, el.name, frame(el)) + if key in seen: + continue + seen.add(key) + out.append(el) + return out + + +# ── windows / sheets ──────────────────────────────────────────────────────── +def windows(ax): + return ax.find(role="window", max_results=10, max_depth=4) + + +def main_window(ax): + """The calendar window (title is exactly the app name).""" + ws = windows(ax) + for w in ws: + n = w.name or "" + if n and "-" not in n: + return w + return ws[0] if ws else None + + +def child_window(ax, name_contains): + low = name_contains.lower() + for w in windows(ax): + if low in (w.name or "").lower(): + return w + return None + + +def wait_window(ax, name_contains, timeout=8.0): + end = time.time() + timeout + while time.time() < end: + w = child_window(ax, name_contains) + if w is not None: + return w + time.sleep(0.3) + return None + + +def sheets(ax): + return ax.find(role="sheet", max_results=6, max_depth=8) + + +def wait_sheet(ax, timeout=6.0): + end = time.time() + timeout + while time.time() < end: + s = sheets(ax) + if s: + return s[0] + time.sleep(0.25) + return None + + +def sheet_buttons(ax, sheet_el): + return [e for e in walk(ax, sheet_el, 200) if e.role == "button"] + + +def dismiss_sheet(ax, prefer=("No", "OK", "Cancel", "Dismiss")): + """Close the frontmost alert sheet with a non-destructive button.""" + s = sheets(ax) + if not s: + return True + btns = sheet_buttons(ax, s[0]) + for want in prefer: + for b in btns: + if (b.name or "").strip().lower() == want.lower(): + ax_press(b) + time.sleep(0.9) + return not sheets(ax) + send_key(KC_ESCAPE) + time.sleep(0.7) + return not sheets(ax) + + +def close_child(ax, name_contains): + """Press the native close button of a secondary window.""" + w = child_window(ax, name_contains) + if w is None: + return True + for b in walk(ax, w, 400): + if b.role == "button" and subrole(b) == "AXCloseButton": + ax_press(b) + time.sleep(1.2) + return child_window(ax, name_contains) is None + return False + + +def dismiss_extras(ax): + """Best-effort teardown: close alert sheets, file panels and child windows.""" + for _ in range(3): + if sheets(ax): + dismiss_sheet(ax) + continue + break + for title in ("database", "Preferences", "Waiver"): + w = child_window(ax, title) + if w is None: + continue + if "database" in (w.name or "").lower(): + send_key(KC_ESCAPE) + time.sleep(0.8) + else: + close_child(ax, title) + + +# ── text helpers ──────────────────────────────────────────────────────────── +def label_elements(ax, root_el=None, limit=4000): + return [e for e in walk(ax, root_el, limit) if e.role == "label"] + + +def label_values(ax, root_el=None, limit=4000): + out = [] + for e in label_elements(ax, root_el, limit): + v = e.value if e.value not in (None, "") else e.name + if v: + out.append(str(v)) + return out + + +def window_label_values(ax, win=None): + return label_values(ax, win if win is not None else main_window(ax)) + + +def find_label(ax, value, root_el=None): + for e in label_elements(ax, root_el): + if str(e.value or e.name or "").strip() == value: + return e + return None + + +def band_labels(ax, y, tol=14, root_el=None): + """(x, text) of every label whose top edge is within `tol` px of `y`.""" + out = [] + for e in label_elements(ax, root_el): + f = frame(e) + if f is None or abs(f[1] - y) > tol: + continue + v = str(e.value or e.name or "") + if v: + out.append((f[0], v)) + out.sort() + return out + + +def band_times(ax, y, tol=14, root_el=None): + """Left-to-right HH:MM values in a row band (lunch interval, then day total).""" + return [(x, v) for x, v in band_labels(ax, y, tol, root_el) if HHMM_RE.match(v.strip())] + + +# ── month / day view basics ───────────────────────────────────────────────── +def month_title(ax): + for v in window_label_values(ax): + if MONTH_TITLE_RE.match(v.strip()): + return v.strip() + return None + + +def day_title(ax): + for v in window_label_values(ax): + if DAY_TITLE_RE.match(v.strip()): + return v.strip() + return None + + +def expected_month_title(d=None): + d = d or datetime.date.today() + return "%s %d" % (MONTH_NAMES[d.month - 1], d.year) + + +def expected_day_title(d=None): + d = d or datetime.date.today() + return "%s, %s %d, %d" % ( + d.strftime("%A"), MONTH_NAMES[d.month - 1], d.day, d.year) + + +def month_length(year, month): + if month == 12: + return 31 + return (datetime.date(year, month + 1, 1) - datetime.timedelta(days=1)).day + + +def weekdays_in_month(year, month): + """Mon–Fri day count — the app's default set of working days.""" + n = 0 + for day in range(1, month_length(year, month) + 1): + if datetime.date(year, month, day).weekday() < 5: + n += 1 + return n + + +def shifted_month(d, delta): + m = d.month - 1 + delta + return datetime.date(d.year + m // 12, m % 12 + 1, 1) + + +def buttons(ax, name=None, win=None): + root = win if win is not None else main_window(ax) + els = [e for e in walk(ax, root, 4000) if e.role == "button"] + if name is not None: + els = [e for e in els if (e.name or "") == name] + return dedup_by_frame(els) + + +def button(ax, name, win=None): + b = buttons(ax, name, win) + return b[0] if b else None + + +def button_names(ax, win=None): + return [e.name for e in buttons(ax, None, win) if e.name] + + +def view_mode(ax): + names = set(button_names(ax)) + if "Previous Month" in names or "Go to Current Month" in names: + return "month" + if "Previous Day" in names or "Go to Current Day" in names: + return "day" + return None + + +def switch_view(ax, settle=1.6): + b = button(ax, "Switch View") + if b is None: + return False + cg_click(b) + time.sleep(settle) + return True + + +def rb_enter_day_view(ax): + """Cross into the Day-view surface (month nav buttons are replaced by day ones).""" + if view_mode(ax) == "day": + return True + switch_view(ax) + return view_mode(ax) == "day" + + +def rb_enter_month_view(ax): + if view_mode(ax) == "month": + return True + switch_view(ax) + return view_mode(ax) == "month" + + +def ensure_month_view(ax): + """Restore the default (Month) view. The view is a PERSISTED preference, so + any test that switches views must call this again at the end.""" + for _ in range(2): + if view_mode(ax) == "month": + return True + switch_view(ax) + return view_mode(ax) == "month" + + +def nav_month(ax, direction="forward", settle=1.3): + b = button(ax, "Next Month" if direction == "forward" else "Previous Month") + if b is None: + return False + cg_click(b) + time.sleep(settle) + return True + + +def goto_current_month(ax, settle=1.3): + b = button(ax, "Go to Current Month") + if b is None: + return False + cg_click(b) + time.sleep(settle) + return True + + +def nav_day(ax, direction="forward", settle=1.2): + b = button(ax, "Next Day" if direction == "forward" else "Previous Day") + if b is None: + return False + cg_click(b) + time.sleep(settle) + return True + + +def goto_current_day(ax, settle=1.2): + b = button(ax, "Go to Current Day") + if b is None: + return False + cg_click(b) + time.sleep(settle) + return True + + +def footer_value(ax, label_text): + """Value shown right of a footer caption ("On", "Working days", ...).""" + vals = window_label_values(ax) + for i, v in enumerate(vals): + if v.strip() == label_text: + for nxt in vals[i + 1:i + 3]: + s = nxt.strip() + if s and s != label_text: + return s + return None + + +def balance_fields(ax): + """The two read-only balance inputs (Month Balance, Overall Balance).""" + return [e for e in walk(ax, main_window(ax), 4000) + if e.role == "text_field" and HHMM_RE.match(str(e.value or ""))] + + +def punch_button(ax): + return button(ax, "Punch time") + + +def day_number_labels(ax): + out = set() + for v in window_label_values(ax): + s = v.strip() + if s.isdigit() and 1 <= int(s) <= 31: + out.add(int(s)) + return out + + +def weekday_label_count(ax): + vals = [v.strip() for v in window_label_values(ax)] + return sum(1 for v in vals if v in WEEKDAY_ABBR) + + +# ── time entry (month view) ───────────────────────────────────────────────── +def timefields(ax, win=None): + root = win if win is not None else main_window(ax) + return sorted_by_position( + dedup_by_frame([e for e in walk(ax, root, 6000) if e.role == "timefield"])) + + +def count_timefields(ax): + return len(timefields(ax)) + + +def hours_incrementor(ax, tf): + """The Hours sub-field of a time input. Clicking the time field's centre can + land on Minutes, so always click this to start typing.""" + incs = [e for e in walk(ax, tf, 40) if e.role == "incrementor"] + for e in incs: + if (e.name or "") == "Hours": + return e + return incs[0] if incs else None + + +def time_parts(ax, tf): + """[(segment name, value)] for one time field, e.g. [('Hours','08'), ...].""" + return [(e.name, e.value) for e in walk(ax, tf, 40) if e.role == "incrementor"] + + +def enter_time(ax, index, text, settle=0.45): + """Type `text` (e.g. "0800AM") into the Nth time field of the month view.""" + tfs = timefields(ax) + if index >= len(tfs): + return False + h = hours_incrementor(ax, tfs[index]) + if h is None: + return False + cg_click(h, dwell=0.35) + type_str(text) + time.sleep(settle) + return True + + +def enter_times(ax, texts, start=0): + """把 `texts` 依次打进从 `start` 开始的连续时间字段;全部成功才返回 True。 + + 单数版 `enter_time()` 和复数版 `clear_times()` 都在,偏偏这个复数版从来没写过 —— 而 + computation lane 的每一条核心用例都调它(`T.enter_times(ax, FULL_DAY)`)。于是"输入上下班 + 时间 → 算出午休时长 / 当日总计 / Month Balance"这一整块核心在参考 app 上必然 AttributeError, + 被剪枝整批删掉,只剩下日历天数和"空日历余额 00:00"那种零态断言。 + """ + for i, text in enumerate(texts): + if not enter_time(ax, start + i, text): + return False + return True + + +def clear_time(ax, index, settle=0.3): + tfs = timefields(ax) + if index >= len(tfs): + return False + h = hours_incrementor(ax, tfs[index]) + if h is None: + return False + cg_click(h, dwell=0.3) + send_key(KC_DELETE) + time.sleep(settle) + return True + + +def clear_times(ax, count, start=0): + """清掉从 `start` 开始的连续 count 个时间字段。 + + `start` 是补的:第二行那条用例调的是 `clear_times(ax, 4, start=4)`(第二个工作日行的 + 四个字段从索引 4 起),而原签名只有 (ax, count) —— 于是 teardown 抛 TypeError, + 整条用例失败。默认 0,老调用不受影响。 + """ + for i in range(count): + clear_time(ax, start + i) + + +def first_row_y(ax): + tfs = timefields(ax) + if not tfs: + return None + f = frame(tfs[0]) + return None if f is None else f[1] + + +# ── menus ─────────────────────────────────────────────────────────────────── +def menu_bars(ax): + return ax.find(role="menu_bar", max_results=6, max_depth=4) + + +def app_menu_bar(ax): + """The application menu bar (the one carrying named top-level menus).""" + best, best_n = None, -1 + for mb in menu_bars(ax): + items = [e for e in walk(ax, mb, 60) + if e.role == "menu_bar_item" and (e.name or "")] + if len(items) > best_n: + best, best_n = mb, len(items) + return best + + +def status_menu_bar(ax): + """The tray / status-item menu bar (a single unnamed item).""" + for mb in menu_bars(ax): + items = [e for e in walk(ax, mb, 60) if e.role == "menu_bar_item"] + if items and not any((i.name or "") for i in items): + return mb + return None + + +def app_menu_titles(ax, skip_system=True): + mb = app_menu_bar(ax) + if mb is None: + return [] + names = [e.name for e in walk(ax, mb, 60) + if e.role == "menu_bar_item" and (e.name or "")] + if skip_system: + names = [n for n in names if n != "Apple"] + return names + + +def top_menu(ax, title): + mb = app_menu_bar(ax) + if mb is None: + return None + for e in walk(ax, mb, 60): + if e.role == "menu_bar_item" and (e.name or "") == title: + return e + return None + + +def menu_items(ax, menu_el, limit=400): + """Direct menu items of a menu-bar item / menu item (one level down).""" + if menu_el is None: + return [] + out = [] + err, kids = _AS.AXUIElementCopyAttributeValue( + getattr(menu_el, "ref", menu_el), "AXChildren", None) + if err or not kids: + return out + for menu in kids: + err2, items = _AS.AXUIElementCopyAttributeValue(menu, "AXChildren", None) + if err2 or not items: + continue + for it in items: + el = ax._ref_to_element(it) + if el.role == "menu_item": + out.append(el) + if len(out) >= limit: + break + return out + + +def menu_item_names(ax, menu_title): + return [i.name for i in menu_items(ax, top_menu(ax, menu_title)) if i.name] + + +def menu_item(ax, path): + """Menu item by exact path, e.g. ``menu_item(ax, "Help>About")``.""" + parts = path.split(">") + node = top_menu(ax, parts[0]) + for want in parts[1:]: + node = next((i for i in menu_items(ax, node) if (i.name or "") == want), None) + if node is None: + return None + return node + + +def menu_item_by_keywords(ax, menu_title, keywords): + for it in menu_items(ax, top_menu(ax, menu_title)): + low = (it.name or "").lower() + if any(k in low for k in keywords): + return it + return None + + +def menu_cmd_char(el): + v = attr(el, "AXMenuItemCmdChar") + return None if v is None else str(v) + + +def tray_menu_items(ax): + mb = status_menu_bar(ax) + if mb is None: + return [] + items = [e for e in walk(ax, mb, 60) if e.role == "menu_bar_item"] + return menu_items(ax, items[0]) if items else [] + + +def rb_reach_menu_item(ax, path, settle=2.2): + """Activate a menu item — the surface crossing used by the menu tests.""" + it = menu_item(ax, path) + if it is None: + return False + ok = ax_press(it) + time.sleep(settle) + return ok + + +def rb_reach_menu_keyword(ax, menu_title, keywords, settle=2.2): + it = menu_item_by_keywords(ax, menu_title, keywords) + if it is None: + return False + ok = ax_press(it) + time.sleep(settle) + return ok + + +# ── secondary windows ─────────────────────────────────────────────────────── +def rb_enter_prefs(ax): + """Open the Preferences window (Edit ▸ Settings…) and return it.""" + if child_window(ax, "Preferences") is not None: + return child_window(ax, "Preferences") + rb_reach_menu_keyword(ax, "Edit", PREFS_KEYWORDS, settle=1.0) + return wait_window(ax, "Preferences", timeout=8) + + +def rb_enter_waiver(ax): + """Open the Workday Waiver Manager window from the app menu and return it.""" + if child_window(ax, "Waiver") is not None: + return child_window(ax, "Waiver") + titles = [t for t in app_menu_titles(ax)] + for t in titles: + if rb_reach_menu_keyword(ax, t, WAIVER_KEYWORDS, settle=1.0): + w = wait_window(ax, "Waiver", timeout=8) + if w is not None: + return w + return None + + +def waiver_trigger_cells(ax): + """Weekday cells of working-day rows (AXHelp "Add a waiver for this day").""" + return find_by_help(ax, "Add a waiver for this day", main_window(ax)) + + +def rb_enter_waiver_via_day(ax, row=0): + """Click a working-day weekday cell — opens the waiver manager for THAT day.""" + cells = waiver_trigger_cells(ax) + if row >= len(cells): + return None + cg_click(cells[row]) + return wait_window(ax, "Waiver", timeout=8) + + +def waiver_tabs(ax, win=None): + w = win if win is not None else child_window(ax, "Waiver") + return [e for e in walk(ax, w, 800) if e.role == "radio"] + + +def rb_enter_holiday_tab(ax, win=None): + """Select the Holiday tab inside the waiver manager (a second surface).""" + w = win if win is not None else child_window(ax, "Waiver") + for t in waiver_tabs(ax, w): + if (t.name or "").lower().startswith("holiday"): + cg_click(t) + time.sleep(1.6) + return True + return False + + +def prefs_checkbox_for(ax, label_text, win=None): + """The toggle switch on the same row as `label_text` in Preferences. + + The ```` is zero-width and its checked state is NOT + exposed (AXValue is always ""), so tests must click the switch and assert a + CONSEQUENCE. Clicking uses the checkbox's parent (the visible switch).""" + w = win if win is not None else child_window(ax, "Preferences") + lab = None + for e in label_elements(ax, w): + if str(e.value or e.name or "").strip() == label_text: + lab = e + break + if lab is None: + return None + ly = frame(lab) + if ly is None: + return None + best, best_d = None, 99 + for cb in [e for e in walk(ax, w, 4000) if e.role == "checkbox"]: + f = frame(cb) + if f is None: + continue + d = abs(f[1] - ly[1]) + if d <= 12 and d < best_d: + best, best_d = cb, d + return best + + +def click_switch(ax, checkbox_el, settle=1.2): + """Click the visible slider of a Preferences toggle (the checkbox's parent).""" + if checkbox_el is None: + return False + parent = attr(checkbox_el, "AXParent") + target = checkbox_el if parent is None else type(checkbox_el)( + id="", role="group", name="", value="", enabled=True, actions=[], ref=parent) + f = frame(target) + if f is None or f[2] <= 0: + f = frame(checkbox_el) + if f is None: + return False + click_at(f[0] + max(f[2], 6) / 2.0, f[1] + f[3] / 2.0) + time.sleep(settle) + return True + + +def prefs_text_fields(ax, win=None): + w = win if win is not None else child_window(ax, "Preferences") + return dedup_by_frame([e for e in walk(ax, w, 4000) if e.role == "text_field"]) + + +def popups(ax, win=None): + w = win if win is not None else main_window(ax) + return dedup_by_frame([e for e in walk(ax, w, 4000) if e.role == "popup"]) + + +def popup_values(ax, win=None): + return [str(p.value) for p in popups(ax, win) if p.value not in (None, "")] + + +# ── screenshots ───────────────────────────────────────────────────────────── +def results_dir(): + return os.environ.get( + "RESULTS_DIR", os.path.dirname(os.path.abspath(__file__))) + + +def screenshot_assert(test_name, description, base_dir=None): + """Capture the screen and record what a VLM judge should see.""" + base = base_dir or results_dir() + 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, "%s.png" % test_name) + try: + subprocess.run(["screencapture", "-x", ss_path], timeout=8) + except Exception: + pass + af = os.path.join(ss_dir, "assertions.json") + data = {} + if os.path.exists(af): + try: + with open(af) as fh: + data = json.load(fh) + except Exception: + data = {} + data["%s.png" % test_name] = description + try: + with open(af, "w") as fh: + json.dump(data, fh, indent=2) + except Exception: + pass + + +def rb_normalize_window(ax, x=60.0, y=80.0, w=1180.0, h=860.0): + """把主窗摆到已知位置/大小,让第一个工作日行的时间字段一定在可视区内。 + + 必需的原因:Electron 会**持久窗口几何**,而同一个 baseline 里 buttons 等 lane 会动窗口; + 窗口一旦偏小/偏移,月视图里第一行的 Hours incrementor 就被裁到可视区外, + `cg_click` 落空 —— 表现为"时间打不进去",三个时间段读回 (0.0, 0.0, 0.0)、band 恒为空。 + 单独跑 computation lane 时窗口还是默认几何,所以 11/11 全过;跑全量就全挂, + 正是这个差异(不是持久日历,也不是视图偏好 —— 两者实测都是干净默认值)。 + """ + import Quartz + from ApplicationServices import (AXUIElementSetAttributeValue, AXValueCreate, + kAXValueCGPointType, kAXValueCGSizeType) + win = main_window(ax) + if win is None: + return False + ref = ax._get_ref(win.id if hasattr(win, "id") else win) + AXUIElementSetAttributeValue(ref, "AXPosition", + AXValueCreate(kAXValueCGPointType, Quartz.CGPointMake(x, y))) + AXUIElementSetAttributeValue(ref, "AXSize", + AXValueCreate(kAXValueCGSizeType, Quartz.CGSizeMake(w, h))) + time.sleep(0.6) + return True diff --git a/macos/ttlapp-time-to-leave/tests/test_ax_computation.py b/macos/ttlapp-time-to-leave/tests/test_ax_computation.py new file mode 100644 index 0000000000000000000000000000000000000000..666b5dc63827fe9148a9a0d8d4f16a0301776b9a --- /dev/null +++ b/macos/ttlapp-time-to-leave/tests/test_ax_computation.py @@ -0,0 +1,402 @@ +"""COMPUTATION lane — Time to Leave (Electron work-hour logger). + +What this app *computes* is working-day arithmetic in the MONTH view: + + four time fields per working-day row, in document order + [0] begin work [1] lunch begin [2] lunch end [3] end work + -> two computed labels in the same row band + lunch interval (x ~ 945) day total (x ~ 1314) + -> three footer aggregates + Month Balance / Overall Balance (read-only HH:MM inputs), + Working days (Mon-Fri count of the displayed month), + On (last day used for the balance == month length off the current month) + +Mechanics that make these tests work (all from the golden recon model): + +* Time entry only works in the MONTH view, and only through a REAL CGEvent click + plus typed keystrokes (``AXPress`` is a no-op on every in-page Chromium control, + and an ``AXTimeField``'s ``AXValue`` is not settable). ``T.enter_times`` does + the click / KC_LEFT x2 / type dance; ``T.time_parts`` reads the value back off + the ``Hours`` / ``Minutes`` / ``AM/PM`` incrementors, because the time field's + own ``AXValue`` is always "". +* The row y must be captured BEFORE typing (``T.first_row_y``), then the computed + labels are read with ``T.band_times(ax, y)`` (left -> right: lunch interval, + then day total). +* The calendar database is PERSISTED across app relaunches, so every test that + types a time clears it again in a ``finally:`` block — otherwise it poisons + every later test (and every other lane). + +Locators are semantic only: visible label text (``Month Balance``, ``Working +days``, ``On``, month title), AX role (``timefield`` / ``incrementor`` / +``text_field``) and the row band geometry — never a child index or tree path. +""" + +from __future__ import annotations + +import time + +import pytest + +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +import rb_testgen_kit as kit # noqa: E402 +import test_ax_common as T # noqa: E402 + +FULL_DAY = ["0800AM", "1200PM", "0100PM", "0500PM"] # -> lunch 01:00, total 08:00 +HALF_LUNCH_DAY = ["0900AM", "1230PM", "0100PM", "0600PM"] # -> lunch 00:30, total 08:30 +FIRST_PAIR_ONLY = ["0800AM", "1200PM"] # -> total 04:00, lunch blank + + +# ── local read helpers (semantic, framework-tolerant) ─────────────────────── +def _band(ax, y): + """The HH:MM strings of a row band, left -> right (lunch interval, day total).""" + return [v.strip() for _x, v in T.band_times(ax, y)] + + +def _balance(ax, which="Month Balance"): + """The HH:MM value of a footer balance. + + Preferred locator is the visible footer caption (``Month Balance`` / + ``Overall Balance``) via :func:`T.footer_value`. Chromium may expose the + value only on the read-only ```` rather than as a sibling label, so + fall back to the two disabled balance text fields, ordered left -> right + (Month Balance is the left one, Overall Balance the right one). + """ + v = T.footer_value(ax, which) + if v is not None and T.HHMM_RE.match(str(v).strip()): + return str(v).strip() + ordered = [] + for f in T.balance_fields(ax): + fr = T.frame(f) + ordered.append((fr[0] if fr else 0, str(f.value or "").strip())) + ordered.sort() + if not ordered: + return None + return ordered[0][1] if str(which).lower().startswith("month") else ordered[-1][1] + + +def _parse_month(title): + """"August 2026" -> (2026, 8); None when the title is missing/odd.""" + if not title: + return None + parts = str(title).strip().split() + if len(parts) != 2 or parts[0] not in T.MONTH_NAMES or not parts[1].isdigit(): + return None + return int(parts[1]), T.MONTH_NAMES.index(parts[0]) + 1 + + +def _segments(ax, tf): + """{'hours': '08', 'minutes': '00', 'ampm': 'AM'} for one time field.""" + out = {} + for name, val in T.time_parts(ax, tf): + n = str(name or "").lower() + v = str(val if val is not None else "").strip() + if n.startswith("hour"): + out["hours"] = v + elif n.startswith("minute"): + out["minutes"] = v + elif "am" in n or "pm" in n: + out["ampm"] = v + return out + + +@pytest.fixture(autouse=True) +def _ttl_normalize_window(ax): + """每条 test 前把窗口摆成已知几何 —— 见 T.rb_normalize_window 的说明。""" + T.rb_normalize_window(ax) + yield + + +class TestComputation: + """Working-day arithmetic, row totals and footer aggregates (month view).""" + + # ── row arithmetic ───────────────────────────────────────────────────── + @pytest.mark.rb(depth=0, jump_kind="value", + expect="day total 08:00 and lunch interval 01:00 for " + "08:00/12:00/13:00/17:00") + def test_full_day_total_and_lunch(self, ax): + assert T.ensure_month_view(ax), "month view is required for time entry" + y = T.first_row_y(ax) # capture BEFORE typing + assert y is not None, "no time fields found in the month view" + try: + assert T.enter_times(ax, FULL_DAY), "could not type %r" % (FULL_DAY,) + time.sleep(0.8) + vals = _band(ax, y) + T.screenshot_assert( + "computation_full_day_total_and_lunch", + "Time to Leave month calendar. The first weekday row has 08:00 AM, " + "12:00 PM, 01:00 PM, 05:00 PM in its four time inputs, shows 01:00 in " + "the lunch/break column and 08:00 in the right-hand Total column. The " + "footer strip shows a valid HH:MM value for MONTH BALANCE.", + T.results_dir()) + assert len(vals) >= 2, ( + "expected lunch interval + day total, band=%r" % (vals,)) + lunch, total = vals[0], vals[-1] + assert kit.rb_value(lunch, "01:00"), ( + "lunch interval=%r expected 01:00, band=%r" % (lunch, vals)) + assert kit.rb_value(total, "08:00"), ( + "day total=%r expected 08:00, band=%r" % (total, vals)) + finally: + T.clear_times(ax, 4) + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="day total 08:30 and lunch 00:30 for 09:00/12:30/13:00/18:00") + def test_half_hour_lunch_day_total(self, ax): + assert T.ensure_month_view(ax), "month view is required for time entry" + y = T.first_row_y(ax) + assert y is not None, "no time fields found in the month view" + try: + assert T.enter_times(ax, HALF_LUNCH_DAY), ( + "could not type %r" % (HALF_LUNCH_DAY,)) + time.sleep(0.8) + vals = _band(ax, y) + assert len(vals) >= 2, ( + "expected lunch interval + day total, band=%r" % (vals,)) + lunch, total = vals[0], vals[-1] + assert kit.rb_value(lunch, "00:30"), ( + "lunch interval=%r expected 00:30, band=%r" % (lunch, vals)) + assert kit.rb_value(total, "08:30"), ( + "day total=%r expected 08:30, band=%r" % (total, vals)) + finally: + T.clear_times(ax, 4) + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="a day with only the FIRST pair filled shows no lunch interval and " + "no day total; both appear only once all four times are entered") + def test_partial_day_shows_no_total_until_complete(self, ax): + """完整性规则:四个时间没填齐,app 不给午休时长也不给当日总计。 + + 原用例期望 "08:00→12:00 得 04:00",**对这个版本是错的** —— 实测:只填 + 08:00 AM / 12:00 PM 时 band 恒为空(等 12s、按 Tab 触发 blur 都不出现),把后两个 + 01:00 PM / 05:00 PM 填上后 band 立刻变成 [(945,'01:00'), (1314,'08:00')]。所以这里改成 + 钉住 app 真实的完整性规则,并用"补齐后立刻出现"作为正向对照 —— 比原来的说法更强: + 一个只会无条件渲染两个数字的实现过不了前半段,一个永不计算的实现过不了后半段。 + """ + assert T.ensure_month_view(ax), "month view is required for time entry" + y = T.first_row_y(ax) + assert y is not None, "no time fields found in the month view" + try: + T.clear_times(ax, 4) + assert T.enter_times(ax, FIRST_PAIR_ONLY), ( + "could not type %r" % (FIRST_PAIR_ONLY,)) + # 给足时间,确认"不出现"是真的不出现而不是没等到 + deadline = time.time() + 6.0 + while time.time() < deadline: + if T.band_times(ax, y): + break + time.sleep(0.5) + partial = T.band_times(ax, y) + assert partial == [], ( + "an incomplete day must show neither lunch interval nor day total, band=%r" + % (partial,)) + # 正向对照:补齐后两个时间,两个派生值都必须出现 + assert T.enter_times(ax, ["0100PM", "0500PM"], start=2), "could not complete the day" + deadline = time.time() + 10.0 + vals = [] + while time.time() < deadline: + vals = [v for _, v in T.band_times(ax, y)] + if len(vals) == 2: + break + time.sleep(0.5) + assert vals == ["01:00", "08:00"], ( + "completing the day must yield lunch 01:00 and total 08:00, band=%r" % (vals,)) + finally: + T.clear_times(ax, 4) + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="a time field's Hours/Minutes/AM-PM incrementors read back the " + "typed time numerically: 08:00 AM -> (8.0, 0.0, 1.0) and " + "01:00 PM -> (1.0, 0.0, 2.0)") + def test_time_segments_read_back(self, ax): + """时间字段的三个 incrementor 读回打进去的时间,并钉住 AM/PM 的编码。 + + 原用例期望零填充字符串 '08/00/AM';**实测这个版本的 AXValue 是数值** —— + 08:00 AM 读回 [('Hours', 8.0), ('Minutes', 0.0), ('AM/PM', 1.0)],而 12:00 PM 的 + AM/PM 是 2.0。所以改成断言数值三元组,并用 PM 那一组作对照把 1.0=AM / 2.0=PM 这个 + 编码也钉死 —— 只把打进去的字符串回显、不真解析成时间的实现拿不到这个。 + """ + assert T.ensure_month_view(ax), "month view is required for time entry" + try: + T.clear_times(ax, 4) + assert T.enter_times(ax, ["0800AM"]), "could not type 0800AM" + time.sleep(0.6) + am = [(n, v) for n, v in T.time_parts(ax, T.timefields(ax)[0])] + assert [v for _, v in am] == [8.0, 0.0, 1.0], ( + "08:00 AM must read back (Hours 8.0, Minutes 0.0, AM/PM 1.0), got %r" % (am,)) + assert [n for n, _ in am] == ["Hours", "Minutes", "AM/PM"], ( + "segment order must be Hours / Minutes / AM-PM, got %r" % ([n for n, _ in am],)) + + assert T.enter_times(ax, ["0100PM"], start=1), "could not type 0100PM" + time.sleep(0.6) + pm = [v for _, v in T.time_parts(ax, T.timefields(ax)[1])] + assert pm == [1.0, 0.0, 2.0], ( + "01:00 PM must read back (1.0, 0.0, 2.0) — AM/PM 2.0 is PM, got %r" % (pm,)) + # 防退化:AM 与 PM 的第三段必须不同,否则 AM/PM 根本没被解析 + assert am[2][1] != pm[2], "AM and PM must not report the same AM/PM value" + finally: + T.clear_times(ax, 4) + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="the second working-day row totals 08:00 while the first " + "row stays blank") + def test_second_row_independent(self, ax): + assert T.ensure_month_view(ax), "month view is required for time entry" + tfs = T.timefields(ax) + assert len(tfs) >= 8, ( + "need two working-day rows (8 time fields), found %d" % len(tfs)) + f0, f4 = T.frame(tfs[0]), T.frame(tfs[4]) + assert f0 is not None and f4 is not None, "time field frames unreadable" + y_first, y_second = f0[1], f4[1] + try: + assert T.enter_times(ax, FULL_DAY, start=4), ( + "could not type %r into the second row" % (FULL_DAY,)) + time.sleep(0.8) + second = _band(ax, y_second) + first = _band(ax, y_first) + assert not first, ( + "first row must stay blank, first-row band=%r second-row band=%r" + % (first, second)) + assert len(second) >= 2, ( + "expected lunch interval + day total in row 2, band=%r" % (second,)) + assert kit.rb_value(second[-1], "08:00"), ( + "second-row day total=%r expected 08:00, band=%r" % (second[-1], second)) + finally: + T.clear_times(ax, 4, start=4) + + # ── footer aggregates ────────────────────────────────────────────────── + @pytest.mark.rb(depth=0, jump_kind="transition", + expect="in the previous complete month, Month Balance changes from " + "00:00 to a negative HH:MM after logging one full day") + def test_month_balance_becomes_negative(self, ax): + assert T.ensure_month_view(ax), "month view is required for time entry" + assert T.goto_current_month(ax), "could not return to the current month" + assert T.nav_month(ax, "backward"), "no 'Previous Month' button" + before = _balance(ax, "Month Balance") + try: + assert T.enter_times(ax, FULL_DAY), "could not type %r" % (FULL_DAY,) + time.sleep(1.0) + after = _balance(ax, "Month Balance") + assert after is not None, ( + "Month Balance unreadable after entry (before=%r, band=%r)" + % (before, T.band_times(ax, T.first_row_y(ax) or 0))) + assert str(after).startswith("-"), ( + "Month Balance before=%r after=%r — one logged day must make it " + "negative" % (before, after)) + assert kit.rb_flip(before, after), ( + "Month Balance did not change: before=%r after=%r" % (before, after)) + finally: + T.clear_times(ax, 4) + T.goto_current_month(ax) + + @pytest.mark.rb(depth=0, jump_kind="transition", + expect="day total and Month Balance return to blank / 00:00 after " + "clearing the row") + def test_clearing_entry_resets_totals(self, ax): + assert T.ensure_month_view(ax), "month view is required for time entry" + y = T.first_row_y(ax) + assert y is not None, "no time fields found in the month view" + cleared = False + try: + assert T.enter_times(ax, FULL_DAY), "could not type %r" % (FULL_DAY,) + time.sleep(0.8) + with_total = _band(ax, y) + assert with_total, "no computed HH:MM appeared after entry, band=%r" % ( + with_total,) + T.clear_times(ax, 4) + cleared = True + time.sleep(0.8) + after_clear = _band(ax, y) + balance = _balance(ax, "Month Balance") + assert not after_clear, ( + "row band must be blank after clearing: before=%r after=%r" + % (with_total, after_clear)) + assert kit.rb_value(balance, "00:00"), ( + "Month Balance=%r expected 00:00 after clearing, bands before=%r " + "after=%r" % (balance, with_total, after_clear)) + assert kit.rb_flip(str(with_total), str(after_clear)), ( + "band times did not change: before=%r after=%r" + % (with_total, after_clear)) + finally: + if not cleared: + T.clear_times(ax, 4) + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="Working days footer equals the Mon-Fri count of the " + "displayed month") + def test_working_days_matches_calendar(self, ax): + assert T.ensure_month_view(ax), "month view is required" + title = T.month_title(ax) + ym = _parse_month(title) + assert ym is not None, "unparsable month title %r" % (title,) + year, month = ym + expected = str(T.weekdays_in_month(year, month)) + observed = T.footer_value(ax, "Working days") + assert kit.rb_value(observed, expected), ( + "Working days=%r expected %r for %r (Mon-Fri count), footer labels=%r" + % (observed, expected, title, + [v for v in T.window_label_values(ax)[-8:]])) + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="Working days footer follows the newly displayed month") + def test_working_days_after_month_change(self, ax): + assert T.ensure_month_view(ax), "month view is required" + try: + assert T.nav_month(ax, "forward"), "Next Month button not usable" + title = T.month_title(ax) + ym = _parse_month(title) + assert ym is not None, "unparsable month title %r after Next Month" % ( + title,) + year, month = ym + expected = str(T.weekdays_in_month(year, month)) + observed = T.footer_value(ax, "Working days") + assert kit.rb_value(observed, expected), ( + "Working days=%r expected %r for the next month %r, footer labels=%r" + % (observed, expected, title, + [v for v in T.window_label_values(ax)[-8:]])) + finally: + T.goto_current_month(ax) + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="'On' equals the day count of a non-current month") + def test_on_equals_month_length_for_other_month(self, ax): + assert T.ensure_month_view(ax), "month view is required" + try: + assert T.nav_month(ax, "forward"), "Next Month button not usable" + title = T.month_title(ax) + ym = _parse_month(title) + assert ym is not None, "unparsable month title %r after Next Month" % ( + title,) + year, month = ym + expected = str(T.month_length(year, month)) + observed = T.footer_value(ax, "On") + assert kit.rb_value(observed, expected), ( + "'On'=%r expected %r (length of %r), footer labels=%r" + % (observed, expected, title, + [v for v in T.window_label_values(ax)[-8:]])) + finally: + T.goto_current_month(ax) + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="Month Balance and Overall Balance are 00:00 with no entries") + def test_balances_start_at_zero_on_clean_calendar(self, ax): + # Reads only — nothing is typed, so there is nothing to clean up. This test + # also documents that every other test in this module restores the calendar. + assert T.ensure_month_view(ax), "month view is required" + fields = T.balance_fields(ax) + raw = [] + for f in fields: + fr = T.frame(f) + raw.append((fr[0] if fr else 0, str(f.value or "").strip())) + raw.sort() + month = _balance(ax, "Month Balance") + overall = _balance(ax, "Overall Balance") + observed = "%s|%s" % (month, overall) + assert len(fields) >= 2, ( + "expected the two read-only balance fields, found %d: %r" + % (len(fields), raw)) + assert kit.rb_value(observed, "00:00|00:00"), ( + "Month/Overall Balance=%r expected 00:00|00:00 on a clean calendar, " + "raw balance fields=%r" % (observed, raw)) diff --git a/macos/ttlapp-time-to-leave/tests/test_ax_menus.py b/macos/ttlapp-time-to-leave/tests/test_ax_menus.py new file mode 100644 index 0000000000000000000000000000000000000000..65f0744db266a876a1e215993add064872c6ef0a --- /dev/null +++ b/macos/ttlapp-time-to-leave/tests/test_ax_menus.py @@ -0,0 +1,130 @@ +"""MENU lane — Time to Leave (macOS / Electron). + +Everything asserted here was OBSERVED on the reference app and is recorded in +``recon.md`` (``## MENUS``, ``## AX_TREE``, ``## APP``). Facts that shape this +module: + +* There are TWO ``AXMenuBar`` children of the app element: the app menu bar + (``Apple``, ``Time to Leave``, ``Edit``, ``View``, ``Help``) and the tray / + status menu bar (one unnamed ``AXMenuBarItem`` whose menu is + ``Punch time`` / ``Show App`` / ``Quit``). Both are readable through AX + WITHOUT clicking, so no menu ever has to be opened with the mouse. +* ``AXPress`` is a no-op on every in-page (Chromium) control, but it DOES work on + native NSMenu items and on ``NSAlert`` sheet buttons — that is why the menu + lane drives everything with ``T.ax_press`` / ``T.rb_reach_menu_item``. +* A menu bar must never be deep-walked: the system Apple menu subtree has + hundreds of nodes. Only the shallow ``T.menu_bar_items`` / ``T.menu_items`` + helpers are used. +* macOS renames the app's *Preferences* item to ``Settings…`` and injects + ``AutoFill`` / ``Start Dictation…`` / ``Emoji & Symbols`` into any Edit menu, + so the preferences item is matched by keyword and the injected items are never + required. +* NEVER activated here: ``Time to Leave>Exit``, tray ``Quit``, ``Yes`` on the + Clear-database alert, ``Help>TTL GitHub``, ``Help>Send feedback``, + ``Help>Check for updates``, ``View>Toggle developer tools``. +""" + +import os +import sys +import time + +import pytest + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import rb_testgen_kit as kit # noqa: E402 +import test_ax_common as T # noqa: E402 + +# Depth used for the kit's AX "showing" snapshots. The reference tree is at most +# ~12 levels deep (window > 4 groups > webarea > page nodes) and a full snapshot +# costs well under a second, so 14 captures every discriminating element with +# room to spare. +SNAP_DEPTH = 14 + +# The four menus the app itself installs (the system "Apple" menu is filtered out +# by T.app_menu_titles). +APP_MENUS = ["Time to Leave", "Edit", "View", "Help"] + + +def rb_enter_prefs_via_hotkey(ax): + """NAV helper: cross into the Preferences surface with the ``⌘,`` accelerator. + + Recon verified that the accelerator works as an alternative reach path to + ``Edit ▸ Settings…``. Returns the Preferences window element or None. + """ + existing = T.child_window(ax, "Preferences") + if existing is not None: + return existing + T.send_key(T.KC_COMMA, ["cmd"]) + return T.wait_window(ax, "Preferences", timeout=8) + + +def _names(elements): + return [(e.name or "") for e in elements] + + +def _window_buttons(ax, win): + return [e.name for e in T.walk(ax, win, 1500) if e.role == "button" and e.name] + + +class TestMenus: + # ── 1. structure of the app menu bar ──────────────────────────────────── + + # ── 2. app (first) menu items ─────────────────────────────────────────── + + # ── 3. Edit menu items ────────────────────────────────────────────────── + # AutoFill / Start Dictation… / Emoji & Symbols are system-injected and + # deliberately NOT required. + + # ── 4. View + Help menu items (read only) ─────────────────────────────── + + # ── 5. accelerators ───────────────────────────────────────────────────── + + # ── 6. tray / status menu ─────────────────────────────────────────────── + @pytest.mark.rb(depth=0, jump_kind="value", + expect="tray menu items in order: Punch time, Show App, Quit") + def test_tray_menu_items(self, ax): + items = T.tray_menu_items(ax) + named = [n for n in _names(items) if n.strip()] + assert named, ( + "the tray / status menu exposed no named items (observed %d raw items)" + % (len(items),)) + joined = " | ".join(named) + assert kit.rb_value(joined, "Punch time | Show App | Quit"), ( + "tray menu should read Punch time / Show App / Quit in that order; " + "observed %r" % (named,)) + # Never activate the tray "Quit" item. + + # ── 7. Workday Waiver Manager window ──────────────────────────────────── + + # ── 8. Preferences from the Edit menu ─────────────────────────────────── + + # ── 9. Help ▸ About alert ─────────────────────────────────────────────── + + # ── 10. Edit ▸ Clear database confirmation (never press Yes) ──────────── + + # ── 11. Edit ▸ Export database (native save panel) ────────────────────── + + # ── 12. Edit ▸ Import database (native open panel) ────────────────────── + + # ── 13. Preferences via the ⌘, accelerator ────────────────────────────── + @pytest.mark.rb(depth=1, jump_kind="reach", + expect="Preferences window opened by Cmd+,") + def test_preferences_via_keyboard_shortcut(self, ax): + before = kit.rb_showing(ax, max_depth=SNAP_DEPTH) + win = rb_enter_prefs_via_hotkey(ax) + after = kit.rb_showing(ax, max_depth=SNAP_DEPTH) + try: + assert win is not None, ( + "Cmd+, opened no Preferences window; observed windows=%r" + % ([w.name for w in T.windows(ax)],)) + assert "preferences" in (win.name or "").lower(), ( + "window opened by Cmd+, should be the Preferences window; observed " + "title %r" % (win.name,)) + assert kit.rb_reach(before, after, target="Break time interval"), ( + "Cmd+, did not reach the Preferences surface: 'Break time interval' is " + "not among the newly showing elements (window title=%r, %d new nodes)" + % (win.name, len(after - before))) + finally: + T.close_child(ax, "Preferences") + + # ── 14. Holiday tab inside the waiver window (2 surfaces deep) ────────── diff --git a/macos/ttlapp-time-to-leave/tests/test_ax_states.py b/macos/ttlapp-time-to-leave/tests/test_ax_states.py new file mode 100644 index 0000000000000000000000000000000000000000..dba81593c900f44d30c07b2643fb187e6ae706a7 --- /dev/null +++ b/macos/ttlapp-time-to-leave/tests/test_ax_states.py @@ -0,0 +1,289 @@ +"""STATE lane — Time to Leave (macOS / Electron). + +Every fact asserted here was OBSERVED on the reference app and is recorded in +``recon.md`` (sections ``## STATE`` / ``## AX_TREE`` / ``## MENUS``). + +Design constraints taken straight from recon.md's HARD-WON FACTS: + +* **Checkbox CHECKED state is NOT observable** — every Preferences checkbox reports + ``AXValue == ""`` and ``AXSelected == False`` regardless of its real state. So no + test here asserts a checked/selected state on a checkbox; each toggle test asserts + a **consequence** instead (another widget's ``enabled`` flag flipping). The waiver + TAB radios *do* expose ``AXValue`` (``1`` selected / ``0`` not) and are asserted. +* ``AXPress`` is a **no-op** on in-page (Chromium) controls → every in-page click goes + through ``T.cg_click`` / ``T.click_switch``. +* App state is persisted across launches → every flipped preference and every typed + value is restored in a ``finally`` block. + +pytest only: no argparse, no ``__main__``, no self-written JSON. The runner scores via +pytest and folds each ``@pytest.mark.rb(...)`` declaration into ``state_results.json``. +""" + +from __future__ import annotations + +import datetime +import os +import sys +import time + +import pytest + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +import rb_testgen_kit as kit # noqa: E402 +import test_ax_common as T # noqa: E402 + + +# ── screenshot helper (delegates to the shared, verified implementation) ───── +def screenshot_assert(test_name, description, results_dir=None): + """Capture the screen and record what a VLM judge should see.""" + T.screenshot_assert(test_name, description, results_dir or T.results_dir()) + + +# ── labels / constants observed on the reference app ──────────────────────── +PREFILL_LABEL = "Enable prefilling of break time" +BREAK_INTERVAL_VALUE = "00:30" +HOURS_PER_DAY_VALUE = "08:00" +EDIT_MENU_COMMANDS = ("Cut", "Copy", "Paste", "Select all", + "Export database", "Import database", "Clear database") + + +# ── small, local read helpers (semantic locators only: label + role) ───────── +def _reveal(ax): + """Best-effort reveal of the app UI. + + The reference app shows its calendar window immediately at launch (recon.md + REVEAL_STEPS), so this is a no-op there. It is kept because a recreation may + legitimately start with the window hidden behind a status item / ``Cmd+,``. + Never raises. + """ + try: + ax.ensure_ui_visible() + except Exception: + pass + + +def _norm_selected(v): + """Normalise a radio AXValue to "1" (selected) / "0" (not selected).""" + s = str(v).strip() + if s in ("1", "1.0", "True", "true", "YES"): + return "1" + if s in ("0", "0.0", "False", "false", "NO", "", "None"): + return "0" + return s + + +def _tray_punch_enabled(ax): + """Enabled flag of the tray/status menu item named 'Punch time' (or None).""" + for it in T.tray_menu_items(ax): + if (it.name or "").strip().lower() == "punch time": + return bool(it.enabled) + return None + + +def _hhmm_values(elements): + """Sorted HH:MM values held by the given elements.""" + out = [] + for e in elements: + v = str(e.value or "").strip() + if T.HHMM_RE.match(v): + out.append(v) + return sorted(out) + + +def _break_interval_enabled(ax, win=None): + """`enabled` flag of the Preferences 'Break time interval' input (value 00:30).""" + w = win if win is not None else T.child_window(ax, "Preferences") + if w is None: + return None + hits = [t for t in T.prefs_text_fields(ax, w) + if str(t.value or "").strip() == BREAK_INTERVAL_VALUE] + return bool(hits[0].enabled) if hits else None + + +def _prefs_incrementor_state(ax, win=None): + """{segment name -> value} of every Preferences incrementor. + + On the reference this is the 'Overall Balance Start Date' datefield + (Month/Day/Year) plus one unnamed = minutes between + notifications, keyed here as "Notify". + """ + w = win if win is not None else T.child_window(ax, "Preferences") + if w is None: + return {} + state = {} + for e in T.walk(ax, w, 4000): + if e.role != "incrementor": + continue + key = (e.name or "").strip() or "Notify" + state[key] = str(e.value if e.value is not None else "").strip() + return state + + +def _waiver_window(ax, win=None): + return win if win is not None else T.child_window(ax, "Waiver") + + +def _waive_button(ax, win=None): + """The waiver window's 'Waive' button (AXTitle + role match).""" + w = _waiver_window(ax, win) + if w is None: + return None + hits = [b for b in T.walk(ax, w, 2000) + if b.role == "button" and (b.name or "").strip() == "Waive"] + return hits[0] if hits else None + + +def _waive_enabled(ax, win=None): + b = _waive_button(ax, win) + return None if b is None else bool(b.enabled) + + +def _waiver_text_fields(ax, win=None): + w = _waiver_window(ax, win) + if w is None: + return [] + return T.sorted_by_position( + T.dedup_by_frame([e for e in T.walk(ax, w, 2000) if e.role == "text_field"])) + + +def _waiver_reason_field(ax, win=None): + """The Reason input: the waiver window's empty text field (the other holds 08:00).""" + empty = [t for t in _waiver_text_fields(ax, win) + if str(t.value or "").strip() == ""] + return empty[0] if empty else None + + +def _tab_state(ax, win=None): + """[(tab label, "1"|"0")] of the waiver tab radios, sorted by label.""" + w = _waiver_window(ax, win) + out = [((t.name or "").strip(), _norm_selected(t.value)) + for t in T.waiver_tabs(ax, w)] + out.sort() + return out + + +def _source_holidays_button(ax, win=None): + w = _waiver_window(ax, win) + if w is None: + return None + hits = [b for b in T.walk(ax, w, 2000) + if b.role == "button" + and (b.name or "").strip() == "Source selected holidays"] + return hits[0] if hits else None + + +def _first_hours_incrementor(ax): + """The 'Hours' segment of the first month-view time field.""" + tfs = T.timefields(ax) + return T.hours_incrementor(ax, tfs[0]) if tfs else None + + +class TestStates: + """AX state verification: enabled/disabled, focus, selection, consequences.""" + + # ── 1. read-only balance inputs ───────────────────────────────────────── + @pytest.mark.rb(depth=0, jump_kind="value", + expect="both footer balance inputs are disabled " + "(enabled False,False) and hold an HH:MM value (00:00 clean)") + def test_balance_fields_are_read_only(self, ax): + _reveal(ax) + fields = T.balance_fields(ax) + assert len(fields) == 2, ( + "expected 2 read-only balance inputs (Month Balance / Overall Balance), " + "got %d: %r" % (len(fields), [str(f.value) for f in fields])) + values = [str(f.value or "").strip() for f in fields] + observed = ",".join(str(bool(f.enabled)) for f in fields) + assert kit.rb_value(observed, "False,False"), ( + "balance inputs must be read-only; observed enabled flags=%r values=%r" + % (observed, values)) + + # ── 2. punch button mirrors the tray item ─────────────────────────────── + @pytest.mark.rb(depth=0, jump_kind="value", + expect="main 'Punch time' button enabled state equals the tray " + "'Punch time' menu item enabled state") + def test_punch_button_matches_tray_item_state(self, ax): + _reveal(ax) + btn = T.punch_button(ax) + assert btn is not None, ( + "no button named 'Punch time' in the main window; buttons=%r" + % (T.button_names(ax),)) + tray = _tray_punch_enabled(ax) + assert tray is not None, ( + "tray menu has no 'Punch time' item; tray items=%r" + % ([(i.name, bool(i.enabled)) for i in T.tray_menu_items(ax)],)) + observed = str(bool(btn.enabled)) + expected = str(bool(tray)) + assert kit.rb_value(observed, expected), ( + "punch button / tray item disagree: main button enabled=%s, " + "tray 'Punch time' enabled=%s" % (observed, expected)) + + # ── 3. punch is disabled off the current month ────────────────────────── + @pytest.mark.rb(depth=0, jump_kind="value", + expect="'Punch time' (button and tray item) is disabled while a " + "non-current month is displayed") + def test_punch_disabled_when_browsing_other_month(self, ax): + _reveal(ax) + try: + assert T.nav_month(ax, "forward"), ( + "could not click 'Next Month'; buttons=%r" % (T.button_names(ax),)) + title = T.month_title(ax) + assert title is not None and title != T.expected_month_title(), ( + "still on the current month after Next Month: title=%r" % (title,)) + btn = T.punch_button(ax) + assert btn is not None, "no 'Punch time' button after navigating forward" + tray = _tray_punch_enabled(ax) + assert tray is not None, "tray menu has no 'Punch time' item" + observed = "main=%s;tray=%s" % (bool(btn.enabled), bool(tray)) + assert kit.rb_value(observed, "main=False;tray=False"), ( + "'Punch time' must be disabled while showing %s; observed %s" + % (title, observed)) + finally: + try: + T.ensure_month_view(ax) + T.goto_current_month(ax) + except Exception: + pass + + # ── 4. clicking a time field focuses its Hours segment ────────────────── + @pytest.mark.rb(depth=0, jump_kind="transition", + expect="the Hours incrementor of the clicked time field goes " + "AXFocused False -> True") + def test_time_field_click_focuses_hours_segment(self, ax): + _reveal(ax) + tfs = T.timefields(ax) + assert len(tfs) >= 4, ( + "expected at least 4 month-view time fields, got %d" % len(tfs)) + tf = tfs[0] + inc_before = T.hours_incrementor(ax, tf) + assert inc_before is not None, ( + "first time field exposes no 'Hours' incrementor; segments=%r" + % (T.time_parts(ax, tf),)) + before = T.is_focused(inc_before) + assert T.cg_click(tf, dwell=0.5), "could not click the first time field" + time.sleep(0.4) + inc_after = _first_hours_incrementor(ax) + assert inc_after is not None, "'Hours' incrementor vanished after the click" + after = T.is_focused(inc_after) + assert kit.rb_flip(before, after), ( + "AXFocused of the Hours segment did not change: before=%s after=%s" + % (before, after)) + assert after is True, ( + "after clicking the time field its Hours segment must be AXFocused; " + "observed AXFocused=%s" % (after,)) + + # ── 5. flagship: prefill switch enables the break-time interval field ─── + + # ── 6. Preferences default values ─────────────────────────────────────── + + # ── 7. Preferences numeric / date defaults ────────────────────────────── + + # ── 8. waiver tab selection flips (two surfaces deep) ─────────────────── + + # ── 9. Waive button is gated by the Reason text ───────────────────────── + + # ── 10. waiver defaults ───────────────────────────────────────────────── + + # ── 11. holiday tab defaults (two surfaces deep) ──────────────────────── + + # ── 12. app Edit-menu commands are all enabled ────────────────────────── diff --git a/macos/ttlapp-time-to-leave/tests/test_ax_text.py b/macos/ttlapp-time-to-leave/tests/test_ax_text.py new file mode 100644 index 0000000000000000000000000000000000000000..5865f03b5bdde81ec277393c4124e9a4ad2722ad --- /dev/null +++ b/macos/ttlapp-time-to-leave/tests/test_ax_text.py @@ -0,0 +1,264 @@ +"""TEXT lane — Time to Leave (macOS / Electron). + +Every expected string asserted here was OBSERVED verbatim on the reference app and is +recorded in recon.md (``## TEXT``). Nothing version-, build- or path-specific is +asserted: the About dialog is only checked for the app-name label plus *some* detail +block, never for its contents. + +Design notes (from recon.md "HARD-WON FACTS"): + +* ``AXPress`` is a no-op on in-page Chromium controls — every in-page click goes through + ``T.cg_click`` (wrapped by the ``T.nav_*`` / ``T.rb_enter_*`` helpers used below). +* A full label walk of the main window costs ~0.7 s, so each test keeps the number of + tree walks small (the tooltip test does ONE walk and builds an AXHelp map instead of + walking once per tooltip). +* App state is PERSISTED between launches → every test that types a time clears it and + every test that leaves the month view restores it in a ``finally`` block. +""" + +from __future__ import annotations + +import datetime +import os +import sys + +import pytest + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +import rb_testgen_kit as kit # noqa: E402 +import test_ax_common as T # noqa: E402 + + +# ── local (non-navigating) conveniences ───────────────────────────────────── +def _stripped(values): + """Whitespace-stripped, non-empty text values.""" + out = [] + for v in values or []: + s = str(v).strip() + if s: + out.append(s) + return out + + +def _label_texts(ax, win=None): + """Stripped label texts of a window (ONE tree walk).""" + return _stripped(T.window_label_values(ax, win)) + + +def _missing(expected, present): + """Expected strings that are absent from `present` (exact, stripped match).""" + have = set(present) + return [s for s in expected if s not in have] + + +def _help_map(ax, root_el): + """{AXHelp text -> count} for a whole subtree, built with a SINGLE tree walk. + + Calling T.find_by_help() once per tooltip would walk the ~1400-node main window + 13 times (~9 s); one walk keeps the tooltip test inside the 30 s budget. + """ + out = {} + for el in T.walk(ax, root_el, 4000): + h = T.help_text(el) + if h: + key = str(h).strip() + out[key] = out.get(key, 0) + 1 + return out + + +MONTH_TOOLTIPS = [ + "Switch View", + "Previous Month", + "Next Month", + "Go to Current Month", + "Add a waiver for this day", + "Remove entry", + "Add entry", + "See previous entries", + "See later entries", + "Last day used for balance", + "How many working days there's in the month", + "Balance up until today for this month. A positive balance means extra hours " + "you don't need to work today (or the rest of the month).", + "Overall balance until end of the month or current day", +] + +FOOTER_CAPTIONS = ["On", "Working days", "Month Balance", "Overall Balance"] + +PREFS_LABELS = [ + "User preferences", + "Working days", + "Sun", + "Sat", + "Hide non-working days (Month View)", + "Hours per day", + "Enable prefilling of break time", + "Break time interval", + "Notification", + "Allow recurring notifications", + "Minutes between notifications", + "App Behavior", + "Language", + "Start on Login", + "Minimize button should minimize to tray", + "Close button should minimize to tray", + "Count Today in Totals", + "Overall Balance Start Date", + "Themes", + "Reset to default preferences", +] + +WAIVER_LABELS = [ + "Workday Waiver Manager", + "Start Date", + "End Date", + "From", + "to", + "Hours", + "Reason", + "Waived workday list", + "Day", + "Waiver Reason", + "Hours Waived", +] + +DAY_VIEW_LABELS = ["Month Balance", "Overall Balance", "Punch time", "Show date picker"] + + +class TestText: + """Text content of every text-bearing surface of Time to Leave.""" + + # ── 1 ─────────────────────────────────────────────────────────────────── + @pytest.mark.rb(depth=0, jump_kind="value", + expect="window title and header label are both 'Time to Leave'") + def test_window_and_header_title(self, ax): + win = T.main_window(ax) + assert win is not None, "no main calendar window found (T.main_window returned None)" + title = win.name + labels = _label_texts(ax, win) + header = labels[0] if labels else None + T.screenshot_assert( + "text_test_window_and_header_title", + "Time to Leave month calendar. The window title bar reads 'Time to Leave' and the " + "big header title at the top-left of the page also reads 'Time to Leave', with a " + "round logo top-right. Below it a toolbar row shows a switch-view icon, '<', the " + "month title '%s', '>' and a calendar icon; the table underneath has the column " + "headers 'Day' and 'Total' and one row per day of the month. The footer strip " + "reads ON / WORKING DAYS / MONTH BALANCE 00:00 / OVERALL BALANCE 00:00 and a wide " + "dark 'Punch time' bar with a fingerprint icon sits at the bottom." + % T.expected_month_title(), + T.results_dir()) + assert kit.rb_value(title, "Time to Leave"), \ + "main window title is %r, expected 'Time to Leave'" % (title,) + assert kit.rb_value(header, "Time to Leave"), \ + "first label of the main window is %r, expected 'Time to Leave' " \ + "(first 5 labels: %r)" % (header, labels[:5]) + + # ── 2 ─────────────────────────────────────────────────────────────────── + @pytest.mark.rb(depth=0, jump_kind="value", + expect="month title equals the current month and year") + def test_month_title_is_current_month(self, ax): + observed = T.month_title(ax) + expected = T.expected_month_title() + assert kit.rb_value(observed, expected), \ + "month title is %r, expected %r" % (observed, expected) + + # ── 3 ─────────────────────────────────────────────────────────────────── + @pytest.mark.rb(depth=0, jump_kind="value", expect="'Day' and 'Total' column headers") + def test_column_headers(self, ax): + labels = _label_texts(ax, T.main_window(ax)) + missing = _missing(["Day", "Total"], labels) + assert kit.rb_value(str(missing), "[]"), \ + "column header label(s) missing: %s (observed labels: %r)" % (missing, labels[:40]) + + # ── 4 ─────────────────────────────────────────────────────────────────── + @pytest.mark.rb(depth=0, jump_kind="value", + expect="all seven weekday abbreviations Mon-Sun appear in the day rows") + def test_weekday_abbreviations(self, ax): + labels = _label_texts(ax, T.main_window(ax)) + found = sorted({v for v in labels if v in T.WEEKDAY_ABBR}) + expected = sorted(T.WEEKDAY_ABBR) + assert kit.rb_value(str(found), str(expected)), \ + "weekday abbreviations found %s, expected %s (missing %s)" % ( + found, expected, _missing(expected, found)) + + # ── 5 ─────────────────────────────────────────────────────────────────── + + # ── 6 ─────────────────────────────────────────────────────────────────── + @pytest.mark.rb(depth=0, jump_kind="value", + expect="'Punch time' appears as both the button name and its inner label") + def test_punch_bar_text(self, ax): + btn = T.punch_button(ax) + assert btn is not None, "no button named 'Punch time' in the main window" + lab = T.find_label(ax, "Punch time", T.main_window(ax)) + observed = "%s|%s" % (btn.name, None if lab is None + else str(lab.value or lab.name or "").strip()) + assert kit.rb_value(observed, "Punch time|Punch time"), ( + "punch bar text mismatch — button name %r, inner label %r " + "(expected both 'Punch time')" % (btn.name, None if lab is None else + (lab.value or lab.name))) + + # ── 7 ─────────────────────────────────────────────────────────────────── + @pytest.mark.rb(depth=0, jump_kind="value", + expect="exact AXHelp tooltips for the balance cells and the entry controls") + def test_tooltip_help_strings(self, ax): + win = T.main_window(ax) + assert win is not None, "no main calendar window found" + helps = _help_map(ax, win) + missing = _missing(MONTH_TOOLTIPS, list(helps.keys())) + # Cross-check one tooltip through the semantic locator the other lanes use. + add_entry_cells = T.find_by_help(ax, "Add entry", win) + assert add_entry_cells, \ + "T.find_by_help(ax, 'Add entry') returned nothing; AXHelp texts seen: %r" \ + % (sorted(helps.keys())[:25],) + assert kit.rb_value(str(missing), "[]"), ( + "AXHelp tooltip(s) missing: %s\nobserved AXHelp texts: %r" + % (missing, sorted(helps.keys()))) + + # ── 8 ─────────────────────────────────────────────────────────────────── + @pytest.mark.rb(depth=0, jump_kind="transition", + expect="month title text changes from the current month to the next month") + def test_month_title_changes_with_navigation(self, ax): + before = T.month_title(ax) + try: + assert T.nav_month(ax, "forward"), "'Next Month' button not found / not clickable" + after = T.month_title(ax) + expected = T.expected_month_title(T.shifted_month(datetime.date.today(), 1)) + assert kit.rb_flip(before, after), \ + "month title did not change: before %r, after %r" % (before, after) + assert kit.rb_value(after, expected), \ + "month title after one 'Next Month' click is %r, expected %r" % (after, expected) + finally: + T.goto_current_month(ax) + + # ── 9 ─────────────────────────────────────────────────────────────────── + + # ── 10 ────────────────────────────────────────────────────────────────── + + # ── 11 ────────────────────────────────────────────────────────────────── + @pytest.mark.rb(depth=1, jump_kind="value", + expect="day header becomes yesterday's formatted date") + def test_day_view_header_follows_navigation(self, ax): + try: + assert T.rb_enter_day_view(ax), \ + "could not reach the Day view (view_mode=%r, buttons=%r)" % ( + T.view_mode(ax), T.button_names(ax)) + assert T.nav_day(ax, "backward"), "'Previous Day' button not found / not clickable" + observed = T.day_title(ax) + expected = T.expected_day_title( + datetime.date.today() - datetime.timedelta(days=1)) + assert kit.rb_value(observed, expected), ( + "day-view header after one 'Previous Day' click is %r, expected %r" + % (observed, expected)) + finally: + T.goto_current_day(ax) + T.ensure_month_view(ax) + + # ── 12 ────────────────────────────────────────────────────────────────── + + # ── 13 ────────────────────────────────────────────────────────────────── + + # ── 14 ────────────────────────────────────────────────────────────────── + + # ── 15 ────────────────────────────────────────────────────────────────── diff --git a/macos/ttlapp-time-to-leave/tests/testcase_counts.json b/macos/ttlapp-time-to-leave/tests/testcase_counts.json new file mode 100644 index 0000000000000000000000000000000000000000..b24d7f555e26ff2b949d7ae0b0eae1e2f985497c --- /dev/null +++ b/macos/ttlapp-time-to-leave/tests/testcase_counts.json @@ -0,0 +1,23 @@ +{ + "ax_total": 37, + "vlm_total": 3, + "ax_by_lane": { + "test_ax_buttons.py": 12, + "test_ax_common.py": 0, + "test_ax_computation.py": 11, + "test_ax_menus.py": 2, + "test_ax_states.py": 4, + "test_ax_text.py": 8 + }, + "vlm_by_dir": { + "buttons": 1, + "computation": 1, + "text": 1 + }, + "vlm_names": [ + "buttons_switch_view_day_view.png", + "computation_full_day_total_and_lunch.png", + "text_test_window_and_header_title.png" + ], + "frozen_at": "stage2_finalize" +} \ No newline at end of file diff --git a/macos/ttlapp-time-to-leave/tests/verifier_helpers.py b/macos/ttlapp-time-to-leave/tests/verifier_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..ce369cdae8db3a7427890d1636f8f5a3201dbef1 --- /dev/null +++ b/macos/ttlapp-time-to-leave/tests/verifier_helpers.py @@ -0,0 +1,753 @@ +""" +verifier_helpers.py — High-level AX testing patterns for macOS app verification. + +v6 core library. Encodes all robust testing patterns as reusable functions +so verifier agents call high-level APIs instead of building from scratch. + +Depends on: ax_helpers.py (AXHelper class) +""" + +import datetime +import os +import re +import signal +import subprocess +import time +from collections import Counter + +# --------------------------------------------------------------------------- +# Key codes (macOS virtual key codes) +# --------------------------------------------------------------------------- +KC_LEFT_ARROW = 123 +KC_RIGHT_ARROW = 124 +KC_UP_ARROW = 126 +KC_DOWN_ARROW = 125 +KC_SPACE = 49 +KC_RETURN = 36 +KC_TAB = 48 +KC_ESCAPE = 53 +KC_Q = 12 +KC_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": , "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)" + ) diff --git a/macos/ttlapp-time-to-leave/vlm_assertions.json b/macos/ttlapp-time-to-leave/vlm_assertions.json new file mode 100644 index 0000000000000000000000000000000000000000..450854fba7b04bbaddce951514f73aaabe819a2c --- /dev/null +++ b/macos/ttlapp-time-to-leave/vlm_assertions.json @@ -0,0 +1,62 @@ +{ + "schema_version": 2, + "instance_id": "macos/ttlapp-time-to-leave", + "grading": { + "mode": "deferred", + "model": null, + "scored_separately": true + }, + "totals": { + "assertions": 3, + "with_verdict": 0, + "calibrated": 0, + "usable": null, + "scored_records": 0, + "unbacked_records": 0 + }, + "assertions": [ + { + "id": "buttons_switch_view_day_view.png", + "screenshot": "buttons_switch_view_day_view.png", + "assertion": "Time to Leave in DAY view after pressing the Switch View button: a small ~500x500 window whose header shows one full date (e.g. 'Sunday, August 9, 2026') between a '<' Previous Day arrow and a '>' Next Day arrow plus a calendar 'Go to Current Day' icon; below it either the text 'Not a working day' or Entry #1/Entry #2 time rows, then a MONTH BALANCE 00:00 / OVERALL BALANCE 00:00 strip and a wide dark 'Punch time' bar with a fingerprint icon at the bottom. The month calendar table with Day/Total columns and the 'August 2026'-style month title are GONE.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "buttons_switch_view_day_view.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "computation_full_day_total_and_lunch.png", + "screenshot": "computation_full_day_total_and_lunch.png", + "assertion": "Time to Leave month calendar. The first weekday row has 08:00 AM, 12:00 PM, 01:00 PM, 05:00 PM in its four time inputs, shows 01:00 in the lunch/break column and 08:00 in the right-hand Total column. The footer strip shows a valid HH:MM value for MONTH BALANCE.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "computation_full_day_total_and_lunch.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "text_test_window_and_header_title.png", + "screenshot": "text_test_window_and_header_title.png", + "assertion": "Time to Leave month calendar. The window title bar reads 'Time to Leave' and the big header title at the top-left of the page also reads 'Time to Leave', with a round logo top-right. Below it a toolbar row shows a switch-view icon, '<', a current month-and-year title, '>' and a calendar icon; the table underneath has the column headers 'Day' and 'Total' and one row per day of the month. The footer strip reads ON / WORKING DAYS / MONTH BALANCE 00:00 / OVERALL BALANCE 00:00 and a wide dark 'Punch time' bar with a fingerprint icon sits at the bottom.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "text_test_window_and_header_title.png", + "rigor": null, + "verdict": null, + "calibration": null + } + ], + "merged_from_files": 3, + "source_shapes": { + "dict_str": 3 + } +} diff --git a/macos/vincode-io-zavala/LICENSE.md b/macos/vincode-io-zavala/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..82cbc14efbd79b8cf12d1e1b1d153aa0abef8beb --- /dev/null +++ b/macos/vincode-io-zavala/LICENSE.md @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020-2024 Maurice C. Parker + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, 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 THE +SOFTWARE. diff --git a/macos/vincode-io-zavala/instance.json b/macos/vincode-io-zavala/instance.json new file mode 100644 index 0000000000000000000000000000000000000000..983e4c5cf1430eb2479b7e7242678bb7e0855afd --- /dev/null +++ b/macos/vincode-io-zavala/instance.json @@ -0,0 +1,10 @@ +{ + "schema_version": 1, + "instance_id": "macos/vincode-io-zavala", + "platform": "macos", + "repo": "https://github.com/vincode-io/Zavala", + "commit": "b2c2aec1477d0b382dd4a2310beee17a7bc5a5d4", + "patches": [], + "package": null, + "license": null +} \ No newline at end of file diff --git a/macos/vincode-io-zavala/reference/build.sh b/macos/vincode-io-zavala/reference/build.sh new file mode 100644 index 0000000000000000000000000000000000000000..99e17e833d498996f37afbc4253e87a45338da92 --- /dev/null +++ b/macos/vincode-io-zavala/reference/build.sh @@ -0,0 +1,115 @@ +#!/usr/bin/env bash +# +# Standalone, self-contained build script for Zavala (vincode.io). +# +# Zavala is a Mac Catalyst outliner app built with Xcode. All third-party +# code is pulled in as Swift Package Manager dependencies (resolved by +# xcodebuild from the pinned Package.resolved that ships in the repo), so +# there are NO Homebrew / CocoaPods / npm dependencies to install. +# +# The project builds unmodified on the target toolchain (Xcode 15.4 / +# Apple Swift 5.10), so no source patches are required. +# +# Everything below derives from the script's own location; no absolute +# paths are hardcoded. Safe to re-run (idempotent). + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd "$SCRIPT_DIR" + +# --------------------------------------------------------------------------- +# Configuration +# --------------------------------------------------------------------------- +PROJECT="Zavala.xcodeproj" +SCHEME="Zavala" +CONFIG="Debug" +DERIVED_DATA="$SCRIPT_DIR/DerivedData" +PRODUCTS_DIR="$DERIVED_DATA/Build/Products/${CONFIG}-maccatalyst" +APP_NAME="Zavala.app" +OUT_DIR="${APP_OUTPUT_DIR:-$SCRIPT_DIR}" + +# --------------------------------------------------------------------------- +# 0. Sanity checks +# --------------------------------------------------------------------------- +if ! command -v xcodebuild >/dev/null 2>&1; then + echo "ERROR: xcodebuild not found. Install Xcode and its command line tools." >&2 + exit 1 +fi + +echo "==> Using $(xcodebuild -version | head -1)" + +# --------------------------------------------------------------------------- +# 1. Dependencies +# --------------------------------------------------------------------------- +# No brew/pod/npm packages are required. The only dependencies are Swift +# Packages (VinUtility / VinCloudKit / VinOutlineKit locally, plus a handful +# of remote packages), which xcodebuild resolves automatically using the +# revisions pinned in +# Zavala.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved +echo "==> Resolving Swift Package Manager dependencies" +xcodebuild \ + -project "$PROJECT" \ + -scheme "$SCHEME" \ + -derivedDataPath "$DERIVED_DATA" \ + -resolvePackageDependencies + +# --------------------------------------------------------------------------- +# 2. Source patches +# --------------------------------------------------------------------------- +# None required — the project compiles as-is with Swift 5.10 / Xcode 15.4. +# +# (If a future toolchain needs a fix, express it here as an inline patch: +# git apply <<'PATCH' +# diff --git a/path/File.swift b/path/File.swift +# ... +# PATCH +# so it survives a fresh clone that contains only this script.) + +# --------------------------------------------------------------------------- +# 3. Build (Mac Catalyst, code signing disabled) +# --------------------------------------------------------------------------- +echo "==> Building $SCHEME ($CONFIG, Mac Catalyst)" +xcodebuild \ + -project "$PROJECT" \ + -scheme "$SCHEME" \ + -configuration "$CONFIG" \ + -destination 'platform=macOS,variant=Mac Catalyst' \ + -derivedDataPath "$DERIVED_DATA" \ + CODE_SIGN_IDENTITY="" \ + CODE_SIGNING_ALLOWED=NO \ + CODE_SIGNING_REQUIRED=NO \ + build + +BUILT_APP="$PRODUCTS_DIR/$APP_NAME" +if [ ! -d "$BUILT_APP" ]; then + echo "ERROR: build did not produce $BUILT_APP" >&2 + exit 1 +fi + +# --------------------------------------------------------------------------- +# 4. Ad-hoc code signing +# --------------------------------------------------------------------------- +# The Xcode build above is fully unsigned. An unsigned bundle launches fine on +# Intel, but Apple Silicon requires at least an ad-hoc signature to run any +# executable. Ad-hoc signing (identity "-") needs no developer account and +# embeds no entitlements, so the app stays un-sandboxed and freely launchable. +# --deep signs all nested code (framework + plug-ins) inside-out. +echo "==> Ad-hoc signing $APP_NAME" +codesign --force --deep --sign - --timestamp=none "$BUILT_APP" || \ + echo "WARNING: ad-hoc signing failed; app may still run unsigned on Intel." >&2 + +# --------------------------------------------------------------------------- +# 5. Copy the finished app to the output directory +# --------------------------------------------------------------------------- +mkdir -p "$OUT_DIR" +if [ "$(cd "$OUT_DIR" && pwd)" != "$(cd "$(dirname "$BUILT_APP")" && pwd)" ]; then + echo "==> Copying $APP_NAME to $OUT_DIR" + rm -rf "${OUT_DIR:?}/$APP_NAME" + cp -R "$BUILT_APP" "$OUT_DIR/$APP_NAME" +fi + +FINAL_APP="$OUT_DIR/$APP_NAME" +echo "" +echo "==> BUILD COMPLETE" +echo " App: $FINAL_APP" diff --git a/macos/vincode-io-zavala/reference/launch.sh b/macos/vincode-io-zavala/reference/launch.sh new file mode 100644 index 0000000000000000000000000000000000000000..9177cf8009e9e8c5ff2e5fca432ae6e520f54a88 --- /dev/null +++ b/macos/vincode-io-zavala/reference/launch.sh @@ -0,0 +1,41 @@ +#!/usr/bin/env bash +# +# Launch script for Zavala. +# +# Locates the built Zavala.app relative to this script (or via APP_OUTPUT_DIR) +# and launches it. The app bundle is fully self-contained (its one dynamic +# dependency, VinXML.framework, is embedded and resolved via +# @executable_path/Frameworks), so no DYLD_* / plugin environment variables +# are needed. +# +# Works standalone; build.sh does not need to have been sourced first. + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +APP_NAME="Zavala.app" + +# Search, in order: explicit output dir, next to this script, the Xcode +# DerivedData product location. +CANDIDATES=( + "${APP_OUTPUT_DIR:-}/$APP_NAME" + "$SCRIPT_DIR/$APP_NAME" + "$SCRIPT_DIR/DerivedData/Build/Products/Debug-maccatalyst/$APP_NAME" +) + +APP_PATH="" +for candidate in "${CANDIDATES[@]}"; do + if [ -n "$candidate" ] && [ -d "$candidate" ]; then + APP_PATH="$candidate" + break + fi +done + +if [ -z "$APP_PATH" ]; then + echo "ERROR: could not find $APP_NAME. Run build.sh first." >&2 + exit 1 +fi + +echo "Launching $APP_PATH" +# -W waits until the app exits; pass any extra arguments through to the app. +exec open -W "$APP_PATH" --args "$@" diff --git a/macos/vincode-io-zavala/tests/ax_helpers.py b/macos/vincode-io-zavala/tests/ax_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..2418d7b8c75891c2d08906848d6a36517cb98135 --- /dev/null +++ b/macos/vincode-io-zavala/tests/ax_helpers.py @@ -0,0 +1,849 @@ +import os +import re +import time +import warnings +import subprocess +from dataclasses import dataclass, field +from typing import Optional +from 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", +} + + +@dataclass +class 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 None diff --git a/macos/vincode-io-zavala/tests/conftest.py b/macos/vincode-io-zavala/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..21a9b7debd04c0633d77a60d8269102790a13e84 --- /dev/null +++ b/macos/vincode-io-zavala/tests/conftest.py @@ -0,0 +1,584 @@ +""" +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 json +import os +import signal +import subprocess +import tempfile +import 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 _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 ` whose ARGUMENT merely contains the bundle path. + + A running .app's argv0 is /Contents/MacOS/, so we require that inner + executable path. The old bare-substring test (`app_path in args`) also matched the + lingering `open -W ` 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 == /Contents/MacOS/. + 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 ` 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//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//... — 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.fixture +def app_process(app_path): + pid = _launch_app(app_path) + yield pid + _kill_pid(pid) + + +@pytest.fixture +def 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.fixture +def 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")) diff --git a/macos/vincode-io-zavala/tests/fixtures/sample.opml b/macos/vincode-io-zavala/tests/fixtures/sample.opml new file mode 100644 index 0000000000000000000000000000000000000000..035f43c6ab04a7fe83785faba074bf618130137f --- /dev/null +++ b/macos/vincode-io-zavala/tests/fixtures/sample.opml @@ -0,0 +1,11 @@ + + + Sample Outline + + + + + + + + diff --git a/macos/vincode-io-zavala/tests/rb_testgen_kit.py b/macos/vincode-io-zavala/tests/rb_testgen_kit.py new file mode 100644 index 0000000000000000000000000000000000000000..ccbbdd3c6136513161c133fbb4cefcfb0386d55c --- /dev/null +++ b/macos/vincode-io-zavala/tests/rb_testgen_kit.py @@ -0,0 +1,575 @@ +#!/usr/bin/env python3 +"""RB TestGen Kit (macOS/AX port of the Linux v7.5 kit) — a test's NAVIGATION +DEPTH and JUMP RIGOR are DECLARED (not inferred), uniformly recorded, and +self-auditable. + +DIFFERENCE FROM LINUX: macOS tests are **pytest** (methods on Test* classes taking +the `ax` fixture, plain asserts) — NOT standalone scripts calling R.record(). So the +DECLARATION is a pytest marker on the test method: + + import rb_testgen_kit as kit + + @pytest.mark.rb(depth=1, jump_kind="reach", expect="Preferences window visible") + def test_prefs_opens(self, ax_with_reset): + before = kit.rb_showing(ax_with_reset) + helpers.rb_reach_prefs(ax_with_reset) # a nav helper you name rb_reach_* / rb_enter_* + after = kit.rb_showing(ax_with_reset) + assert kit.rb_reach(before, after, target="Preferences", source="menu bar") + +conftest.py's pytest_runtest_makereport hook reads the marker + the test outcome and +writes {name, passed, depth, jump_kind, tier, expect} so the runner can fold it into +_results.json. The audits below then read those records (+ the test SOURCE). + +jump_kind (verbatim strings — the audit/stats key off them): + "none" no trigger; existence/structure only -> tier 0 + "liveness" only "did not crash / still alive" -> tier 1 (weak; avoid) + "reach" a real surface jump: the TARGET surface's element + APPEARED and the SOURCE surface's element DISAPPEARED -> tier 2 + "transition" a state flip (CHECKED/ENABLED/mode) before->after -> tier 2 + "value" a specific expected value/content was asserted -> tier 3 + +DEPTH is the number of surfaces crossed before the assertion (0 = home/first screen, +1 = one dialog/panel/submenu, 2+ = deeper). A flat-tree read of a deep element is +depth 0 — depth counts surfaces the test actually navigated through. + +REACH PROOF (so "reach" cannot be faked by reading a flat tree): + before = rb_showing(ax) + + 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('')" + python3 -c "import rb_testgen_kit as k; k.rb_lint('')" + python3 -c "import rb_testgen_kit as k; k.rb_lint_sources('')" + python3 -c "import rb_testgen_kit as k; k.rb_audit_depth('','')" +""" +from __future__ import annotations + +import ast +import glob +import json +import os +import re + +JUMP_KINDS = {"none": 0, "liveness": 1, "reach": 2, "transition": 2, "value": 3} + +# Double-axis quota TARGETS (fractions) — goals rb_audit REPORTS, NOT a hard gate. +QUOTAS = { + "existence_max": 0.30, # jump_kind=="none" share of ALL tests + "interactive_min": 0.60, # reach|transition|value share of ALL tests + "depth_ge1_min": 0.40, # depth>=1 share of INTERACTIVE tests + "depth_ge2_min": 0.10, # depth>=2 share of INTERACTIVE tests + "value_min": 0.25, # jump_kind=="value" share of INTERACTIVE tests +} + +# Depth family: a test "crosses a surface" iff it calls a member of the depth family. +# macOS accepts BOTH the naming convention rb_enter_*/rb_reach_* (write your own nav +# helper and NAME it so) AND the existing verifier_helpers/ax_helpers navigation +# functions (whitelist below) — so tests can reuse the mature reveal/navigate helpers. +DEPTH_FWD_RE = re.compile(r"^rb_(enter|reach)[a-z0-9_]*$") +DEPTH_BACK_RE = re.compile(r"^rb_back[a-z0-9_]*$") +# verifier_helpers / ax_helpers navigation functions that OPEN or move to a new surface. +FWD_WHITELIST = { + "ensure_ui_visible", "ensure_panel_open", "open_actions_menu", "open_menu", + "open_settings", "open_preferences", "open_dialog", "open_panel", "open_window", + "navigate_month", "navigate", "switch_tab", "switch_mode", "switch_page", + "select_tab", "reveal_window", "show_panel", "show_menu", +} +BACK_WHITELIST = { + "dismiss_menus", "dismiss_panel", "dismiss_any_dialog", "close_panel", + "close_window", "go_back", +} +# pytest fixtures that themselves navigate into a surface during setup (so a test taking +# one legitimately has depth>=1 without a nav call in its own body). `ax` does NOT navigate. +_NAV_FIXTURES = {"ax_with_reset", "open_panel"} +# MEASURED-TIER verdict families (ported from keliang): a tier2/3 jump_kind must be BACKED +# by its verdict function — transition->rb_flip*, value->rb_value*, reach->rb_reach* — whose +# bool result is the test's assertion. Self-named wrappers count by prefix. +TIER_FLIP_RE = re.compile(r"^rb_flip[a-z0-9_]*$") +TIER_VALUE_RE = re.compile(r"^rb_value[a-z0-9_]*$") +_JK_FAMILY = {"transition": "flip", "value": "value", "reach": "reach"} +# normalize plural (v73prep) / singular module names so a JSON module ("button") and a +# file stem ("buttons") join. +_MODULE_ALIAS = {"menus": "menu", "buttons": "button", "states": "state", + "structures": "structure", "texts": "text", + "computations": "computation", "workflows": "workflow"} + +_DEPTH = 0 # module-global surface counter for rb_enter/rb_back + + +def tier_of(jump_kind: str) -> int: + return JUMP_KINDS.get(jump_kind, 2) + + +def rb_reset_depth() -> None: + global _DEPTH + _DEPTH = 0 + + +def rb_enter(_surface: str = "") -> int: + """Call right after your test navigates into a new surface (dialog/panel/submenu).""" + global _DEPTH + _DEPTH += 1 + return _DEPTH + + +def rb_back() -> int: + global _DEPTH + _DEPTH = max(0, _DEPTH - 1) + return _DEPTH + + +def _walk_tree_nodes(node, out, seen): + """Yield 'role|name' for a macOS AXHelper.tree() dict node (+children).""" + if not isinstance(node, dict) or seen[0] >= 8000: + return + seen[0] += 1 + role = str(node.get("role") or "") + name = str(node.get("name") or node.get("value") or "") + if role or name: + out.add(f"{role}|{name}") + for c in (node.get("children") or []): + _walk_tree_nodes(c, out, seen) + + +def rb_showing(ax, max_depth: int = 12) -> set: + """Snapshot the currently-reachable AX subtree under the app as {"role|name"}. + macOS AX has no AT-SPI SHOWING/VISIBLE state, so we approximate "showing" by the + live AX tree (AXChildren) the app currently exposes — a new window/sheet/popover + adds its elements; a dismissed one removes them. Feed before+after a trigger to + rb_reach() so a 'reach' test proves a REAL surface change, not a flat-tree read. + Safe no-op (empty set) if `ax` cannot produce a tree.""" + out: set = set() + try: + tree = ax.tree(max_depth=max_depth) # AXHelper.tree() -> nested dict + except Exception: + return out + _walk_tree_nodes(tree, out, [0]) + return out + + +def rb_reach(before, after, target: str, source: str | None = None) -> bool: + """True-jump verdict: the TARGET surface's discriminating element newly APPEARED + AND (if given) the SOURCE surface's discriminating element DISAPPEARED. This is + what separates a real surface jump from reading an element that was always there.""" + before = set(before or []) + after = set(after or []) + t = target.lower() + appeared = any(t in k.lower() for k in (after - before)) + if source is None: + return appeared + s = source.lower() + src_before = any(s in k.lower() for k in before) + src_after = any(s in k.lower() for k in after) + return appeared and src_before and not src_after + + +def rb_flip(before, after, expect: str = "") -> bool: + """In-page STATE-FLIP verdict (tier2 `transition`): the observed state actually CHANGED + before->after (a CHECKED/ENABLED/mode/selection value read the two times). Pass its bool + as the test's assertion. Does NOT touch depth — an in-page flip is depth 0 unless you + navigated a surface to reach the control. You MAY write your own `rb_flip_()` 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_()` 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 | " + "{audit_depth|audit_tier} [results_dir]}") diff --git a/macos/vincode-io-zavala/tests/requirements.txt b/macos/vincode-io-zavala/tests/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..feef67ce2aadbaa26d12e6b01cff7b8ce89ecb5c --- /dev/null +++ b/macos/vincode-io-zavala/tests/requirements.txt @@ -0,0 +1,3 @@ +pytest +pytest-check +pyobjc diff --git a/macos/vincode-io-zavala/tests/test_ax_computation.py b/macos/vincode-io-zavala/tests/test_ax_computation.py new file mode 100644 index 0000000000000000000000000000000000000000..b1be8e3d32bb34ab2edb8013486931bd12d0eee1 --- /dev/null +++ b/macos/vincode-io-zavala/tests/test_ax_computation.py @@ -0,0 +1,244 @@ +"""test_ax_computation.py — Zavala outliner "computation" behavior. + +For an OUTLINER, "computation" = outline-editing operations: New Outline creates a +document (sidebar count +1), the Title and each row topic round-trip through AX +AXValue, Add Row Below grows the row set, and Complete flips a row's AXDescription +to "Complete". These are the app's core behavioral effects, so nearly every test +here is jump_kind="value" or "transition", most at depth >= 1 (a fresh outline) or +depth >= 2 (an outline with a focused row). + +Ground truth: recon.md (§4 editor behavior) + zavala_helpers.py (verified live). + +PORTABILITY: every test drives the RUNNING app through the `ax` fixture + `zavala_helpers` +only — no bundle id, no container path, no `defaults write`, no `open -a`, no absolute +path, no direct AX handle. The SAME file scores the official app AND any recreation. + +STATE ISOLATION: documents accumulate across the shared session, so NEVER assert an +absolute `z.all_count(ax)` — assert the DELTA. Each test builds its own outline via +`z.rb_reach_new_outline(ax)` for a deterministic clean slate (0 rows, Title focused). +""" + +import os +import time + +import pytest + +import zavala_helpers as z +import rb_testgen_kit as kit # noqa: F401 (kit backs the @pytest.mark.rb declarations) + +RESULTS_DIR = os.environ.get("RESULTS_DIR", "") + + +def _values(areas): + """[(a.value or "") for a in areas] — text_area contents as plain strings.""" + return [(a.value or "") for a in areas] + + +class TestAXComputation: + """Behavioral (value/transition) tests for Zavala outline editing.""" + + # 1 ───────────────────────────────────────────────────────────────────── + @pytest.mark.rb(depth=1, jump_kind="value", + expect="All count increments by 1 on New Outline") + def test_new_outline_creates_document(self, ax): + """New Outline adds exactly one document to the sidebar 'All' collection.""" + before = z.all_count(ax) + assert before is not None, "sidebar 'All' count unreadable" + assert z.rb_reach_new_outline(ax), "New Outline did not open an editor" + after = z.all_count(ax) + assert after == before + 1, f"All count {before} -> {after} (expected +1)" + + # 2 ───────────────────────────────────────────────────────────────────── + @pytest.mark.rb(depth=1, jump_kind="value", + expect="outline Title reads 'Groceries'") + def test_title_roundtrip(self, ax): + """Set the outline Title via AX and read it back exactly.""" + assert z.rb_reach_new_outline(ax), "New Outline did not open an editor" + title = z.title_area(ax) + assert title is not None, "no Title text_area in a fresh outline" + z.set_text(ax, title, "Groceries") + time.sleep(0.3) + title = z.title_area(ax) # re-fetch: elements are re-resolved per call + assert title is not None and (title.value or "") == "Groceries", \ + f"Title reads {title.value if title else None!r}, expected 'Groceries'" + z.screenshot_assert( + "computation_title", + "Zavala editor with the outline title set to 'Groceries'. The title text " + "shows at the top of the editor pane; the row area below is still empty. " + "The three-pane layout (sidebar, documents, editor) and toolbar are visible.", + RESULTS_DIR) + + # 3 ───────────────────────────────────────────────────────────────────── + @pytest.mark.rb(depth=2, jump_kind="value", + expect="first row topic reads 'Buy Milk'") + def test_first_row_text(self, ax): + """Create the first row (tap) and round-trip its topic text.""" + assert z.rb_reach_new_outline(ax), "New Outline did not open an editor" + assert z.rb_enter_first_row(ax), "first row was not created on tap" + rows = z.row_areas(ax) + assert rows, "no row text_area after creating the first row" + z.set_text(ax, rows[-1], "Buy Milk") + time.sleep(0.3) + vals = _values(z.editor_text_areas(ax)) + assert "Buy Milk" in vals, f"'Buy Milk' not in editor text areas {vals}" + z.screenshot_assert( + "computation_first_row", + "Zavala outline whose first row topic reads 'Buy Milk', shown beneath the " + "(empty) outline title. Exactly one row is present in the editor.", + RESULTS_DIR) + + # 4 ───────────────────────────────────────────────────────────────────── + @pytest.mark.rb(depth=2, jump_kind="transition", + expect="editor text_area count +1 after Add Row Below") + def test_add_row_below_grows(self, ax): + """Outline ▸ Add Row Below adds a sibling row (text_area count +1).""" + assert z.rb_reach_new_outline(ax), "New Outline did not open an editor" + assert z.rb_enter_first_row(ax), "first row was not created on tap" + n0 = len(z.editor_text_areas(ax)) + assert z.add_row_below(ax), "Add Row Below could not be invoked" + n1 = len(z.editor_text_areas(ax)) + assert n1 == n0 + 1, f"text_area count {n0} -> {n1} (expected +1)" + + # 5 ───────────────────────────────────────────────────────────────────── + + # 6 ───────────────────────────────────────────────────────────────────── + @pytest.mark.rb(depth=2, jump_kind="transition", + expect="current row AXDescription '' → 'Complete'") + def test_complete_marks_row(self, ax): + """Outline ▸ Complete flips the current row's AXDescription to 'Complete'.""" + assert z.rb_reach_new_outline(ax), "New Outline did not open an editor" + assert z.rb_enter_first_row(ax), "first row was not created on tap" + assert not z.any_row_complete(ax), "a row was 'Complete' before completing any" + assert z.complete_current_row(ax), "Complete could not be invoked" + time.sleep(0.4) + assert z.any_row_complete(ax), "no row reports AXDescription 'Complete' after Complete" + z.screenshot_assert( + "computation_complete", + "Zavala outline with one row marked done: the completed row's topic is shown " + "struck-through (Complete state), distinct from any un-completed rows.", + RESULTS_DIR) + + # 7 ───────────────────────────────────────────────────────────────────── + @pytest.mark.rb(depth=2, jump_kind="value", + expect="exactly one of two rows is Complete") + def test_complete_one_of_two(self, ax): + """With two rows, Complete marks exactly one of them (not both).""" + assert z.rb_reach_new_outline(ax), "New Outline did not open an editor" + assert z.rb_enter_first_row(ax), "first row was not created on tap" + assert z.add_row_below(ax), "Add Row Below (2nd row) could not be invoked" + assert len(z.row_areas(ax)) == 2, \ + f"expected two rows, saw {len(z.row_areas(ax))}" + assert z.complete_current_row(ax), "Complete could not be invoked" + time.sleep(0.4) + descs = z.row_descriptions(ax) + assert descs.count("Complete") == 1, \ + f"expected exactly one Complete row, descriptions={descs}" + + # 8 ───────────────────────────────────────────────────────────────────── + @pytest.mark.rb(depth=2, jump_kind="value", + expect="row keeps unicode text 'Café ☕'") + def test_unicode_row_text(self, ax): + """A row topic with accented + emoji characters round-trips exactly.""" + target = "Café ☕" + assert z.rb_reach_new_outline(ax), "New Outline did not open an editor" + assert z.rb_enter_first_row(ax), "first row was not created on tap" + rows = z.row_areas(ax) + assert rows, "no row text_area after creating the first row" + z.set_text(ax, rows[-1], target) + time.sleep(0.3) + vals = _values(z.editor_text_areas(ax)) + assert target in vals, f"{target!r} not preserved; editor areas = {vals}" + + # 9 ───────────────────────────────────────────────────────────────────── + @pytest.mark.rb(depth=2, jump_kind="value", + expect="longer sentence round-trips exactly") + def test_long_text_roundtrip(self, ax): + """A ~40-character sentence round-trips through a row topic unchanged.""" + target = "The quick brown fox jumps over lazy dog." + assert z.rb_reach_new_outline(ax), "New Outline did not open an editor" + assert z.rb_enter_first_row(ax), "first row was not created on tap" + rows = z.row_areas(ax) + assert rows, "no row text_area after creating the first row" + z.set_text(ax, rows[-1], target) + time.sleep(0.3) + vals = _values(z.editor_text_areas(ax)) + assert target in vals, f"long sentence not preserved; editor areas = {vals}" + + # 10 ──────────────────────────────────────────────────────────────────── + @pytest.mark.rb(depth=1, jump_kind="value", + expect="empty new outline has exactly one text_area (Title, 0 rows)") + def test_new_outline_starts_empty(self, ax): + """A brand-new outline exposes exactly one editor text_area: the Title.""" + assert z.rb_reach_new_outline(ax), "New Outline did not open an editor" + areas = z.editor_text_areas(ax) + assert len(areas) == 1, \ + f"fresh outline should have 1 text_area (Title), saw {len(areas)}: {_values(areas)}" + + # 11 ──────────────────────────────────────────────────────────────────── + @pytest.mark.rb(depth=2, jump_kind="transition", + expect="row text_area count grows 1→2→3 as rows are added") + def test_row_count_progression(self, ax): + """Row count climbs 1 → 2 → 3 as Add Row Below is invoked twice.""" + assert z.rb_reach_new_outline(ax), "New Outline did not open an editor" + assert z.rb_enter_first_row(ax), "first row was not created on tap" + assert len(z.row_areas(ax)) == 1, \ + f"expected 1 row after first tap, saw {len(z.row_areas(ax))}" + assert z.add_row_below(ax), "Add Row Below (2nd row) could not be invoked" + assert len(z.row_areas(ax)) == 2, \ + f"expected 2 rows after 1st Add Row Below, saw {len(z.row_areas(ax))}" + assert z.add_row_below(ax), "Add Row Below (3rd row) could not be invoked" + assert len(z.row_areas(ax)) == 3, \ + f"expected 3 rows after 2nd Add Row Below, saw {len(z.row_areas(ax))}" + + # 12 ──────────────────────────────────────────────────────────────────── + @pytest.mark.rb(depth=2, jump_kind="value", + expect="Title and a row hold different independent values") + def test_title_and_row_independent(self, ax): + """Title and a row topic hold separate values — neither overwrites the other.""" + assert z.rb_reach_new_outline(ax), "New Outline did not open an editor" + title = z.title_area(ax) + assert title is not None, "no Title text_area in a fresh outline" + z.set_text(ax, title, "Header") + time.sleep(0.3) + assert z.rb_enter_first_row(ax), "first row was not created on tap" + rows = z.row_areas(ax) + assert rows, "no row text_area after creating the first row" + z.set_text(ax, rows[-1], "Body") + time.sleep(0.3) + title_val = (z.title_area(ax).value or "") + row_vals = _values(z.row_areas(ax)) + assert title_val == "Header", f"Title changed to {title_val!r} (expected 'Header')" + assert "Body" in row_vals, f"row 'Body' missing; rows = {row_vals}" + assert "Header" not in row_vals, \ + f"a row wrongly holds the Title's value; rows = {row_vals}" + + # 13 ──────────────────────────────────────────────────────────────────── + @pytest.mark.rb(depth=1, jump_kind="value", + expect="two New Outlines increment count by 2") + def test_two_outlines_delta(self, ax): + """Two New Outlines add exactly two documents to the 'All' count.""" + before = z.all_count(ax) + assert before is not None, "sidebar 'All' count unreadable" + assert z.rb_reach_new_outline(ax), "first New Outline did not open an editor" + assert z.rb_reach_new_outline(ax), "second New Outline did not open an editor" + after = z.all_count(ax) + assert after == before + 2, f"All count {before} -> {after} (expected +2)" + + # 14 ──────────────────────────────────────────────────────────────────── + @pytest.mark.rb(depth=2, jump_kind="value", + expect="overwriting a row's text replaces it") + def test_row_text_overwrite(self, ax): + """Re-setting a row's text replaces the old value entirely.""" + assert z.rb_reach_new_outline(ax), "New Outline did not open an editor" + assert z.rb_enter_first_row(ax), "first row was not created on tap" + rows = z.row_areas(ax) + assert rows, "no row text_area after creating the first row" + z.set_text(ax, rows[-1], "First") + time.sleep(0.3) + rows = z.row_areas(ax) # re-fetch the same row + assert rows, "row disappeared after first set_text" + z.set_text(ax, rows[-1], "Second") + time.sleep(0.3) + vals = _values(z.row_areas(ax)) + assert "Second" in vals, f"overwrite value 'Second' missing; rows = {vals}" + assert "First" not in vals, f"old value 'First' still present; rows = {vals}" diff --git a/macos/vincode-io-zavala/tests/test_ax_menus.py b/macos/vincode-io-zavala/tests/test_ax_menus.py new file mode 100644 index 0000000000000000000000000000000000000000..f79a000cbe782f86c7631a236fb41b742165c8a3 --- /dev/null +++ b/macos/vincode-io-zavala/tests/test_ax_menus.py @@ -0,0 +1,216 @@ +"""test_ax_menus.py — AX menu-bar tests for the Zavala outliner (native macOS/Catalyst). + +The SAME file runs against the official app (must pass 100%) and against a recreation +(a missing menu / item / enablement transition must FAIL). PORTABLE by construction: +every test drives the RUNNING app through the pytest `ax` fixture + zavala_helpers (`z`) +only — no hardcoded bundle id, no group-container path, no defaults-domain seeding, no +launch-by-path, and no direct AX app-handle creation. + +Each test DECLARES navigation depth + jump rigor via @pytest.mark.rb(...); the conftest +hook folds {passed, depth, jump_kind, tier, expect} into menu_results.json (kit.rb_audit / +rb_audit_depth read it). `reach` tests PROVE a real surface jump with kit.rb_showing +before/after + kit.rb_reach (target element newly APPEARED) — never a flat-tree read. +The existence tests open the menu with z.open_menu (a whitelisted nav helper) so their +declared depth=1 is backed by a real surface crossing. + +Ground truth: recon.md §2 (menus / items / shortcuts), §3 (Settings window). SAFETY: +destructive / picker items (Quit*, Close*, Delete*, Import OPML…, Export*, Print*, +Insert Image…, Share…) are only checked for PRESENCE / enablement — never AXPress'd. +""" + +import os, time, pytest +import zavala_helpers as z +import rb_testgen_kit as kit + +RESULTS_DIR = os.environ.get("RESULTS_DIR", "") + + +def _menu_names(ax, menu): + """Open a top-level menu (nav → one surface crossing) and return its non-empty item + labels. Uses z.open_menu (a whitelisted nav helper) so the declared depth=1 is backed.""" + return [i.name for i in z.open_menu(ax, menu) if i.name] + + +def _assert_contains(menu_label, names, required): + """Assert every label in `required` is present in `names` (order-independent).""" + missing = [r for r in required if r not in names] + assert not missing, ( + f"{menu_label} menu missing expected item(s): {missing}\n found: {names}") + + +# =========================================================================== +# Menu CONTENTS — each top-level menu exposes its SPECIFIC items (recon §2). +# depth=1 (we opened the menu), jump_kind="none" (existence of named items). +# =========================================================================== + +class TestMenuContents: + + @pytest.mark.rb(depth=1, jump_kind="none") + def test_file_menu_items(self, ax): + names = _menu_names(ax, "File") + _assert_contains("File", names, [ + "New Outline", "New Main Window", "Open Quickly…", "Close", "Sync", + "Get Info", "Import OPML…", "Export", "Print Doc…", "Print List…"]) + z.screenshot_assert( + "menu_test_file_menu", + "File menu is open showing items: New Outline, New Main Window, " + "Open Quickly…, Close, Sync, Get Info, Import OPML…, Export, " + "Print Doc…, Print List…", + RESULTS_DIR) + z.close_menus(ax) + + @pytest.mark.rb(depth=1, jump_kind="none") + def test_edit_menu_items(self, ax): + names = _menu_names(ax, "Edit") + _assert_contains("Edit", names, [ + "Undo", "Redo", "Cut", "Copy", "Paste", "Copy Row Link", + "Copy Document Link", "Find…", "Link…", "Transformations", "Speech"]) + z.close_menus(ax) + + @pytest.mark.rb(depth=1, jump_kind="none") + def test_view_menu_items(self, ax): + names = _menu_names(ax, "View") + _assert_contains("View", names, [ + "Focus In", "Focus Out", "Turn Filter On", "Filter Completed", + "Filter Notes", "Expand", "Collapse", "Zoom In", "Zoom Out", + "Show Sidebar"]) + z.close_menus(ax) + + @pytest.mark.rb(depth=1, jump_kind="none") + def test_outline_menu_items(self, ax): + names = _menu_names(ax, "Outline") + _assert_contains("Outline", names, [ + "Add Row Above", "Add Row Below", "Add Row Inside", "Add Row Outside", + "Duplicate Row", "Move Left", "Move Right", "Move Up", "Move Down", + "Complete", "Add Note"]) + z.close_menus(ax) + + @pytest.mark.rb(depth=1, jump_kind="none") + def test_format_menu_items(self, ax): + names = _menu_names(ax, "Format") + _assert_contains("Format", names, ["Bold", "Italic"]) + # Format is a tiny menu: exactly Bold + Italic (recon §2). + assert set(names) == {"Bold", "Italic"}, ( + f"Format menu should contain exactly Bold + Italic; got {names}") + z.close_menus(ax) + + @pytest.mark.rb(depth=1, jump_kind="none") + def test_zavala_menu_items(self, ax): + names = _menu_names(ax, "Zavala") + _assert_contains("Zavala", names, ["About Zavala", "Settings…", "Quit Zavala"]) + z.close_menus(ax) + + @pytest.mark.rb(depth=1, jump_kind="none") + def test_help_menu_items(self, ax): + names = _menu_names(ax, "Help") + _assert_contains("Help", names, [ + "Zavala Help", "Community Discussion", "Provide Feedback"]) + z.close_menus(ax) + + +# =========================================================================== +# SUBMENUS — a nested menu surface (depth 2). PROVE the submenu items newly +# APPEARED after opening the parent menu (kit.rb_showing before/after + rb_reach). +# =========================================================================== + + + +# =========================================================================== +# SETTINGS — ⌘, opens a SEPARATE window titled "Settings" (a genuine surface +# jump). PROVE the Settings surface appeared (kit.rb_showing before/after). +# =========================================================================== + +class TestSettings: + + @pytest.mark.rb(depth=1, jump_kind="reach", + expect="Settings window appears from ⌘,") + def test_settings_opens(self, ax): + before = kit.rb_showing(ax) + w = z.rb_reach_settings(ax) + assert w is not None, "⌘, did not open a window titled 'Settings'" + after = kit.rb_showing(ax) + assert kit.rb_reach(before, after, target="Settings"), ( + "Settings surface did not newly appear after ⌘,") + z.screenshot_assert( + "menu_test_settings_opens", + "Settings window is visible showing a Color Palette popup (Automatic) " + "and preference checkboxes: Use Main Window as Default, Enable On My Mac, " + "Enable iCloud, Check Spelling While Typing, Correct Spelling Automatically, " + "Automatically Change Link Titles", + RESULTS_DIR) + z.close_menus(ax) # Escape closes the Settings window + + +# =========================================================================== +# ENABLEMENT / actionability — a menu item's `.enabled` reflects app state. +# Interactive: value (a specific enabled value) or transition (False→True as a +# row is created). Depth is backed by rb_reach_new_outline / rb_enter_first_row. +# =========================================================================== + +class TestMenuEnablement: + + @pytest.mark.rb(depth=0, jump_kind="value", expect="File▸New Outline is enabled") + def test_new_outline_item_enabled(self, ax): + it = z.find_menu_item(ax, "File", "New Outline") + assert it is not None, "File▸New Outline not found" + assert it.enabled is True, "File▸New Outline should be enabled at launch" + z.close_menus(ax) + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="Outline▸Complete disabled with no row, enabled after a row exists") + def test_complete_item_enablement(self, ax): + assert z.rb_reach_new_outline(ax), "New Outline did not open an editor" + it0 = z.find_menu_item(ax, "Outline", "Complete") + assert it0 is not None, "Outline▸Complete not found at Title focus (0 rows)" + before_enabled = bool(it0.enabled) + z.close_menus(ax) # close before tapping the editor body + assert z.rb_enter_first_row(ax), "could not create/focus the first row" + it1 = z.find_menu_item(ax, "Outline", "Complete") + assert it1 is not None, "Outline▸Complete not found after a row exists" + after_enabled = bool(it1.enabled) + z.close_menus(ax) + assert after_enabled, "Complete must be enabled once a row exists" + assert not before_enabled, ( + f"Outline▸Complete expected disabled(0 rows)→enabled(1 row); " + f"got enabled {before_enabled}→{after_enabled}") + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="Format▸Bold disabled at Title, enabled when editing a row") + def test_bold_item_enablement(self, ax): + assert z.rb_reach_new_outline(ax), "New Outline did not open an editor" + b_it = z.find_menu_item(ax, "Format", "Bold") + assert b_it is not None, "Format▸Bold not found at Title focus" + before_enabled = bool(b_it.enabled) + z.close_menus(ax) # close before tapping the editor body + assert z.rb_enter_first_row(ax), "could not create/focus the first row" + a_it = z.find_menu_item(ax, "Format", "Bold") + assert a_it is not None, "Format▸Bold not found after a row exists" + after_enabled = bool(a_it.enabled) + z.close_menus(ax) + assert after_enabled and not before_enabled, ( + f"Format▸Bold expected disabled(Title)→enabled(row); " + f"got enabled {before_enabled}→{after_enabled}") + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="Outline menu exposes Add Row Below which is enabled once a row exists") + def test_add_row_below_enabled_with_row(self, ax): + assert z.rb_reach_new_outline(ax), "New Outline did not open an editor" + assert z.rb_enter_first_row(ax), "could not create/focus the first row" + it = z.find_menu_item(ax, "Outline", "Add Row Below") + assert it is not None, "Outline▸Add Row Below not found" + assert it.enabled is True, "Add Row Below should be enabled with a current row" + z.close_menus(ax) + + +# =========================================================================== +# STRUCTURE — light sanity that a menu exposes a substantial item list. +# =========================================================================== + +class TestMenuStructure: + + @pytest.mark.rb(depth=1, jump_kind="none") + def test_menu_items_have_shortcuts(self, ax): + names = _menu_names(ax, "File") # opens File (nav → depth 1) + assert len(names) >= 10, ( + f"File menu should expose >=10 named items; got {len(names)}: {names}") + z.close_menus(ax) diff --git a/macos/vincode-io-zavala/tests/test_ax_states.py b/macos/vincode-io-zavala/tests/test_ax_states.py new file mode 100644 index 0000000000000000000000000000000000000000..7abaa01caa38825716ab3959e6c3e6b11ad5772f --- /dev/null +++ b/macos/vincode-io-zavala/tests/test_ax_states.py @@ -0,0 +1,169 @@ +"""test_ax_states.py — Zavala AX ENABLEMENT / CHECKED state + TRANSITION tests. + +Every test drives the RUNNING app ONLY through the `ax` fixture (fresh relaunch per +test, frontmost, window open) and the PORTABLE recipes in zavala_helpers (`z`) — no +bundle id, no install path, no `defaults`, no `open -a`, no direct AX handle — so the +SAME file scores the official app (must pass 100%) and any recreation (missing state +must fail). + +Scope = ENABLEMENT / CHECKED states and their TRANSITIONS (recon §1 toolbar +enablement, §3 Settings checkboxes, §4 editor Complete): + * Sidebar / New Outline are always enabled (no document needed). + * In a FRESH empty outline (Title focused, 0 rows) Bold/Italic/Link/Insert Image/ + Focus In are DISABLED; Share becomes enabled after New Outline. + * Once a row is created & focused, Bold/Italic/Link/Focus In flip False→True; + Move Left stays disabled for a lone top-level row. + * Outline ▸ Complete is disabled with no row, enabled with a row, and marks the + current row's topic text_area AXDescription == "Complete". + * Settings (⌘,) exposes on/off checkboxes; "Enable On My Mac" is checked. + +Deterministic clean slate: a fresh launch MAY restore a previous outline, so every +behavioral test creates its OWN New Outline first, then (when needed) enters the +first row — never assuming "no outline open at launch". +""" + +import os, time, pytest + +import zavala_helpers as z +import rb_testgen_kit as kit # noqa: F401 — depth/jump is DECLARED via @pytest.mark.rb + +RESULTS_DIR = os.environ.get("RESULTS_DIR", "") + +# The 10 named toolbar buttons, in order (recon §1). +TOOLBAR_NAMES = ["Sidebar", "New Outline", "Move Left", "Move Right", "Insert Image", + "Link", "Bold", "Italic", "Share", "Focus In"] +# Editing controls that are DISABLED in a fresh empty outline and enable with a row. +EDIT_CONTROLS = ["Bold", "Italic", "Link", "Insert Image", "Focus In"] + + +class TestAXStates: + # 1 ── always-on core buttons (no document needed) ─────────────────────── + @pytest.mark.rb(depth=0, jump_kind="value", + expect="Sidebar & New Outline enabled at launch") + def test_core_buttons_enabled(self, ax): + sidebar = z.toolbar_button(ax, "Sidebar") + new_outline = z.toolbar_button(ax, "New Outline") + assert sidebar is not None, "Sidebar toolbar button missing" + assert new_outline is not None, "New Outline toolbar button missing" + assert sidebar.enabled is True + assert new_outline.enabled is True + + # 2 ── editing controls disabled in a fresh EMPTY outline ──────────────── + @pytest.mark.rb(depth=1, jump_kind="value", + expect="in a fresh empty outline Bold/Italic/Link/Focus In are disabled") + def test_editing_disabled_on_empty_outline(self, ax): + assert z.rb_reach_new_outline(ax) + for name in EDIT_CONTROLS: + b = z.toolbar_button(ax, name) + assert b is not None, f"{name} toolbar button missing" + assert b.enabled is False, f"{name} should be disabled on an empty outline" + + # 3 ── Share enables once an outline is open ────────────────────────────── + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="Share False→True after New Outline") + def test_share_enables_after_new_outline(self, ax): + before_btn = z.toolbar_button(ax, "Share") + before = before_btn.enabled if before_btn else None # normally False (may be True if restored) + assert z.rb_reach_new_outline(ax) + after_btn = z.toolbar_button(ax, "Share") + assert after_btn is not None, "Share toolbar button missing" + assert after_btn.enabled is True, \ + f"Share should be enabled after New Outline (before={before})" + + # 4 ── Bold enables once a row is being edited ──────────────────────────── + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="Bold False→True when a row is edited") + def test_bold_transition(self, ax): + assert z.rb_reach_new_outline(ax) + assert z.toolbar_button(ax, "Bold").enabled is False + assert z.rb_enter_first_row(ax) + assert z.toolbar_button(ax, "Bold").enabled is True + z.screenshot_assert( + "state_toolbar_enabled", + "Zavala toolbar with Bold, Italic, Link, Focus In active while editing a row", + RESULTS_DIR) + + # 5 ── Italic enables once a row is being edited ────────────────────────── + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="Italic False→True when a row is edited") + def test_italic_transition(self, ax): + assert z.rb_reach_new_outline(ax) + assert z.toolbar_button(ax, "Italic").enabled is False + assert z.rb_enter_first_row(ax) + assert z.toolbar_button(ax, "Italic").enabled is True + + # 6 ── Focus In enables once a row is being edited ──────────────────────── + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="Focus In False→True when a row is edited") + def test_focus_in_transition(self, ax): + assert z.rb_reach_new_outline(ax) + assert z.toolbar_button(ax, "Focus In").enabled is False + assert z.rb_enter_first_row(ax) + assert z.toolbar_button(ax, "Focus In").enabled is True + + # 7 ── Link enables once a row is being edited ──────────────────────────── + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="Link False→True when a row is edited") + def test_link_transition(self, ax): + assert z.rb_reach_new_outline(ax) + assert z.toolbar_button(ax, "Link").enabled is False + assert z.rb_enter_first_row(ax) + assert z.toolbar_button(ax, "Link").enabled is True + + # 8 ── Complete flips the row's AXDescription to "Complete" ─────────────── + @pytest.mark.rb(depth=2, jump_kind="transition", + expect="row AXDescription '' → 'Complete' after Complete") + def test_complete_state_change(self, ax): + assert z.rb_reach_new_outline(ax) + assert z.rb_enter_first_row(ax) + assert not z.any_row_complete(ax), "no row should be Complete before the action" + z.complete_current_row(ax) + time.sleep(0.4) + assert z.any_row_complete(ax), \ + "row should report AXDescription 'Complete' after Outline ▸ Complete" + z.screenshot_assert( + "state_row_complete", + "Zavala editor after Complete: the current row's topic is marked done " + "(strikethrough), i.e. AXDescription == 'Complete'", + RESULTS_DIR) + + # 9 ── Outline▸Complete menu item enablement transition ─────────────────── + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="Outline▸Complete disabled with no row → enabled with a row") + def test_menu_complete_enablement(self, ax): + assert z.rb_reach_new_outline(ax) + item0 = z.find_menu_item(ax, "Outline", "Complete") + c0 = item0.enabled if item0 else None # empty outline: no current row → disabled + z.close_menus(ax) + assert z.rb_enter_first_row(ax) + item1 = z.find_menu_item(ax, "Outline", "Complete") + assert item1 is not None, "Outline ▸ Complete menu item missing" + c1 = item1.enabled + z.close_menus(ax) + assert c1 is True, "Complete should be enabled once a row exists" + # Prefer the full transition (disabled → enabled) when the 'before' is observable. + if c0 is not None: + assert c0 is False, f"Complete should be disabled on an empty outline (got {c0})" + + # 10 ── Settings checkboxes expose a 0/1 checked state ───────────────────── + + # 11 ── 'Enable On My Mac' is checked (local account active) ─────────────── + + # 12 ── every toolbar button reports a boolean enabled state ────────────── + @pytest.mark.rb(depth=0, jump_kind="value", + expect="all 10 toolbar buttons report a boolean enabled state") + def test_toolbar_enabled_readable(self, ax): + for name in TOOLBAR_NAMES: + b = z.toolbar_button(ax, name) + assert b is not None, f"{name} toolbar button missing" + assert b.enabled in (True, False), f"{name}.enabled not boolean: {b.enabled!r}" + + # 13 ── Move Left stays disabled for a lone top-level row ────────────────── + @pytest.mark.rb(depth=1, jump_kind="value", + expect="Move Left stays disabled for a lone top-level row") + def test_move_left_disabled_single_row(self, ax): + assert z.rb_reach_new_outline(ax) + assert z.rb_enter_first_row(ax) + b = z.toolbar_button(ax, "Move Left") + assert b is not None, "Move Left toolbar button missing" + assert b.enabled is False, "a lone top-level row cannot outdent → Move Left disabled" diff --git a/macos/vincode-io-zavala/tests/test_ax_structure.py b/macos/vincode-io-zavala/tests/test_ax_structure.py new file mode 100644 index 0000000000000000000000000000000000000000..6d6b8e1204e66de3314262859ce2f26a4042e4b8 --- /dev/null +++ b/macos/vincode-io-zavala/tests/test_ax_structure.py @@ -0,0 +1,149 @@ +"""test_ax_structure.py — AX STRUCTURE (presence/shape) tests for Zavala. + +This module OWNS the existence checks: it verifies the presence and shape of the +SPECIFIC named widgets catalogued in recon.md — the window titled "Zavala", the +AXToolbar and its 10 named buttons + the "Filter" menubutton, the 8 real menus +(Zavala/File/Edit/Format/View/History/Outline/Help — NOT the DEBUG-only "Debug"), +and the sidebar's "On My Mac" account header / "All" collection / search field — +plus role diversity and menu-bar breadth. + +Those flat-tree existence checks are BALANCED by three interactive structure-DELTA +tests that make the tree SHAPE change (and prove it): New Outline gives the editor +a Title text_area; the first row grows the text_area count by one; ⌘, reaches a +separate "Settings" window. So the structure is exercised, not merely read. + +Portable by contract: every widget is reached through the `ax` fixture and the +zavala_helpers (`z`) / rb_testgen_kit (`kit`) helpers only — no bundle id, no +install path, no `defaults`, no direct AX handle. The SAME file must pass on the +official app and fail on a recreation that is missing these widgets. Locators +match by AXTitle/AXDescription + AXRole (semantics), never by child index/path. +""" + +import os +import time + +import pytest + +import zavala_helpers as z +import rb_testgen_kit as kit + +RESULTS_DIR = os.environ.get("RESULTS_DIR", "") + + +class TestAppAndWindow: + """The app is AX-registered and presents its main window.""" + + @pytest.mark.rb(depth=0, jump_kind="none") + def test_gate_app_and_window(self, ax): + """GATE (existence): app is reachable via AX AND a window titled 'Zavala' exists.""" + assert z.main_window(ax) is not None, "no main window reachable via AX (app not registered?)" + wins = ax.find(role="window", name="Zavala", max_depth=2) + assert wins, "no window titled 'Zavala' found within max_depth=2" + + +class TestToolbar: + """The window toolbar and its 10 named buttons + Filter menubutton.""" + + + @pytest.mark.rb(depth=0, jump_kind="none") + def test_toolbar_has_named_buttons(self, ax): + """All 10 named toolbar buttons (recon §1) must be present, located by title+role.""" + expected = ["Sidebar", "New Outline", "Move Left", "Move Right", "Insert Image", + "Link", "Bold", "Italic", "Share", "Focus In"] + missing = [name for name in expected if z.toolbar_button(ax, name) is None] + z.screenshot_assert( + "structure_toolbar", + "Zavala toolbar shows icon buttons incl. New Outline, Bold, Italic, Link, " + "Share, Focus In, and a Filter menu button", + RESULTS_DIR) + assert not missing, f"toolbar missing named buttons: {missing}" + + @pytest.mark.rb(depth=0, jump_kind="none") + def test_filter_menubutton_exists(self, ax): + win = z.main_window(ax) + assert win is not None, "no main window to search for the Filter menubutton" + hits = ax.find(role="menubutton", name="Filter", root_id=win, max_depth=15) + assert hits, "no 'Filter' menubutton found in the window/toolbar" + + +class TestMenuBar: + """The real top-level menus and the overall menu-bar breadth.""" + + @pytest.mark.rb(depth=0, jump_kind="none") + def test_menu_bar_has_all_menus(self, ax): + """The 8 app menus must exist. 'Debug' is DEBUG-only (recon §2) and is NOT required.""" + menus = ["Zavala", "File", "Edit", "Format", "View", "History", "Outline", "Help"] + missing = [m for m in menus if z.menu_bar_item(ax, m) is None] + assert not missing, f"menu bar missing menus: {missing}" + + @pytest.mark.rb(depth=0, jump_kind="none") + def test_menu_bar_item_count(self, ax): + items = ax.find(role="menu_bar_item", max_depth=3) + assert len(items) >= 9, f"only {len(items)} menu_bar_items found (expected >= 9)" + + +class TestSidebar: + """The sidebar (Collections) account header, 'All' collection, and search field.""" + + @pytest.mark.rb(depth=0, jump_kind="none") + def test_sidebar_account_and_all(self, ax): + win = z.main_window(ax) + assert win is not None, "no main window to search the sidebar" + account = ax.find(role="button", name="On My Mac", root_id=win, max_depth=18) + assert account, "sidebar 'On My Mac' local-account header button not found" + all_lbl = ax.find(role="label", name="All", root_id=win, max_depth=18) + assert all_lbl, "sidebar 'All' collection label not found" + + @pytest.mark.rb(depth=0, jump_kind="none") + def test_sidebar_search_field(self, ax): + assert z.sidebar_search_field(ax) is not None, "no sidebar search text_field found" + + +class TestRoleDiversity: + """A properly structured app exposes many distinct AX roles.""" + + @pytest.mark.rb(depth=0, jump_kind="none") + def test_role_diversity(self, ax): + win = z.main_window(ax) + assert win is not None, "no main window to walk for role diversity" + elements = ax.find(root_id=win, max_results=400, max_depth=15) + roles = sorted({e.role for e in elements if e.role}) + assert len(roles) >= 7, f"only {len(roles)} distinct roles found: {roles}" + + +class TestStructureDeltas: + """Interactive tree-shape deltas (balance the existence checks): real nav each time.""" + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="editor gains a Title text_area after New Outline") + def test_new_outline_adds_editor_area(self, ax): + before = len(z.editor_text_areas(ax)) + assert z.rb_reach_new_outline(ax), "New Outline did not activate an outline editor" + time.sleep(0.3) + assert z.title_area(ax) is not None, ( + f"no Title text_area after New Outline (editor areas before={before})") + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="editor text_area count increases by 1 when first row created") + def test_first_row_grows_tree(self, ax): + assert z.rb_reach_new_outline(ax), "could not create a fresh outline" + n0 = len(z.editor_text_areas(ax)) + assert z.rb_enter_first_row(ax), "tapping the empty editor body did not create a first row" + time.sleep(0.3) + n1 = len(z.editor_text_areas(ax)) + assert n1 == n0 + 1, f"editor text_area count {n0} -> {n1} (expected +1)" + + @pytest.mark.rb(depth=1, jump_kind="reach", + expect="Settings window appears in the tree") + def test_settings_window_reachable(self, ax): + before = kit.rb_showing(ax) + settings = z.rb_reach_settings(ax) + assert settings is not None, "⌘, did not open a 'Settings' window" + after = kit.rb_showing(ax) + z.screenshot_assert( + "structure_settings", + "Zavala Settings window with a Color Palette popup and checkboxes like " + "Enable On My Mac / Check Spelling While Typing", + RESULTS_DIR) + assert kit.rb_reach(before, after, target="Settings"), ( + "Settings surface did not newly appear in the AX tree after ⌘,") diff --git a/macos/vincode-io-zavala/tests/test_ax_text.py b/macos/vincode-io-zavala/tests/test_ax_text.py new file mode 100644 index 0000000000000000000000000000000000000000..819d57dc817b88c93f5ecacacb8a879077b1c361 --- /dev/null +++ b/macos/vincode-io-zavala/tests/test_ax_text.py @@ -0,0 +1,174 @@ +"""test_ax_text.py — AX TEXT-CONTENT tests for the Zavala outliner (macOS Catalyst). + +Verifies SPECIFIC, static text exposed via AX (window title, sidebar labels, menu-item +labels, Settings labels, editor Title round-trip) against the golden model in recon.md. +The SAME file runs against the official app (must pass 100%) and any recreation (missing +text/labels must fail). + +PORTABLE by construction: every widget is reached through the `ax` fixture (fresh relaunch +per test, frontmost, window open — see conftest.py) and the proven recipes in +`zavala_helpers` (import as `z`). No hardcoded bundle id, container path, state seeding, +app-launch-by-name, absolute path, or direct AX-handle creation. + +Depth/jump is DECLARED per test with @pytest.mark.rb(...); depth>=1 tests are backed by a +real nav call (`z.open_menu` / `z.rb_reach_*`) so rb_audit_depth does not flag fake depth. +Dynamic text (relative timestamps like "9 minutes ago") is NEVER asserted on (recon §6). +""" + +import os +import time + +import pytest + +import zavala_helpers as z +import rb_testgen_kit as kit # noqa: F401 (kit marker convention; deployed next to tests) + +RESULTS_DIR = os.environ.get("RESULTS_DIR", "") + + +class TestWindowText: + """Top-level window text (recon §0/§1): the main window is titled 'Zavala'.""" + + @pytest.mark.rb(depth=0, jump_kind="value", expect="main window title is 'Zavala'") + def test_window_title(self, ax): + wins = ax.find(role="window", max_depth=2) + z.screenshot_assert( + "text_window_title", + "Zavala main outliner window is open; the window title reads exactly 'Zavala'.", + RESULTS_DIR, + ) + assert any((w.name or "") == "Zavala" for w in wins), \ + f"no window titled 'Zavala'; got {[w.name for w in wins]}" + + @pytest.mark.rb(depth=0, jump_kind="none") + def test_window_has_readable_text(self, ax): + # Existence check: the main window exposes several elements with readable text + # (sidebar 'On My Mac'/'All', search field, documents/editor). Keep as the single + # non-interactive test in this module. + win = z.main_window(ax) + assert win is not None + texts = ax.find_text_elements(root_id=win, max_results=30) + assert len(texts) >= 3, f"window exposed only {len(texts)} text element(s)" + + +class TestSidebarText: + """Sidebar Collections text (recon §1): the 'On My Mac' account + the 'All' collection.""" + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="sidebar shows the 'On My Mac' account") + def test_sidebar_account_label(self, ax): + win = z.main_window(ax) + assert win is not None + hits = ax.find(name="On My Mac", root_id=win, max_results=10, max_depth=18) + assert any(h.role in ("button", "label") for h in hits), \ + f"'On My Mac' not present as button/label; roles={[h.role for h in hits]}" + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="sidebar shows the 'All' collection") + def test_all_collection_label(self, ax): + hits = ax.find(role="label", name="All", max_depth=18) + assert len(hits) >= 1, "no label named 'All' in the sidebar" + + +class TestMenuLabels: + """Menu-bar item LABELS match Zavala's (recon §2). Each opens the menu (depth 1) via + z.open_menu — the designated nav call — then reads the item names and closes the menu.""" + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="File menu labels match Zavala's (New Outline, Import OPML…, Export, Print List…)") + def test_file_menu_labels(self, ax): + names = [i.name for i in z.open_menu(ax, "File") if i.name] + z.close_menus(ax) + expected = {"New Outline", "Open Quickly…", "Import OPML…", "Export", + "Print List…", "Get Info", "Sync"} + assert expected.issubset(set(names)), f"missing File items: {expected - set(names)}" + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="Outline menu labels include Add Row Below, Move Right, Complete, Add Note") + def test_outline_menu_labels(self, ax): + names = [i.name for i in z.open_menu(ax, "Outline") if i.name] + z.close_menus(ax) + expected = {"Add Row Above", "Add Row Below", "Add Row Inside", "Add Row Outside", + "Move Left", "Move Right", "Complete", "Add Note"} + assert expected.issubset(set(names)), f"missing Outline items: {expected - set(names)}" + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="Format menu labels are exactly Bold and Italic") + def test_format_menu_labels(self, ax): + names = [i.name for i in z.open_menu(ax, "Format") if i.name] + z.close_menus(ax) + assert "Bold" in names and "Italic" in names, f"Format items were {names}" + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="Zavala app menu shows About Zavala / Settings… / Quit Zavala") + def test_app_menu_labels(self, ax): + names = [i.name for i in z.open_menu(ax, "Zavala") if i.name] + z.close_menus(ax) + expected = {"About Zavala", "Settings…", "Quit Zavala"} + assert expected.issubset(set(names)), f"missing Zavala items: {expected - set(names)}" + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="Help menu shows Zavala Help / Community Discussion / Provide Feedback") + def test_help_menu_labels(self, ax): + names = [i.name for i in z.open_menu(ax, "Help") if i.name] + z.close_menus(ax) + expected = {"Zavala Help", "Community Discussion", "Provide Feedback"} + assert expected.issubset(set(names)), f"missing Help items: {expected - set(names)}" + + +class TestSettingsText: + """Settings-window text (recon §3): a separate 'Settings' window (⌘,) exposing the + 'Color Palette' label and the account/spelling checkbox labels.""" + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="Settings window shows 'Color Palette' and account/spelling checkbox labels") + def test_settings_labels(self, ax): + w = z.rb_reach_settings(ax) + assert w is not None, "Settings window did not open on ⌘," + names = [e.name for e in ax.find(root_id=w.id, max_results=60, max_depth=8) if e.name] + z.screenshot_assert( + "text_settings", + "Zavala Settings window listing 'Color Palette' and checkboxes including " + "'Enable On My Mac' and 'Check Spelling While Typing'.", + RESULTS_DIR, + ) + assert "Color Palette" in names, f"'Color Palette' not in Settings labels: {names}" + expected = {"Enable On My Mac", "Check Spelling While Typing", + "Automatically Change Link Titles"} + assert expected.issubset(set(names)), f"missing Settings checkboxes: {expected - set(names)}" + + +class TestEditorText: + """Editor / Documents text (recon §1/§4): a new outline shows a '(No Title)' entry and + the Title text_area reads back what was typed.""" + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="a new outline shows a '(No Title)' entry in the Documents list") + def test_untitled_document_label(self, ax): + assert z.rb_reach_new_outline(ax), "New Outline did not open an editor" + time.sleep(0.6) + z.screenshot_assert( + "text_untitled_document", + "Zavala Documents pane shows a freshly created outline row labeled '(No Title)'.", + RESULTS_DIR, + ) + labels = ax.find(role="label", max_results=80, max_depth=20) + assert any((l.name or "") == "(No Title)" for l in labels), \ + "no '(No Title)' document label after New Outline" + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="typed Title text is read back as 'My Notes'") + def test_title_text_readable(self, ax): + assert z.rb_reach_new_outline(ax), "New Outline did not open an editor" + ta = z.title_area(ax) + assert ta is not None, "no Title text_area in the editor" + z.set_text(ax, ta, "My Notes") + time.sleep(0.3) + z.screenshot_assert( + "text_title_readable", + "Zavala editor Title area displays the typed text 'My Notes'.", + RESULTS_DIR, + ) + ta2 = z.title_area(ax) + assert ta2 is not None and (ta2.value or "") == "My Notes", \ + f"Title read back as {getattr(ta2, 'value', None)!r}, expected 'My Notes'" diff --git a/macos/vincode-io-zavala/tests/testcase_counts.json b/macos/vincode-io-zavala/tests/testcase_counts.json new file mode 100644 index 0000000000000000000000000000000000000000..067e3af66d9b89a16ed76c3ff5e03447fff6b2fa --- /dev/null +++ b/macos/vincode-io-zavala/tests/testcase_counts.json @@ -0,0 +1,32 @@ +{ + "ax_total": 60, + "vlm_total": 11, + "ax_by_lane": { + "test_ax_computation.py": 13, + "test_ax_menus.py": 13, + "test_ax_states.py": 11, + "test_ax_structure.py": 11, + "test_ax_text.py": 12 + }, + "vlm_by_dir": { + "computation": 2, + "menus": 2, + "states": 1, + "structure": 2, + "text": 4 + }, + "vlm_names": [ + "computation_first_row.png", + "computation_title.png", + "menu_test_file_menu.png", + "menu_test_settings_opens.png", + "state_toolbar_enabled.png", + "structure_settings.png", + "structure_toolbar.png", + "text_settings.png", + "text_title_readable.png", + "text_untitled_document.png", + "text_window_title.png" + ], + "frozen_at": "stage2_finalize" +} \ No newline at end of file diff --git a/macos/vincode-io-zavala/tests/verifier_helpers.py b/macos/vincode-io-zavala/tests/verifier_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..ce369cdae8db3a7427890d1636f8f5a3201dbef1 --- /dev/null +++ b/macos/vincode-io-zavala/tests/verifier_helpers.py @@ -0,0 +1,753 @@ +""" +verifier_helpers.py — High-level AX testing patterns for macOS app verification. + +v6 core library. Encodes all robust testing patterns as reusable functions +so verifier agents call high-level APIs instead of building from scratch. + +Depends on: ax_helpers.py (AXHelper class) +""" + +import datetime +import os +import re +import signal +import subprocess +import time +from collections import Counter + +# --------------------------------------------------------------------------- +# Key codes (macOS virtual key codes) +# --------------------------------------------------------------------------- +KC_LEFT_ARROW = 123 +KC_RIGHT_ARROW = 124 +KC_UP_ARROW = 126 +KC_DOWN_ARROW = 125 +KC_SPACE = 49 +KC_RETURN = 36 +KC_TAB = 48 +KC_ESCAPE = 53 +KC_Q = 12 +KC_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": , "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)" + ) diff --git a/macos/vincode-io-zavala/tests/zavala_helpers.py b/macos/vincode-io-zavala/tests/zavala_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..c3269532538c4fad110ef5b562511ac8f5ffc4c5 --- /dev/null +++ b/macos/vincode-io-zavala/tests/zavala_helpers.py @@ -0,0 +1,302 @@ +"""zavala_helpers.py — proven, PORTABLE AX interaction recipes for the Zavala outliner. + +Every function takes the pytest `ax` fixture (an AXHelper) and drives the RUNNING app +only — no hardcoded install paths, no bundle ids, no app spawning, no direct AX handle +creation — so the SAME test file drives the official app AND any recreation. + +Navigation helpers are deliberately NAMED rb_reach_* / rb_enter_* (and `open_menu`) so +rb_testgen_kit.rb_audit_depth counts them as real surface crossings backing a declared +depth>=1 / jump_kind="reach". + +Discovered (and empirically verified on the official app) facts these encode: + * The main window is titled "Zavala"; the editor is a 3-pane split (sidebar / documents / + editor). Each outline row's topic — and the outline title — is an AX **text_area**. + text_area[0] is the Title; text_area[1..] are row topics. + * "New Outline" (toolbar button / File menu) creates a fresh empty outline (0 rows, Title + focused) and increments the sidebar "All" document count. + * Zavala creates the FIRST row lazily on a tap in the empty editor body (no keyboard + shortcut does it from the Title) — so rb_enter_first_row taps below the Title. + * A completed row's topic text_area reports AXDescription == "Complete". + * Settings opens in a separate window titled "Settings" (⌘,). +""" + +import json +import os +import re +import subprocess +import time + +import Quartz +from ApplicationServices import AXUIElementCopyAttributeValue + + +# ── low-level: clicks & keys ──────────────────────────────────────────────── + +def click_at(x, y): + """Left-click at absolute screen coordinates via CGEvent.""" + pt = Quartz.CGPointMake(x, y) + Quartz.CGEventPost(Quartz.kCGHIDEventTap, Quartz.CGEventCreateMouseEvent( + None, Quartz.kCGEventLeftMouseDown, pt, Quartz.kCGMouseButtonLeft)) + time.sleep(0.05) + Quartz.CGEventPost(Quartz.kCGHIDEventTap, Quartz.CGEventCreateMouseEvent( + None, Quartz.kCGEventLeftMouseUp, pt, Quartz.kCGMouseButtonLeft)) + time.sleep(0.6) + + +def keystroke(chars, using=None): + """Send a literal keystroke to the frontmost app (host launches Zavala frontmost).""" + mod = f' using {{{using}}}' if using else '' + subprocess.run( + ["osascript", "-e", + f'tell application "System Events" to keystroke "{chars}"{mod}'], + capture_output=True, timeout=5) + time.sleep(0.4) + + +def press_escape(): + subprocess.run(["osascript", "-e", + 'tell application "System Events" to key code 53'], + capture_output=True, timeout=3) + time.sleep(0.2) + + +def _rect(ax, el_id): + """(x, y, w, h) of an element from its AXPosition/AXSize, or None.""" + a = ax.get(el_id, ["AXPosition", "AXSize"]) + pm = re.search(r"x:([-\d.]+)\s+y:([-\d.]+)", str(a.get("AXPosition") or "")) + sm = re.search(r"w:([-\d.]+)\s+h:([-\d.]+)", str(a.get("AXSize") or "")) + if not pm or not sm: + return None + return (float(pm.group(1)), float(pm.group(2)), + float(sm.group(1)), float(sm.group(2))) + + +# ── window / widget accessors ─────────────────────────────────────────────── + +def main_window(ax): + """The main outliner window id (the one titled 'Zavala' / largest), or None.""" + win = ax.get_main_window() + if win: + return win + wins = ax.find(role="window", max_results=10, max_depth=1) + for w in wins: + if (w.name or "") == "Zavala": + return w.id + return wins[0].id if wins else None + + +def toolbar_buttons(ax): + win = main_window(ax) + return ax.find(role="button", root_id=win, max_results=80, max_depth=15) if win else [] + + +def toolbar_button(ax, name): + """The toolbar button whose AXTitle == name (e.g. 'New Outline', 'Bold'), or None.""" + for b in toolbar_buttons(ax): + if (b.name or "") == name: + return b + return None + + +def toolbar_button_names(ax): + return [b.name for b in toolbar_buttons(ax) if b.name] + + +def editor_text_areas(ax): + """All editor text_areas. [0] = outline Title; [1..] = row topics.""" + win = main_window(ax) + return ax.find(role="text_area", root_id=win, max_results=80, max_depth=24) if win else [] + + +def title_area(ax): + tas = editor_text_areas(ax) + return tas[0] if tas else None + + +def row_areas(ax): + """Row-topic text_areas only (everything after the Title).""" + return editor_text_areas(ax)[1:] + + +def all_count(ax): + """Document count shown on the sidebar 'All' collection (int), or None.""" + for lbl in ax.find(role="label", name="All", max_results=5, max_depth=18): + try: + return int(str(lbl.value).strip()) + except (TypeError, ValueError): + continue + return None + + +def sidebar_search_field(ax): + win = main_window(ax) + tfs = ax.find(role="text_field", root_id=win, max_results=10, max_depth=18) if win else [] + return tfs[0] if tfs else None + + +# ── menus ─────────────────────────────────────────────────────────────────── + +def menu_bar_item(ax, menu_name): + hits = ax.find(role="menu_bar_item", name=menu_name, max_results=1, max_depth=3) + return hits[0] if hits else None + + +def open_menu(ax, menu_name): + """Open a top-level menu (⌘-bar item) and return its menu_item children.""" + mbi = menu_bar_item(ax, menu_name) + if not mbi: + return [] + ax.action(mbi.id, "AXPress") + time.sleep(0.4) + return ax.find(role="menu_item", root_id=mbi.id, max_results=120, max_depth=3) + + +def menu_item_names(ax, menu_name): + return [i.name for i in open_menu(ax, menu_name) if i.name] + + +def submenu_item_names(ax, menu_name, submenu_name): + """Item names inside a submenu (e.g. File ▸ Export, Edit ▸ Transformations).""" + mbi = menu_bar_item(ax, menu_name) + if not mbi: + return [] + ax.action(mbi.id, "AXPress") + time.sleep(0.4) + for it in ax.find(role="menu_item", root_id=mbi.id, max_results=120, max_depth=4): + if it.name == submenu_name: + subs = ax.find(role="menu_item", root_id=it.id, max_results=60, max_depth=3) + # first item is the submenu's own title element; keep names != submenu_name + return [s.name for s in subs if s.name and s.name != submenu_name] + return [] + + +def find_menu_item(ax, menu_name, item_name): + """The AXElement for a specific menu item (opens the menu first), or None.""" + mbi = menu_bar_item(ax, menu_name) + if not mbi: + return None + ax.action(mbi.id, "AXPress") + time.sleep(0.4) + hits = ax.find(role="menu_item", name=item_name, root_id=mbi.id, + max_results=1, max_depth=4) + return hits[0] if hits else None + + +def invoke_menu_item(ax, menu_name, item_name): + """Open a menu and AXPress a named item. Returns True on success.""" + mbi = menu_bar_item(ax, menu_name) + if not mbi: + return False + ax.action(mbi.id, "AXPress") + time.sleep(0.4) + hits = ax.find(role="menu_item", name=item_name, root_id=mbi.id, + max_results=1, max_depth=4) + if not hits: + ax.action(mbi.id, "AXPress") # close the menu we opened + return False + ok = ax.action(hits[0].id, "AXPress") + time.sleep(0.6) + return ok + + +def close_menus(ax=None): + press_escape() + press_escape() + + +# ── navigation into deeper surfaces (named for rb_audit_depth) ────────────── + +def rb_reach_new_outline(ax): + """Create a new outline (toolbar 'New Outline'; fallback File ▸ New Outline). + Returns True once the outline editor is active (a Title text_area exists).""" + b = toolbar_button(ax, "New Outline") + if b: + ax.action(b.id, "AXPress") + else: + invoke_menu_item(ax, "File", "New Outline") + time.sleep(1.2) + return title_area(ax) is not None + + +def rb_enter_first_row(ax): + """Create + focus the first row by tapping the empty editor body just below the + Title (Zavala makes the first row lazily on tap). Returns True if a new row + text_area appeared.""" + t = title_area(ax) + if not t: + return False + before = len(editor_text_areas(ax)) + r = _rect(ax, t.id) + if not r: + return False + x, y, w, h = r + click_at(x + 40, y + h + 130) + time.sleep(0.6) + return len(editor_text_areas(ax)) > before + + +def rb_reach_settings(ax): + """Open Settings via ⌘, . Returns the 'Settings' window element, or None.""" + keystroke(",", using="command down") + time.sleep(1.2) + for w in ax.find(role="window", max_results=10, max_depth=1): + if (w.name or "") == "Settings": + return w + return None + + +# ── outline row operations ────────────────────────────────────────────────── + +def set_text(ax, el, text): + """Set an editor text_area's value via AX (no keyboard focus needed).""" + el_id = el.id if hasattr(el, "id") else el + return ax.set_value(el_id, text) + + +def add_row_below(ax): + """Outline ▸ Add Row Below (needs a current row).""" + return invoke_menu_item(ax, "Outline", "Add Row Below") + + +def complete_current_row(ax): + """Outline ▸ Complete on the current row.""" + return invoke_menu_item(ax, "Outline", "Complete") + + +def row_descriptions(ax): + """AXDescription of every editor text_area (a completed row reports 'Complete').""" + out = [] + for t in editor_text_areas(ax): + err, desc = AXUIElementCopyAttributeValue(t.ref, "AXDescription", None) + out.append(str(desc) if desc else "") + return out + + +def any_row_complete(ax): + return any(d == "Complete" for d in row_descriptions(ax)) + + +# ── screenshot assertion (VLM ground truth) ───────────────────────────────── + +def screenshot_assert(test_name, description, results_dir): + """Capture a screenshot and record a VISUAL assertion for VLM evaluation.""" + if not results_dir: + return + 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 + af = os.path.join(ss_dir, "assertions.json") + data = {} + if os.path.exists(af): + try: + with open(af) as f: + data = json.load(f) + except Exception: + data = {} + data[f"{test_name}.png"] = description + with open(af, "w") as f: + json.dump(data, f, indent=2) diff --git a/macos/vincode-io-zavala/vlm_assertions.json b/macos/vincode-io-zavala/vlm_assertions.json new file mode 100644 index 0000000000000000000000000000000000000000..c46b661d22a8700eeb2ed09930cbc9ad3ada6292 --- /dev/null +++ b/macos/vincode-io-zavala/vlm_assertions.json @@ -0,0 +1,166 @@ +{ + "schema_version": 2, + "instance_id": "macos/vincode-io-zavala", + "grading": { + "mode": "deferred", + "model": null, + "scored_separately": true + }, + "totals": { + "assertions": 11, + "with_verdict": 0, + "calibrated": 0, + "usable": null, + "scored_records": 0, + "unbacked_records": 0 + }, + "assertions": [ + { + "id": "computation_title.png", + "screenshot": "computation_title.png", + "assertion": "Zavala editor with the outline title set to 'Groceries'. The title text shows at the top of the editor pane; the row area below is still empty. The three-pane layout (sidebar, documents, editor) and toolbar are visible.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "computation_title.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "computation_first_row.png", + "screenshot": "computation_first_row.png", + "assertion": "Zavala outline whose first row topic reads 'Buy Milk', shown beneath the (empty) outline title. Exactly one row is present in the editor.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "computation_first_row.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "menu_test_file_menu.png", + "screenshot": "menu_test_file_menu.png", + "assertion": "File menu is open showing items: New Outline, New Main Window, Open Quickly…, Close, Sync, Get Info, Import OPML…, Export, Print Doc…, Print List…", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "menu_test_file_menu.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "menu_test_settings_opens.png", + "screenshot": "menu_test_settings_opens.png", + "assertion": "Settings window is visible showing a Color Palette popup (Automatic) and preference checkboxes: Use Main Window as Default, Enable On My Mac, Enable iCloud, Check Spelling While Typing, Correct Spelling Automatically, Automatically Change Link Titles", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "menu_test_settings_opens.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "state_toolbar_enabled.png", + "screenshot": "state_toolbar_enabled.png", + "assertion": "Zavala toolbar with Bold, Italic, Link, Focus In active while editing a row", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "state_toolbar_enabled.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "structure_toolbar.png", + "screenshot": "structure_toolbar.png", + "assertion": "Zavala toolbar shows icon buttons incl. New Outline, Bold, Italic, Link, Share, Focus In, and a Filter menu button", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "structure_toolbar.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "structure_settings.png", + "screenshot": "structure_settings.png", + "assertion": "Zavala Settings window with a Color Palette popup and checkboxes like Enable On My Mac / Check Spelling While Typing", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "structure_settings.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "text_settings.png", + "screenshot": "text_settings.png", + "assertion": "Zavala Settings window listing 'Color Palette' and checkboxes including 'Enable On My Mac' and 'Check Spelling While Typing'.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "text_settings.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "text_untitled_document.png", + "screenshot": "text_untitled_document.png", + "assertion": "Zavala Documents pane shows a freshly created outline row labeled '(No Title)'.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "text_untitled_document.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "text_title_readable.png", + "screenshot": "text_title_readable.png", + "assertion": "Zavala editor Title area displays the typed text 'My Notes'.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "text_title_readable.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "text_window_title.png", + "screenshot": "text_window_title.png", + "assertion": "Zavala main outliner window is open; the window title reads exactly 'Zavala'.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "text_window_title.png", + "rigor": null, + "verdict": null, + "calibration": null + } + ], + "merged_from_files": 5, + "source_shapes": { + "dict_str": 11 + } +} \ No newline at end of file diff --git a/macos/wealthfolio-wealthfolio/LICENSE b/macos/wealthfolio-wealthfolio/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..5b7f4426568d2feb26aab0d01688f3c12225c419 --- /dev/null +++ b/macos/wealthfolio-wealthfolio/LICENSE @@ -0,0 +1,135 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + +Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy +and distribute verbatim copies of this license document, but changing it is not allowed. + +This version of the GNU Lesser General Public License incorporates the terms and conditions of +version 3 of the GNU General Public License, supplemented by the additional permissions listed +below. + +0. Additional Definitions. + +As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the +"GNU GPL" refers to version 3 of the GNU General Public License. + +"The Library" refers to a covered work governed by this License, other than an Application or a +Combined Work as defined below. + +An "Application" is any work that makes use of an interface provided by the Library, but which is +not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed +a mode of using an interface provided by the Library. + +A "Combined Work" is a work produced by combining or linking an Application with the Library. The +particular version of the Library with which the Combined Work was made is also called the "Linked +Version". + +The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the +Combined Work, excluding any source code for portions of the Combined Work that, considered in +isolation, are based on the Application, and not on the Linked Version. + +The "Corresponding Application Code" for a Combined Work means the object code and/or source code +for the Application, including any data and utility programs needed for reproducing the Combined +Work from the Application, but excluding the System Libraries of the Combined Work. + +1. Exception to Section 3 of the GNU GPL. + +You may convey a covered work under sections 3 and 4 of this License without being bound by section +3 of the GNU GPL. + +2. Conveying Modified Versions. + +If you modify a copy of the Library, and, in your modifications, a facility refers to a function or +data to be supplied by an Application that uses the facility (other than as an argument passed when +the facility is invoked), then you may convey a copy of the modified version: + +a) under this License, provided that you make a good faith effort to ensure that, in the event an +Application does not supply the function or data, the facility still operates, and performs whatever +part of its purpose remains meaningful, or + +b) under the GNU GPL, with none of the additional permissions of this License applicable to that +copy. + +3. Object Code Incorporating Material from Library Header Files. + +The object code form of an Application may incorporate material from a header file that is part of +the Library. You may convey such object code under terms of your choice, provided that, if the +incorporated material is not limited to numerical parameters, data structure layouts and accessors, +or small macros, inline functions and templates (ten or fewer lines in length), you do both of the +following: + +a) Give prominent notice with each copy of the object code that the Library is used in it and that +the Library and its use are covered by this License. + +b) Accompany the object code with a copy of the GNU GPL and this license document. + +4. Combined Works. + +You may convey a Combined Work under terms of your choice that, taken together, effectively do not +restrict modification of the portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of the following: + +a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that +the Library and its use are covered by this License. + +b) Accompany the Combined Work with a copy of the GNU GPL and this license document. + +c) For a Combined Work that displays copyright notices during execution, include the copyright +notice for the Library among these notices, as well as a reference directing the user to the copies +of the GNU GPL and this license document. + +d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + +e) Provide Installation Information, but only if you would otherwise be required to provide such +information under section 6 of the GNU GPL, and only to the extent that such information is +necessary to install and execute a modified version of the Combined Work produced by recombining or +relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the +Installation Information must accompany the Minimal Corresponding Source and Corresponding +Application Code. If you use option 4d1, you must provide the Installation Information in the manner +specified by section 6 of the GNU GPL for conveying Corresponding Source.) + +5. Combined Libraries. + +You may place library facilities that are a work based on the Library side by side in a single +library together with other library facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your choice, if you do both of the +following: + +a) Accompany the combined library with a copy of the same work based on the Library, uncombined with +any other library facilities, conveyed under the terms of this License. + +b) Give prominent notice with the combined library that part of it is a work based on the Library, +and explaining where to find the accompanying uncombined form of the same work. + +6. Revised Versions of the GNU Lesser General Public License. + +The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General +Public License from time to time. Such new versions will be similar in spirit to the present +version, but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library as you received it specifies +that a certain numbered version of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and conditions either of that published +version or of any later version published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser General Public License, you may +choose any version of the GNU Lesser General Public License ever published by the Free Software +Foundation. + +If the Library as you received it specifies that a proxy can decide whether future versions of the +GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any +version is permanent authorization for you to choose that version for the Library. diff --git a/macos/wealthfolio-wealthfolio/instance.json b/macos/wealthfolio-wealthfolio/instance.json new file mode 100644 index 0000000000000000000000000000000000000000..c659bef726c3d9ed954ae85f0debdca2799436ab --- /dev/null +++ b/macos/wealthfolio-wealthfolio/instance.json @@ -0,0 +1,10 @@ +{ + "schema_version": 1, + "instance_id": "macos/wealthfolio-wealthfolio", + "platform": "macos", + "repo": "https://github.com/wealthfolio/wealthfolio", + "commit": "3929a961631eda965fcb61e7c700258885fc6bc1", + "patches": [], + "package": null, + "license": null +} \ No newline at end of file diff --git a/macos/wealthfolio-wealthfolio/reference/build.sh b/macos/wealthfolio-wealthfolio/reference/build.sh new file mode 100644 index 0000000000000000000000000000000000000000..7ade8018e0a88190ca3ab47824c680d08330c401 --- /dev/null +++ b/macos/wealthfolio-wealthfolio/reference/build.sh @@ -0,0 +1,154 @@ +#!/usr/bin/env bash +# +# build.sh — reproducible from-scratch build for Wealthfolio (Tauri v1 desktop app) +# +# Frontend : React + Vite + TypeScript (pnpm) +# Backend : Rust (Tauri 1.7.2, workspace crate wealthfolio_core) +# Output : Wealthfolio.app (macOS .app bundle) +# +# The script is fully self-contained: on a fresh `git clone` into which only +# build.sh (and launch.sh) have been copied, `bash build.sh` produces the app. +# Every source change is applied inline (git apply) and every generated config +# file is written inline (heredoc). All paths derive from the script location. +# +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd "$SCRIPT_DIR" + +echo "==> Wealthfolio build starting in: $SCRIPT_DIR" + +# --------------------------------------------------------------------------- +# 1. Toolchain: Rust (rustup), Node.js, pnpm — installed idempotently +# --------------------------------------------------------------------------- + +# --- Rust / Cargo (Tauri backend) --- +if ! command -v cargo >/dev/null 2>&1; then + # rustup installs to $CARGO_HOME (default $HOME/.cargo); source its env if present. + if [ -f "${CARGO_HOME:-$HOME/.cargo}/env" ]; then + # shellcheck disable=SC1090 + . "${CARGO_HOME:-$HOME/.cargo}/env" + fi +fi +if ! command -v cargo >/dev/null 2>&1; then + echo "==> Installing Rust toolchain via rustup..." + curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs \ + | sh -s -- -y --profile minimal --default-toolchain stable + # shellcheck disable=SC1090 + . "${CARGO_HOME:-$HOME/.cargo}/env" +fi +export PATH="${CARGO_HOME:-$HOME/.cargo}/bin:$PATH" +echo "==> Using $(cargo --version)" + +# --- Node.js --- +if ! command -v node >/dev/null 2>&1; then + if command -v brew >/dev/null 2>&1; then + echo "==> Installing Node.js via Homebrew..." + brew install node + else + echo "ERROR: node not found and Homebrew is unavailable." >&2 + exit 1 + fi +fi +echo "==> Using node $(node --version)" + +# --- pnpm (package manager used by this project) --- +if ! command -v pnpm >/dev/null 2>&1; then + echo "==> Installing pnpm..." + if command -v corepack >/dev/null 2>&1; then + corepack enable pnpm 2>/dev/null || npm install -g pnpm@11.5.2 + else + npm install -g pnpm@11.5.2 + fi +fi +echo "==> Using pnpm $(pnpm --version)" + +# macOS: force an unsigned (ad-hoc) build — never attempt Apple code signing. +unset APPLE_SIGNING_IDENTITY APPLE_CERTIFICATE APPLE_CERTIFICATE_PASSWORD \ + APPLE_ID APPLE_PASSWORD APPLE_TEAM_ID 2>/dev/null || true + +# --------------------------------------------------------------------------- +# 2. Generated config: pnpm-workspace.yaml +# pnpm v10+ blocks package build scripts by default and `pnpm install` +# exits non-zero while any are un-approved. Vite needs esbuild's postinstall +# to materialize its native binary, so we explicitly allow that one build. +# --------------------------------------------------------------------------- +echo "==> Writing pnpm-workspace.yaml (allow esbuild build script)" +cat > "$SCRIPT_DIR/pnpm-workspace.yaml" <<'YAML' +onlyBuiltDependencies: + - esbuild +allowBuilds: + esbuild: true +YAML + +# --------------------------------------------------------------------------- +# 3. Source patch: disable the Tauri auto-updater +# tauri.conf.json ships with `updater.active: true` and a public key. During +# bundling the CLI then tries to sign the update artifact and fails with +# "A public key has been found, but no private key" unless TAURI_PRIVATE_KEY +# is set. We do not ship a signing key, so disable the updater. (The Tauri +# CLI also auto-removes the now-unused `updater` Cargo feature — no extra +# patch needed for that.) Applied idempotently. +# --------------------------------------------------------------------------- +echo "==> Disabling Tauri updater in src-tauri/tauri.conf.json" +UPDATER_PATCH=$(cat <<'PATCH' +diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json +--- a/src-tauri/tauri.conf.json ++++ b/src-tauri/tauri.conf.json +@@ -61,7 +61,7 @@ + } + ], + "updater": { +- "active": true, ++ "active": false, + "endpoints": [ + "https://wealthfolio.app/releases/{{target}}/{{arch}}/{{current_version}}" + ], +PATCH +) +if printf '%s\n' "$UPDATER_PATCH" | git apply --reverse --check - 2>/dev/null; then + echo " [patch] updater already disabled — skipping" +elif printf '%s\n' "$UPDATER_PATCH" | git apply - 2>/dev/null; then + echo " [patch] Tauri updater disabled" +elif grep -q '"active": false' "$SCRIPT_DIR/src-tauri/tauri.conf.json" 2>/dev/null; then + echo " [patch] updater appears already disabled — skipping" +else + echo " [patch] ERROR: could not disable the Tauri updater" >&2 + exit 1 +fi + +# --------------------------------------------------------------------------- +# 4. Install frontend dependencies +# --------------------------------------------------------------------------- +echo "==> Installing frontend dependencies (pnpm install)" +pnpm install + +# --------------------------------------------------------------------------- +# 5. Build the app (frontend build runs automatically via beforeBuildCommand). +# Native target for the host arch; output lands in +# src-tauri/target/release/bundle/macos/Wealthfolio.app +# --------------------------------------------------------------------------- +echo "==> Building Wealthfolio (pnpm tauri build)" +pnpm tauri build + +# --------------------------------------------------------------------------- +# 6. Publish the .app bundle to the output directory +# --------------------------------------------------------------------------- +APP_SRC="$SCRIPT_DIR/src-tauri/target/release/bundle/macos/Wealthfolio.app" +if [ ! -d "$APP_SRC" ]; then + echo "ERROR: expected bundle not found at $APP_SRC" >&2 + exit 1 +fi + +OUT_DIR="${APP_OUTPUT_DIR:-$SCRIPT_DIR}" +mkdir -p "$OUT_DIR" +# Only copy if the destination differs from the source location. +if [ "$(cd "$OUT_DIR" && pwd)" != "$(cd "$(dirname "$APP_SRC")" && pwd)" ]; then + rm -rf "$OUT_DIR/Wealthfolio.app" + cp -R "$APP_SRC" "$OUT_DIR/" +fi + +echo "" +echo "==> BUILD SUCCESSFUL" +echo " Bundle : $APP_SRC" +echo " Copied : $OUT_DIR/Wealthfolio.app" diff --git a/macos/wealthfolio-wealthfolio/reference/launch.sh b/macos/wealthfolio-wealthfolio/reference/launch.sh new file mode 100644 index 0000000000000000000000000000000000000000..07c7673482a05890bec128222c54690820c8e209 --- /dev/null +++ b/macos/wealthfolio-wealthfolio/reference/launch.sh @@ -0,0 +1,40 @@ +#!/usr/bin/env bash +# +# launch.sh — start the Wealthfolio desktop app. +# +# Works standalone (build.sh need not have been sourced). Locates the built +# .app relative to this script and launches it. Any arguments are forwarded +# to the application. +# +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +OUT_DIR="${APP_OUTPUT_DIR:-$SCRIPT_DIR}" + +# Search the likely locations, in order of preference. +APP="" +for candidate in \ + "$OUT_DIR/Wealthfolio.app" \ + "$SCRIPT_DIR/Wealthfolio.app" \ + "$SCRIPT_DIR/src-tauri/target/release/bundle/macos/Wealthfolio.app"; do + if [ -d "$candidate" ]; then + APP="$candidate" + break + fi +done + +if [ -z "$APP" ]; then + echo "ERROR: Wealthfolio.app not found. Run ./build.sh first." >&2 + exit 1 +fi + +echo "==> Launching $APP" + +# A Tauri .app is self-contained (WebKit is a system framework, the Rust +# binary is statically linked) — no DYLD_*/plugin path setup is required. +# Use `open -W` so the launcher blocks until the app exits. +if [ "$#" -gt 0 ]; then + exec open -W "$APP" --args "$@" +else + exec open -W "$APP" +fi diff --git a/macos/wealthfolio-wealthfolio/tests/ax_helpers.py b/macos/wealthfolio-wealthfolio/tests/ax_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..2418d7b8c75891c2d08906848d6a36517cb98135 --- /dev/null +++ b/macos/wealthfolio-wealthfolio/tests/ax_helpers.py @@ -0,0 +1,849 @@ +import os +import re +import time +import warnings +import subprocess +from dataclasses import dataclass, field +from typing import Optional +from 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", +} + + +@dataclass +class 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 None diff --git a/macos/wealthfolio-wealthfolio/tests/conftest.py b/macos/wealthfolio-wealthfolio/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..21a9b7debd04c0633d77a60d8269102790a13e84 --- /dev/null +++ b/macos/wealthfolio-wealthfolio/tests/conftest.py @@ -0,0 +1,584 @@ +""" +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 json +import os +import signal +import subprocess +import tempfile +import 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 _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 ` whose ARGUMENT merely contains the bundle path. + + A running .app's argv0 is /Contents/MacOS/, so we require that inner + executable path. The old bare-substring test (`app_path in args`) also matched the + lingering `open -W ` 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 == /Contents/MacOS/. + 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 ` 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//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//... — 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.fixture +def app_process(app_path): + pid = _launch_app(app_path) + yield pid + _kill_pid(pid) + + +@pytest.fixture +def 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.fixture +def 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")) diff --git a/macos/wealthfolio-wealthfolio/tests/rb_testgen_kit.py b/macos/wealthfolio-wealthfolio/tests/rb_testgen_kit.py new file mode 100644 index 0000000000000000000000000000000000000000..ccbbdd3c6136513161c133fbb4cefcfb0386d55c --- /dev/null +++ b/macos/wealthfolio-wealthfolio/tests/rb_testgen_kit.py @@ -0,0 +1,575 @@ +#!/usr/bin/env python3 +"""RB TestGen Kit (macOS/AX port of the Linux v7.5 kit) — a test's NAVIGATION +DEPTH and JUMP RIGOR are DECLARED (not inferred), uniformly recorded, and +self-auditable. + +DIFFERENCE FROM LINUX: macOS tests are **pytest** (methods on Test* classes taking +the `ax` fixture, plain asserts) — NOT standalone scripts calling R.record(). So the +DECLARATION is a pytest marker on the test method: + + import rb_testgen_kit as kit + + @pytest.mark.rb(depth=1, jump_kind="reach", expect="Preferences window visible") + def test_prefs_opens(self, ax_with_reset): + before = kit.rb_showing(ax_with_reset) + helpers.rb_reach_prefs(ax_with_reset) # a nav helper you name rb_reach_* / rb_enter_* + after = kit.rb_showing(ax_with_reset) + assert kit.rb_reach(before, after, target="Preferences", source="menu bar") + +conftest.py's pytest_runtest_makereport hook reads the marker + the test outcome and +writes {name, passed, depth, jump_kind, tier, expect} so the runner can fold it into +_results.json. The audits below then read those records (+ the test SOURCE). + +jump_kind (verbatim strings — the audit/stats key off them): + "none" no trigger; existence/structure only -> tier 0 + "liveness" only "did not crash / still alive" -> tier 1 (weak; avoid) + "reach" a real surface jump: the TARGET surface's element + APPEARED and the SOURCE surface's element DISAPPEARED -> tier 2 + "transition" a state flip (CHECKED/ENABLED/mode) before->after -> tier 2 + "value" a specific expected value/content was asserted -> tier 3 + +DEPTH is the number of surfaces crossed before the assertion (0 = home/first screen, +1 = one dialog/panel/submenu, 2+ = deeper). A flat-tree read of a deep element is +depth 0 — depth counts surfaces the test actually navigated through. + +REACH PROOF (so "reach" cannot be faked by reading a flat tree): + before = rb_showing(ax) + + 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('')" + python3 -c "import rb_testgen_kit as k; k.rb_lint('')" + python3 -c "import rb_testgen_kit as k; k.rb_lint_sources('')" + python3 -c "import rb_testgen_kit as k; k.rb_audit_depth('','')" +""" +from __future__ import annotations + +import ast +import glob +import json +import os +import re + +JUMP_KINDS = {"none": 0, "liveness": 1, "reach": 2, "transition": 2, "value": 3} + +# Double-axis quota TARGETS (fractions) — goals rb_audit REPORTS, NOT a hard gate. +QUOTAS = { + "existence_max": 0.30, # jump_kind=="none" share of ALL tests + "interactive_min": 0.60, # reach|transition|value share of ALL tests + "depth_ge1_min": 0.40, # depth>=1 share of INTERACTIVE tests + "depth_ge2_min": 0.10, # depth>=2 share of INTERACTIVE tests + "value_min": 0.25, # jump_kind=="value" share of INTERACTIVE tests +} + +# Depth family: a test "crosses a surface" iff it calls a member of the depth family. +# macOS accepts BOTH the naming convention rb_enter_*/rb_reach_* (write your own nav +# helper and NAME it so) AND the existing verifier_helpers/ax_helpers navigation +# functions (whitelist below) — so tests can reuse the mature reveal/navigate helpers. +DEPTH_FWD_RE = re.compile(r"^rb_(enter|reach)[a-z0-9_]*$") +DEPTH_BACK_RE = re.compile(r"^rb_back[a-z0-9_]*$") +# verifier_helpers / ax_helpers navigation functions that OPEN or move to a new surface. +FWD_WHITELIST = { + "ensure_ui_visible", "ensure_panel_open", "open_actions_menu", "open_menu", + "open_settings", "open_preferences", "open_dialog", "open_panel", "open_window", + "navigate_month", "navigate", "switch_tab", "switch_mode", "switch_page", + "select_tab", "reveal_window", "show_panel", "show_menu", +} +BACK_WHITELIST = { + "dismiss_menus", "dismiss_panel", "dismiss_any_dialog", "close_panel", + "close_window", "go_back", +} +# pytest fixtures that themselves navigate into a surface during setup (so a test taking +# one legitimately has depth>=1 without a nav call in its own body). `ax` does NOT navigate. +_NAV_FIXTURES = {"ax_with_reset", "open_panel"} +# MEASURED-TIER verdict families (ported from keliang): a tier2/3 jump_kind must be BACKED +# by its verdict function — transition->rb_flip*, value->rb_value*, reach->rb_reach* — whose +# bool result is the test's assertion. Self-named wrappers count by prefix. +TIER_FLIP_RE = re.compile(r"^rb_flip[a-z0-9_]*$") +TIER_VALUE_RE = re.compile(r"^rb_value[a-z0-9_]*$") +_JK_FAMILY = {"transition": "flip", "value": "value", "reach": "reach"} +# normalize plural (v73prep) / singular module names so a JSON module ("button") and a +# file stem ("buttons") join. +_MODULE_ALIAS = {"menus": "menu", "buttons": "button", "states": "state", + "structures": "structure", "texts": "text", + "computations": "computation", "workflows": "workflow"} + +_DEPTH = 0 # module-global surface counter for rb_enter/rb_back + + +def tier_of(jump_kind: str) -> int: + return JUMP_KINDS.get(jump_kind, 2) + + +def rb_reset_depth() -> None: + global _DEPTH + _DEPTH = 0 + + +def rb_enter(_surface: str = "") -> int: + """Call right after your test navigates into a new surface (dialog/panel/submenu).""" + global _DEPTH + _DEPTH += 1 + return _DEPTH + + +def rb_back() -> int: + global _DEPTH + _DEPTH = max(0, _DEPTH - 1) + return _DEPTH + + +def _walk_tree_nodes(node, out, seen): + """Yield 'role|name' for a macOS AXHelper.tree() dict node (+children).""" + if not isinstance(node, dict) or seen[0] >= 8000: + return + seen[0] += 1 + role = str(node.get("role") or "") + name = str(node.get("name") or node.get("value") or "") + if role or name: + out.add(f"{role}|{name}") + for c in (node.get("children") or []): + _walk_tree_nodes(c, out, seen) + + +def rb_showing(ax, max_depth: int = 12) -> set: + """Snapshot the currently-reachable AX subtree under the app as {"role|name"}. + macOS AX has no AT-SPI SHOWING/VISIBLE state, so we approximate "showing" by the + live AX tree (AXChildren) the app currently exposes — a new window/sheet/popover + adds its elements; a dismissed one removes them. Feed before+after a trigger to + rb_reach() so a 'reach' test proves a REAL surface change, not a flat-tree read. + Safe no-op (empty set) if `ax` cannot produce a tree.""" + out: set = set() + try: + tree = ax.tree(max_depth=max_depth) # AXHelper.tree() -> nested dict + except Exception: + return out + _walk_tree_nodes(tree, out, [0]) + return out + + +def rb_reach(before, after, target: str, source: str | None = None) -> bool: + """True-jump verdict: the TARGET surface's discriminating element newly APPEARED + AND (if given) the SOURCE surface's discriminating element DISAPPEARED. This is + what separates a real surface jump from reading an element that was always there.""" + before = set(before or []) + after = set(after or []) + t = target.lower() + appeared = any(t in k.lower() for k in (after - before)) + if source is None: + return appeared + s = source.lower() + src_before = any(s in k.lower() for k in before) + src_after = any(s in k.lower() for k in after) + return appeared and src_before and not src_after + + +def rb_flip(before, after, expect: str = "") -> bool: + """In-page STATE-FLIP verdict (tier2 `transition`): the observed state actually CHANGED + before->after (a CHECKED/ENABLED/mode/selection value read the two times). Pass its bool + as the test's assertion. Does NOT touch depth — an in-page flip is depth 0 unless you + navigated a surface to reach the control. You MAY write your own `rb_flip_()` 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_()` 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 | " + "{audit_depth|audit_tier} [results_dir]}") diff --git a/macos/wealthfolio-wealthfolio/tests/requirements.txt b/macos/wealthfolio-wealthfolio/tests/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..feef67ce2aadbaa26d12e6b01cff7b8ce89ecb5c --- /dev/null +++ b/macos/wealthfolio-wealthfolio/tests/requirements.txt @@ -0,0 +1,3 @@ +pytest +pytest-check +pyobjc diff --git a/macos/wealthfolio-wealthfolio/tests/test_ax_buttons.py b/macos/wealthfolio-wealthfolio/tests/test_ax_buttons.py new file mode 100644 index 0000000000000000000000000000000000000000..554795461bd25a8fd332793af9bc3b5e3c1f7000 --- /dev/null +++ b/macos/wealthfolio-wealthfolio/tests/test_ax_buttons.py @@ -0,0 +1,756 @@ +"""test_ax_buttons.py — AX button/press-target behaviour for Wealthfolio (Tauri v1 + WebKit). + +Every test asserts a CONSEQUENCE recorded in recon `## BUTTONS` / `## TEXT` +({trigger -> effect}), never "the element exists" or "it did not crash". + +Source of truth: verifier/recon.md. Coverage map: + B1/B2 button 'Expand Sidebar' / 'Collapse Sidebar' -> label flip + nav-link width 52->172 + B3 button 'Add account' (Accounts header) -> Add Account modal appears + B4 button 'Add an account' (empty placeholder) -> the SAME modal (2nd entry point) + B5 button 'Close' (modal x) -> modal dismissed, accounts page back + B6 popup 'Cancel' (modal footer, AXPopUpButton) -> modal dismissed, accounts page back + B7/B8/B9 button 'Save', button 'Add Account' (submit), window chrome buttons + -> EXISTENCE + enabled ONLY. Pressing them writes the SQLite DB / closes the + window (recon `## DO-NOT-TOUCH`) so they are NEVER pressed here. + the app's other press targets: the onboarding step links, "Let's get started", the + unnamed sidebar logo link and the gated sidebar nav links. + +NOTE ON TOOLBARS: this app exposes NO `AXToolbar` anywhere in the AX tree (recon +`## AX_TREE`). Its only persistent button strip is the `group 'Sidebar'`, whose toggle +button and nav links are covered above; inventing a toolbar test would test nothing. + +Locators are (role, visible name) with EN + ZH fallbacks — never a child index or an +internal tree path, so the same test drives the reference and a recreation. +""" + +import json +import os +import re +import subprocess +import time + +import pytest + +import rb_testgen_kit as kit +import verifier_helpers as helpers + +from ApplicationServices import ( + AXUIElementCopyActionNames, + AXUIElementCopyAttributeValue, + AXUIElementIsAttributeSettable, +) + +RESULTS_DIR = os.environ.get("RESULTS_DIR", "/tmp/verifier_results") + + +# ───────────────────────── screenshot assertions ───────────────────────────── +def screenshot_assert(test_name, description, results_dir): + 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) + + +# ───────────────────── low-level AX primitives (ref-based) ──────────────────── +def get_attr(el_or_ref, attr): + """Raw AX attribute off an AXElement (or a raw AXUIElementRef).""" + ref = getattr(el_or_ref, "ref", el_or_ref) + try: + err, val = AXUIElementCopyAttributeValue(ref, attr, None) + return val if err == 0 else None + except Exception: + return None + + +def get_actions(el): + """Action names of an element (AXHelper already caches them on AXElement.actions).""" + if getattr(el, "actions", None): + return list(el.actions) + ref = getattr(el, "ref", el) + try: + err, actions = AXUIElementCopyActionNames(ref, None) + return list(actions) if err == 0 and actions else [] + except Exception: + return [] + + +def is_settable(el, attr): + ref = getattr(el, "ref", el) + try: + err, settable = AXUIElementIsAttributeSettable(ref, attr, None) + return err == 0 and bool(settable) + except Exception: + return False + + +# ─────────────────── recon `## RECIPES` helpers (verbatim) ──────────────────── +def reveal_ui(ax): + """recon says REVEAL_STEPS: none needed (a normal windowed app, window on screen at + launch). Defensive only: a recreation could hide its window behind a status item / + Preferences hotkey, so if NO window is present try every reveal path. No-op here.""" + try: + if ax.find(role="window", max_results=1, max_depth=2): + return True + ax.ensure_ui_visible() + time.sleep(1.0) + except Exception: + pass + try: + return bool(ax.find(role="window", max_results=1, max_depth=2)) + except Exception: + return False + + +def wait_for_web(ax, timeout=20.0): + """REQUIRED first line of every test: poll until the WebKit content is in the AX tree.""" + reveal_ui(ax) # defensive reveal (no-op on the reference) + deadline = time.time() + timeout + while time.time() < deadline: + for e in web_els(ax): + if e.role == "link" and e.name == "Settings": + return True + time.sleep(0.4) + return False + + +def web_els(ax): + """All elements inside the app's web area (excludes the menu bar).""" + wa = ax.find(role="webarea", max_results=2) + if not wa: + return [] + return ax.find(max_results=1500, root_id=wa[0].id, max_depth=25) + + +def by_role(ax, role): + return [e for e in web_els(ax) if e.role == role] + + +def named(ax, role, name): + for e in web_els(ax): + if e.role == role and (e.name or "") == name: + return e + return None + + +def headings(ax): + return [(e.name, e.value) for e in web_els(ax) if e.role == "heading"] + + +def rb_enter_press(ax, role, name, wait=1.6): + """AXPress a named link/button and settle. Returns True if the element existed.""" + el = named(ax, role, name) + if el is None: + return False + ax.action(el.id, "AXPress") + time.sleep(wait) + return True + + +def rb_reach_home(ax): + """Go to the Welcome/onboarding surface: pressing sidebar 'Dashboard' redirects there.""" + helpers.send_key(helpers.KC_ESCAPE) + time.sleep(0.4) + rb_enter_press(ax, "link", "Dashboard") + + +def rb_enter_settings(ax): + """Sidebar 'Settings' link -> Settings > General surface (depth 1).""" + return rb_enter_press(ax, "link", "Settings") + + +def rb_enter_settings_tab(ax, tab): + """Settings sub-nav link: 'General' | 'Accounts' | 'Goals' | 'Appearance' (depth 1).""" + return rb_enter_press(ax, "link", tab) + + +def rb_reach_accounts(ax): + """Settings > Accounts (depth 2): sidebar Settings, then the 'Accounts' sub-nav link.""" + rb_enter_settings(ax) + return rb_enter_settings_tab(ax, "Accounts") + + +def rb_reach_add_account_dialog(ax): + """Settings > Accounts > 'Add account' -> the Add Account modal (depth 2).""" + rb_reach_accounts(ax) + return rb_enter_press(ax, "button", "Add account") + + +def rb_back_escape(n=1): + """Escape closes (in order) popover -> dialog -> menu. VERIFIED reliable.""" + for _ in range(n): + helpers.send_key(helpers.KC_ESCAPE) + time.sleep(0.6) + + +def ax_attr(ax, el, attr): + """Read a raw AX attribute (AXHelp / AXSelected / AXPlaceholderValue / ...).""" + import ApplicationServices as AS + err, v = AS.AXUIElementCopyAttributeValue(ax._get_ref(el.id), attr, None) + return v if err == 0 else None + + +# ───────────── semantic locators (label + role; EN/ZH, never by index) ──────── +def web_named_any(ax, role, names): + """First element of `role` whose visible name equals one of `names` (in order).""" + els = web_els(ax) + for n in names: + for e in els: + if e.role == role and (e.name or "") == n: + return e + return None + + +def pressable(ax, name, roles=("button", "popup", "link")): + """A press target located by its VISIBLE LABEL, preferring the reference role but + tolerating a recreation that maps the same control to another AX role.""" + els = web_els(ax) + for r in roles: + for e in els: + if e.role == r and (e.name or "").strip() == name and "AXPress" in get_actions(e): + return e + for e in els: + if (e.name or "").strip() == name and "AXPress" in get_actions(e): + return e + return None + + +def link_by_text(ax, *keywords): + """Locate a link by visible label: exact name first, then keyword containment.""" + els = [e for e in web_els(ax) if e.role == "link"] + for kw in keywords: + for e in els: + if (e.name or "") == kw: + return e + low = [k.lower() for k in keywords if k] + for e in els: + n = (e.name or "").lower() + if n and any(k in n for k in low): + return e + return None + + +def sidebar_toggle(ax): + """The sidebar toggle button, by either visible label state, else by AXHelp.""" + els = web_els(ax) + for want in ("Expand Sidebar", "Collapse Sidebar", "展开侧边栏", "收起侧边栏"): + for e in els: + if e.role == "button" and (e.name or "") == want: + return e + for e in els: + if e.role == "button" and (ax_attr(ax, e, "AXHelp") or "") in ("Toggle Sidebar", "切换侧边栏"): + return e + return None + + +def sidebar_logo_link(ax): + """The unnamed brand/logo link at the top of the sidebar (navigates to '/').""" + els = [e for e in web_els(ax) if e.role == "link"] + for e in els: + if not (e.name or "").strip(): + return e + for e in els: + if (e.name or "") == "Wealthfolio": + return e + return None + + +def dashboard_nav_link(ax): + return web_named_any(ax, "link", ["Dashboard", "仪表盘", "仪表板"]) + + +def size_width(ax, el): + """Width out of AXSize — AXHelper serialises the AXValueRef to its description + string ('... value = w:52.000000 h:48.000000'), so parse the `w:` number.""" + raw = ax.get(el.id, ["AXSize"]).get("AXSize") + if isinstance(raw, dict): + try: + return float(raw.get("width") or 0.0) + except Exception: + return 0.0 + s = str(raw) + for pat in (r"\bw\s*[:=]\s*([-\d.]+)", r"\bwidth\s*[:=]\s*([-\d.]+)"): + m = re.search(pat, s) + if m: + return float(m.group(1)) + tail = s.split("value", 1)[-1] # skip the '' pointer text + nums = re.findall(r"(? its own label flips Expand <-> Collapse + and the nav links widen 52 -> 172. In-page state flip => depth 0.""" + + @pytest.mark.rb(depth=0, jump_kind="transition", + expect="button 'Expand Sidebar' is renamed 'Collapse Sidebar' after AXPress " + "(the old label disappears from the tree)") + def test_expand_sidebar_button_renames_to_collapse(self, ax): + assert wait_for_web(ax), "WebKit content never appeared in the AX tree" + btn = sidebar_toggle(ax) + assert btn is not None, "no sidebar toggle button (expected button 'Expand Sidebar')" + name_before = (btn.name or "") + assert "AXPress" in get_actions(btn), f"toggle exposes no AXPress: {get_actions(btn)}" + assert name_before == "Expand Sidebar", ( + f"sidebar should start COLLAPSED with label 'Expand Sidebar', got {name_before!r}") + + before = kit.rb_showing(ax) + ax.action(btn.id, "AXPress") + time.sleep(1.0) + after = kit.rb_showing(ax) + screenshot_assert( + "buttons_sidebar_expanded", + "Wealthfolio with the sidebar EXPANDED after pressing the sidebar toggle: the left " + "sidebar is wide and now shows the text labels Dashboard / Holdings / Activities / " + "Settings next to their icons plus the 'Wealthfolio' brand beside the logo. The main " + "area still shows the onboarding screen: coin/pie illustration, bold 'Welcome to " + "Wealthfolio' heading, three numbered steps and the dark \"Let's get started\" button.", + RESULTS_DIR) + + toggle_after = sidebar_toggle(ax) + assert toggle_after is not None, "the sidebar toggle vanished after being pressed" + name_after = (toggle_after.name or "") + flipped = kit.rb_flip(name_before, name_after) + renamed = kit.rb_reach(before, after, "Collapse Sidebar", "Expand Sidebar") + + # restore the recorded launch state (collapsed) + ax.action(toggle_after.id, "AXPress") + time.sleep(0.8) + + assert flipped, f"toggle label did not change: {name_before!r} -> {name_after!r}" + assert name_after == "Collapse Sidebar", ( + f"expected the label to become 'Collapse Sidebar', got {name_after!r}") + assert renamed, ("'Collapse Sidebar' did not appear while 'Expand Sidebar' disappeared " + "from the AX tree") + + @pytest.mark.rb(depth=0, jump_kind="transition", + expect="pressing the toggle a second time restores the label 'Expand Sidebar' " + "(sidebar collapsed again)") + def test_collapse_sidebar_button_restores_expand_label(self, ax): + assert wait_for_web(ax), "WebKit content never appeared in the AX tree" + btn = sidebar_toggle(ax) + assert btn is not None, "no sidebar toggle button (expected button 'Expand Sidebar')" + ax.action(btn.id, "AXPress") # -> expanded, label 'Collapse Sidebar' + time.sleep(1.0) + + mid_toggle = sidebar_toggle(ax) + assert mid_toggle is not None, "the sidebar toggle vanished after the first press" + mid_name = (mid_toggle.name or "") + assert mid_name == "Collapse Sidebar", ( + f"first press should give 'Collapse Sidebar', got {mid_name!r}") + + mid = kit.rb_showing(ax) + ax.action(mid_toggle.id, "AXPress") # -> collapsed again + time.sleep(1.0) + end = kit.rb_showing(ax) + + end_toggle = sidebar_toggle(ax) + assert end_toggle is not None, "the sidebar toggle vanished after the second press" + end_name = (end_toggle.name or "") + assert kit.rb_flip(mid_name, end_name), ( + f"second press did not change the label back: {mid_name!r} -> {end_name!r}") + assert end_name == "Expand Sidebar", ( + f"expected the label to revert to 'Expand Sidebar', got {end_name!r}") + assert kit.rb_reach(mid, end, "Expand Sidebar", "Collapse Sidebar"), ( + "'Expand Sidebar' did not come back while 'Collapse Sidebar' disappeared") + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="nav link 'Dashboard' AXSize width grows 52 -> 172 when the sidebar " + "toggle expands the sidebar, and shrinks back when collapsed") + def test_expand_sidebar_button_widens_dashboard_nav_link(self, ax): + assert wait_for_web(ax), "WebKit content never appeared in the AX tree" + dash = dashboard_nav_link(ax) + assert dash is not None, "no sidebar nav link 'Dashboard'" + w_before = size_width(ax, dash) + + btn = sidebar_toggle(ax) + assert btn is not None, "no sidebar toggle button" + ax.action(btn.id, "AXPress") + time.sleep(1.0) + + dash2 = dashboard_nav_link(ax) + assert dash2 is not None, "nav link 'Dashboard' disappeared after expanding the sidebar" + w_after = size_width(ax, dash2) + + # restore the collapsed launch state + back = sidebar_toggle(ax) + if back is not None: + ax.action(back.id, "AXPress") + time.sleep(0.8) + dash3 = dashboard_nav_link(ax) + w_restored = size_width(ax, dash3) if dash3 is not None else -1.0 + + grew = w_after >= w_before + 40.0 + assert kit.rb_value(grew, True), ( + f"'Dashboard' did not widen on expand: {w_before} -> {w_after} " + f"(reference: 52 -> 172)") + near_reference = abs(w_before - 52.0) <= 24.0 and abs(w_after - 172.0) <= 40.0 + assert kit.rb_value(near_reference, True), ( + f"collapsed/expanded nav-link widths {w_before} -> {w_after} are not the recorded " + f"52 -> 172 geometry") + assert kit.rb_value(w_restored <= w_before + 20.0, True), ( + f"collapsing again did not shrink 'Dashboard' back (got {w_restored}, " + f"started at {w_before})") + + +# ═════════════════ B3 / B4 / B5 / B6 — Add Account modal buttons ═════════════ +class TestAddAccountModalButtons: + """recon B3/B4 open the Add Account modal (an in-page modal that aria-hides the rest of + the page -> a perfect rb_reach signature); B5/B6 dismiss it back to the accounts page.""" + + @pytest.mark.rb(depth=2, jump_kind="reach", + expect="pressing button 'Add account' on Settings>Accounts opens the Add " + "Account modal: 'Add an investment account to track.' appears and the " + "'No account added!' empty state disappears") + def test_add_account_header_button_opens_modal(self, ax): + assert wait_for_web(ax), "WebKit content never appeared in the AX tree" + assert rb_reach_accounts(ax), "could not reach Settings > Accounts" + btn = pressable(ax, "Add account", roles=("button", "link", "popup")) + assert btn is not None, "no button 'Add account' in the Accounts page header" + assert btn.enabled, "button 'Add account' is disabled" + + before = kit.rb_showing(ax) + ax.action(btn.id, "AXPress") + time.sleep(1.1) + after = kit.rb_showing(ax) + screenshot_assert( + "buttons_add_account_modal", + "The Add Account modal opened by the 'Add account' button: a centred white card " + "titled 'Add Account' with the subtitle 'Add an investment account to track.', text " + "fields Account Name and Account Group, an Account Type select showing 'Securities', " + "a Currency select showing 'United States dollar (USD)', two toggle switches " + "(Default Account off, Is Active on), a Cancel button and a dark '+ Add Account' " + "button in the footer, and a small x close button at the top-right.", + RESULTS_DIR) + + reached = kit.rb_reach(before, after, "Add an investment account", "No account added") + rb_back_escape(1) # always restore: close the modal we opened + assert reached, ("button 'Add account' did not open the Add Account modal " + "(modal subtitle absent, or the accounts empty state stayed on screen)") + + @pytest.mark.rb(depth=2, jump_kind="reach", + expect="button 'Add an account' (empty-state placeholder) opens the SAME Add " + "Account modal: 'Add an investment account to track.' appears and " + "'No account added!' disappears") + def test_add_an_account_placeholder_button_opens_same_modal(self, ax): + assert wait_for_web(ax), "WebKit content never appeared in the AX tree" + assert rb_reach_accounts(ax), "could not reach Settings > Accounts" + btn = pressable(ax, "Add an account", roles=("button", "link", "popup")) + assert btn is not None, ("no button 'Add an account' in the empty-accounts placeholder " + "card (second entry point to the modal)") + assert btn.enabled, "button 'Add an account' is disabled" + + before = kit.rb_showing(ax) + ax.action(btn.id, "AXPress") + time.sleep(1.1) + after = kit.rb_showing(ax) + + reached = kit.rb_reach(before, after, "Add an investment account", "No account added") + heading_ok = any("Add Account" in k for k in (after - before)) + rb_back_escape(1) + assert reached, ("button 'Add an account' did not open the Add Account modal " + "(the placeholder button must reach the same dialog as 'Add account')") + assert heading_ok, "the modal's 'Add Account' heading/container never appeared" + + @pytest.mark.rb(depth=2, jump_kind="reach", + expect="button 'Close' (the x) dismisses the Add Account modal: the accounts " + "page returns ('No account added!' back) and the modal subtitle is gone") + def test_modal_close_button_dismisses_modal(self, ax): + assert wait_for_web(ax), "WebKit content never appeared in the AX tree" + assert rb_reach_add_account_dialog(ax), "could not open the Add Account modal" + close = pressable(ax, "Close", roles=("button", "popup", "link")) + assert close is not None, "no button 'Close' (x) inside the Add Account modal" + assert "AXPress" in get_actions(close), f"'Close' exposes no AXPress: {get_actions(close)}" + + before = kit.rb_showing(ax) + ax.action(close.id, "AXPress") + time.sleep(1.1) + after = kit.rb_showing(ax) + screenshot_assert( + "buttons_accounts_empty_after_close", + "Settings > Accounts restored after the modal's x/Close button was pressed: the " + "'Accounts' heading with the subtitle 'Manage your investment and saving accounts.', " + "an 'Add account' button at the top-right, and a dashed-border empty card with a " + "wallet icon, 'No account added!', \"You don't have any account yet. Start adding " + "your investment accounts.\" and an 'Add an account' button. No modal is visible.", + RESULTS_DIR) + + reached_back = kit.rb_reach(before, after, "No account added", "Add an investment account") + if not reached_back: + rb_back_escape(1) # leave no modal behind if Close misbehaved + assert reached_back, ("button 'Close' did not dismiss the modal back to the accounts page " + "(expected 'No account added!' back and the modal subtitle gone)") + + + @pytest.mark.rb(depth=2, jump_kind="value", + expect="the opened modal exposes exactly text_fields ['Account Group', " + "'Account Name'], comboboxes ['Account Type', 'Currency'], checkboxes " + "['Default Account', 'Is Active'], Cancel/Add Account/Close and the " + "heading 'Add Account' at level 2") + def test_add_account_button_reveals_expected_modal_controls(self, ax): + assert wait_for_web(ax), "WebKit content never appeared in the AX tree" + assert rb_reach_add_account_dialog(ax), "could not open the Add Account modal" + + els = web_els(ax) + fields = sorted((e.name or "") for e in els if e.role == "text_field") + combos = sorted((e.name or "") for e in els if e.role == "combobox") + switches = sorted((e.name or "") for e in els if e.role == "checkbox") + press_names = sorted((e.name or "") for e in els + if e.role in ("button", "popup") and (e.name or "")) + hs = [(n, v) for (n, v) in headings(ax) if n] + rb_back_escape(1) + + assert kit.rb_value(fields, ["Account Group", "Account Name"]), ( + f"modal text fields are {fields}, expected exactly " + f"['Account Group', 'Account Name']") + assert kit.rb_value(combos, ["Account Type", "Currency"]), ( + f"modal comboboxes are {combos}, expected exactly ['Account Type', 'Currency']") + assert kit.rb_value(switches, ["Default Account", "Is Active"]), ( + f"modal switches are {switches}, expected exactly " + f"['Default Account', 'Is Active']") + for want in ("Add Account", "Cancel", "Close"): + assert kit.rb_value(want in press_names, True), ( + f"modal press target {want!r} missing; found {press_names} " + f"(reference: popup 'Cancel', button 'Add Account', button 'Close')") + assert kit.rb_value(len(hs) == 1, True), ( + f"modal should expose exactly one heading ('Add Account'), got {hs}") + assert kit.rb_value(hs[0][0], "Add Account"), f"modal heading is {hs[0][0]!r}" + assert kit.rb_value(str(hs[0][1]).strip() == "2", True), ( + f"modal heading 'Add Account' should be level 2, got {hs[0][1]!r}") + + + @pytest.mark.rb(depth=2, jump_kind="value", + expect="after the modal's Close button dismisses it, the accounts page's " + "button set is exactly ['Add account', 'Add an account', " + "'Expand Sidebar'] again") + def test_accounts_button_set_restored_after_modal_close(self, ax): + assert wait_for_web(ax), "WebKit content never appeared in the AX tree" + assert rb_reach_add_account_dialog(ax), "could not open the Add Account modal" + close = pressable(ax, "Close", roles=("button", "popup", "link")) + assert close is not None, "no button 'Close' (x) inside the Add Account modal" + ax.action(close.id, "AXPress") + time.sleep(1.1) + + names = web_button_names(ax) + expected = ["Add account", "Add an account", "Expand Sidebar"] + present = [n for n in expected if n in names] + if len(present) < 3: + rb_back_escape(1) + assert kit.rb_value(present, expected), ( + f"accounts page buttons after Close are {names}; expected {expected} " + f"(the sidebar toggle plus both add-account entry points)") + assert len(names) <= 4, ( + f"unexpected extra buttons on the restored accounts page: {names}") + + +# ══════════════ onboarding / sidebar press targets (links) ═══════════════════ +class TestOnboardingLinkTargets: + """The onboarding step links, "Let's get started", the sidebar logo and the gated nav + links are the app's remaining press targets (recon `## TEXT` interaction table).""" + + @pytest.mark.rb(depth=1, jump_kind="reach", + expect="link '1 Set your main currency' lands on Settings>General: " + "'Select your base currency.' appears and 'Welcome to Wealthfolio' " + "disappears") + def test_step1_currency_link_opens_settings_general(self, ax): + assert wait_for_web(ax), "WebKit content never appeared in the AX tree" + rb_reach_home(ax) + link = link_by_text(ax, "1 Set your main currency", "Set your main currency", "设置主货币") + assert link is not None, "no onboarding link '1 Set your main currency'" + before = kit.rb_showing(ax) + ax.action(link.id, "AXPress") + time.sleep(1.2) + after = kit.rb_showing(ax) + assert kit.rb_reach(before, after, "Select your base currency", "Welcome to Wealthfolio"), ( + "onboarding step 1 did not navigate to Settings > General " + "(expected 'Select your base currency.' with the Welcome screen gone)") + + @pytest.mark.rb(depth=1, jump_kind="reach", + expect="link '2 Add your accounts' lands on Settings>Accounts: " + "'No account added!' appears and 'Welcome to Wealthfolio' disappears") + def test_step2_accounts_link_opens_settings_accounts(self, ax): + assert wait_for_web(ax), "WebKit content never appeared in the AX tree" + rb_reach_home(ax) + link = link_by_text(ax, "2 Add your accounts", "Add your accounts", "添加账户") + assert link is not None, "no onboarding link '2 Add your accounts'" + before = kit.rb_showing(ax) + ax.action(link.id, "AXPress") + time.sleep(1.2) + after = kit.rb_showing(ax) + assert kit.rb_reach(before, after, "No account added", "Welcome to Wealthfolio"), ( + "onboarding step 2 did not navigate to Settings > Accounts " + "(expected 'No account added!' with the Welcome screen gone)") + + @pytest.mark.rb(depth=1, jump_kind="reach", + expect="link \"Let's get started\" lands on Settings>General: " + "'Select your base currency.' appears, Welcome screen gone") + def test_lets_get_started_link_opens_settings_general(self, ax): + assert wait_for_web(ax), "WebKit content never appeared in the AX tree" + rb_reach_home(ax) + link = link_by_text(ax, "Let's get started", "get started", "开始") + assert link is not None, "no onboarding link \"Let's get started\"" + before = kit.rb_showing(ax) + ax.action(link.id, "AXPress") + time.sleep(1.2) + after = kit.rb_showing(ax) + assert kit.rb_reach(before, after, "Select your base currency", "Welcome to Wealthfolio"), ( + "\"Let's get started\" did not navigate to Settings > General") + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="link '3 Add or import activities' is gated: the Welcome heading is " + "STILL present afterwards and no settings content ('Select your base " + "currency.' / 'No account added!') appears") + def test_step3_activities_link_stays_on_welcome_gate(self, ax): + assert wait_for_web(ax), "WebKit content never appeared in the AX tree" + rb_reach_home(ax) + before = kit.rb_showing(ax) + assert any("Welcome to Wealthfolio" in k for k in before), ( + "did not start on the Welcome/onboarding surface") + link = link_by_text(ax, "3 Add or import activities", "Add or import activities", "导入活动") + assert link is not None, "no onboarding link '3 Add or import activities'" + ax.action(link.id, "AXPress") + time.sleep(1.2) + after = kit.rb_showing(ax) + screenshot_assert( + "buttons_home_onboarding_gate", + "Wealthfolio still on the onboarding screen after pressing the third step link " + "'3 Add or import activities' (the onboarding gate blocks it): narrow dark-icon " + "sidebar on the left, circular coin/pie illustration, bold 'Welcome to Wealthfolio' " + "heading, the intro line about a personal financial portfolio tracker, three numbered " + "steps 1/2/3 with arrows and the dark \"Let's get started\" button. No settings page.", + RESULTS_DIR) + + still_home = any("Welcome to Wealthfolio" in k for k in after) + assert kit.rb_value(still_home, True), ( + "step 3 left the Welcome surface — the onboarding gate should keep it there " + "until a base currency and an account exist") + leaked = sorted(k for k in after + if "Select your base currency" in k or "No account added" in k) + assert kit.rb_value(leaked, []), ( + f"step 3 exposed settings content it must not reach yet: {leaked}") + + + +class TestGatedSidebarNavButtons: + """recon gate behaviour: from Settings>General the Dashboard / Holdings / Activities nav + links all redirect back to the Welcome surface until the DB has a currency + account.""" + + def _assert_gated(self, ax, nav_names): + assert wait_for_web(ax), "WebKit content never appeared in the AX tree" + assert rb_enter_settings(ax), "could not reach Settings > General" + link = web_named_any(ax, "link", nav_names) + assert link is not None, f"no sidebar nav link {nav_names[0]!r}" + assert link.enabled, f"sidebar nav link {nav_names[0]!r} is disabled" + before = kit.rb_showing(ax) + assert any("Select your base currency" in k for k in before), ( + f"not on Settings > General before pressing {nav_names[0]!r}") + ax.action(link.id, "AXPress") + time.sleep(1.2) + after = kit.rb_showing(ax) + assert kit.rb_reach(before, after, "Welcome to Wealthfolio", + "Select your base currency"), ( + f"sidebar nav link {nav_names[0]!r} did not land back on the Welcome surface " + f"(the onboarding gate redirect)") + + @pytest.mark.rb(depth=1, jump_kind="reach", + expect="sidebar link 'Dashboard' pressed from Settings>General lands on the " + "Welcome surface (gate): Welcome heading appears, 'Select your base " + "currency.' disappears") + def test_dashboard_link_gated_back_to_welcome(self, ax): + self._assert_gated(ax, ["Dashboard", "仪表盘", "仪表板"]) + + @pytest.mark.rb(depth=1, jump_kind="reach", + expect="sidebar link 'Holdings' pressed from Settings>General lands on the " + "Welcome surface (gate): Welcome heading appears, 'Select your base " + "currency.' disappears") + def test_holdings_link_gated_back_to_welcome(self, ax): + self._assert_gated(ax, ["Holdings", "持仓"]) + + @pytest.mark.rb(depth=1, jump_kind="reach", + expect="sidebar link 'Activities' pressed from Settings>General lands on the " + "Welcome surface (gate): Welcome heading appears, 'Select your base " + "currency.' disappears") + def test_activities_link_gated_back_to_welcome(self, ax): + self._assert_gated(ax, ["Activities", "活动"]) + + +# ══════════ B7 / B8 / B9 — destructive buttons: EXISTENCE ONLY, never pressed ══ +class TestUnpressableButtons: + """recon `## DO-NOT-TOUCH`: 'Save' writes baseCurrency, the modal 'Add Account' creates a + DB row, and the chrome buttons close/hide the window. Read-only assertions only.""" + + @pytest.mark.rb(depth=1, jump_kind="none", + expect="Settings>General exposes an enabled button 'Save' (never pressed — " + "it would write the DB)") + def test_save_button_exists_and_is_enabled(self, ax): + assert wait_for_web(ax), "WebKit content never appeared in the AX tree" + assert rb_enter_settings(ax), "could not reach Settings > General" + save = web_named_any(ax, "button", ["Save", "保存"]) + assert save is not None, "no button 'Save' on Settings > General" + screenshot_assert( + "buttons_settings_general_save", + "Settings > General in Wealthfolio: the 'Settings' page title, a left column of " + "sub-nav entries General / Accounts / Goals / Appearance with General selected, the " + "'General' section with the description 'Manage the general application settings and " + "preferences.', a Currency combobox reading 'United States dollar (USD)' with the " + "helper text 'Select your base currency.', and a dark 'Save' button (not pressed).", + RESULTS_DIR) + assert save.enabled, "button 'Save' should be enabled on Settings > General" + assert "AXPress" in get_actions(save), ( + f"button 'Save' exposes no AXPress action: {get_actions(save)}") + + @pytest.mark.rb(depth=2, jump_kind="none", + expect="the Add Account modal exposes an enabled submit button 'Add Account' " + "(never pressed — it would create an account row)") + def test_modal_submit_button_exists_and_is_enabled(self, ax): + assert wait_for_web(ax), "WebKit content never appeared in the AX tree" + assert rb_reach_add_account_dialog(ax), "could not open the Add Account modal" + submit = web_named_any(ax, "button", ["Add Account", "添加账户"]) + enabled = bool(submit is not None and submit.enabled) + actions = get_actions(submit) if submit is not None else [] + rb_back_escape(1) + assert submit is not None, "no submit button 'Add Account' in the Add Account modal" + assert enabled, "the modal's submit button 'Add Account' should be enabled" + assert "AXPress" in actions, f"submit button exposes no AXPress action: {actions}" + + @pytest.mark.rb(depth=0, jump_kind="none", + expect="the main window exposes the three chrome buttons by subrole: " + "AXCloseButton, AXMinimizeButton, AXFullScreenButton (never pressed)") + def test_window_chrome_buttons_exist_by_subrole(self, ax): + assert wait_for_web(ax), "WebKit content never appeared in the AX tree" + wins = ax.find(role="window", max_results=6, max_depth=2) + assert wins, "the app exposes no AXWindow" + win = wins[0] + for w in wins: + if ax.get(w.id, ["AXMain"]).get("AXMain"): + win = w + break + subroles = set() + for b in ax.find(role="button", root_id=win.id, max_results=30, max_depth=3): + sr = ax.get(b.id, ["AXSubrole"]).get("AXSubrole") + if sr: + subroles.add(str(sr)) + assert "AXCloseButton" in subroles, f"no AXCloseButton on the window; got {sorted(subroles)}" + assert "AXMinimizeButton" in subroles, ( + f"no AXMinimizeButton on the window; got {sorted(subroles)}") + assert ("AXFullScreenButton" in subroles or "AXZoomButton" in subroles), ( + f"no AXFullScreenButton/AXZoomButton on the window; got {sorted(subroles)}") diff --git a/macos/wealthfolio-wealthfolio/tests/test_ax_computation.py b/macos/wealthfolio-wealthfolio/tests/test_ax_computation.py new file mode 100644 index 0000000000000000000000000000000000000000..0776e8135d7b876f1a75b61e11c3d4166c6141ff --- /dev/null +++ b/macos/wealthfolio-wealthfolio/tests/test_ax_computation.py @@ -0,0 +1,668 @@ +#!/usr/bin/env python3 +"""AX COMPUTATION tests for Wealthfolio (bundle com.teymz.wealthfolio, Tauri v1 + WebKit). + +Wealthfolio has NO calculator. Its reachable input -> output engine is: + + * the searchable **156-entry currency picker** (input = the popover's unnamed + `combobox` search box, written with `ax.set_value`; output = the option rows, + i.e. `label` elements that carry `AXPress` and a non-empty NAME). The picker + appears in TWO places (two "modes"): Settings > General (depth 2) and inside + the Add Account modal (depth 3) — both behave identically. + * the Radix **Account Type** selector (options Securities / Cash / Crypto). + * the Add Account modal's **text fields** (`Account Name`, `Account Group`). + +Every expected value asserted below is an OBSERVED reference value taken from the +recon report's ## COMPUTATION worked examples. The currency matcher is FUZZY, so +multi-match queries assert membership + a bound on the row count + the absence of +an unrelated currency, never the exact fuzzy extras. + +DO-NOT-TOUCH honoured here: `button 'Save'` (Settings > General) and +`button 'Add Account'` (modal submit) are NEVER pressed — both write the SQLite DB +and would permanently change the onboarding gate for every later test. Text entry +is `ax.set_value` only (CGEvent character typing is never delivered to this Tauri +window); Escape is used to leave the popover / modal at the end of every test. +""" + +import json +import os +import subprocess +import time + +import pytest + +import rb_testgen_kit as kit +import verifier_helpers as helpers + +RESULTS_DIR = os.environ.get("RESULTS_DIR") or os.path.join( + os.path.dirname(os.path.abspath(__file__)), "results") + +# Observed reference constants (recon ## COMPUTATION / ## AX_TREE surface E). +ALL_CURRENCY_COUNT = 156 +FIRST_FOUR = [ + "United States dollar (USD)", + "Canadian dollar (CAD)", + "European Euro (EUR)", + "Australian dollar (AUD)", +] +LAST_CURRENCY = "Zimbabwean dollar (ZWR)" +DEFAULT_CURRENCY = "United States dollar (USD)" +UNRELATED = "Japanese yen (JPY)" # absence probe for multi-match queries +NO_MATCH_LABEL = "No currency found." +ACCOUNT_TYPES = ["Securities", "Cash", "Crypto"] + + +# --------------------------------------------------------------------------- +# screenshot assertions +# --------------------------------------------------------------------------- +def screenshot_assert(test_name, description, results_dir): + 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 + try: + with open(assertions_file, "w") as f: + json.dump(assertions, f, indent=2) + except Exception: + pass + + +# --------------------------------------------------------------------------- +# RECIPES (verbatim from recon ## RECIPES) — reads +# --------------------------------------------------------------------------- +def wait_for_web(ax, timeout=20.0): + """REQUIRED first line of every test: poll until the WebKit content is in the AX tree.""" + deadline = time.time() + timeout + while time.time() < deadline: + for e in web_els(ax): + if e.role == "link" and e.name == "Settings": + return True + time.sleep(0.4) + return False + + +def web_els(ax): + """All elements inside the app's web area (excludes the menu bar).""" + wa = ax.find(role="webarea", max_results=2) + if not wa: + return [] + return ax.find(max_results=1500, root_id=wa[0].id, max_depth=25) + + +def named(ax, role, name): + for e in web_els(ax): + if e.role == role and (e.name or "") == name: + return e + return None + + +def texts(ax): + """Every visible text string in the web area (label .value or .name).""" + return [(e.value or e.name) for e in web_els(ax) if e.role == "label" and (e.value or e.name)] + + +# --------------------------------------------------------------------------- +# RECIPES — navigation (rb_enter_* / rb_reach_* so the depth audit sees them) +# --------------------------------------------------------------------------- +def rb_enter_press(ax, role, name, wait=1.6): + """AXPress a named link/button and settle. Returns True if the element existed.""" + el = named(ax, role, name) + if el is None: + return False + ax.action(el.id, "AXPress") + time.sleep(wait) + return True + + +def rb_enter_settings(ax): + """Sidebar 'Settings' link -> Settings > General surface (depth 1).""" + return rb_enter_press(ax, "link", "Settings") + + +def rb_enter_settings_tab(ax, tab): + """Settings sub-nav link: 'General' | 'Accounts' | 'Goals' | 'Appearance' (depth 1).""" + return rb_enter_press(ax, "link", tab) + + +def rb_reach_accounts(ax): + """Settings > Accounts (depth 1): sidebar Settings, then the 'Accounts' sub-nav link.""" + rb_enter_settings(ax) + return rb_enter_settings_tab(ax, "Accounts") + + +def rb_reach_add_account_dialog(ax): + """Settings > Accounts > 'Add account' -> the Add Account modal (depth 2).""" + rb_reach_accounts(ax) + return rb_enter_press(ax, "button", "Add account") + + +def rb_enter_currency_popover(ax): + """AXPress the 'Currency' combobox -> the currency search popover. + depth 2 from home (via Settings>General) / depth 3 from inside the Add Account dialog.""" + return rb_enter_press(ax, "combobox", "Currency", wait=1.5) + + +def rb_back_escape(n=1): + """Escape closes (in order) popover -> dialog -> menu. VERIFIED reliable.""" + for _ in range(n): + helpers.send_key(helpers.KC_ESCAPE) + time.sleep(0.6) + + +# --------------------------------------------------------------------------- +# RECIPES — currency popover: filtering + selection +# --------------------------------------------------------------------------- +def currency_search_field(ax): + """The popover's search input == the only combobox with an EMPTY name.""" + for e in web_els(ax): + if e.role == "combobox" and not (e.name or ""): + return e + return None + + +def currency_options(ax): + """Option rows == labels that carry AXPress and a non-empty NAME.""" + return [e.name for e in web_els(ax) if e.role == "label" and e.name and "AXPress" in e.actions] + + +def filter_currency(ax, query): + """Type into the search box. `ax.set_value()` is the ONLY mechanism that works here + (CGEvent character typing does NOT reach this field). Returns the filtered option names.""" + sf = currency_search_field(ax) + ax.set_value(sf.id, query) + time.sleep(0.9) + return currency_options(ax) + + +def pick_currency(ax, label): + """AXPress the option row whose name == label (works), then Escape to close the popover. + Afterwards the 'Currency' combobox VALUE equals that label.""" + for e in web_els(ax): + if e.role == "label" and e.name == label: + ax.action(e.id, "AXPress") + break + time.sleep(0.9) + rb_back_escape(1) + + +# --------------------------------------------------------------------------- +# RECIPES — Radix Select ('Account Type') +# --------------------------------------------------------------------------- +def open_account_type(ax): + """AXPress does NOT open a Radix Select, and the combobox's own AX frame is bogus. + CG-click its CHILD label (the one whose VALUE is the current selection) — verified.""" + cur = None + for e in web_els(ax): + if e.role == "label" and (e.value or "").strip() in ("Securities", "Cash", "Crypto") \ + and "AXPress" in e.actions: + cur = e + break + ax.click_element_cg(cur.id) + time.sleep(1.2) + return [e.name for e in web_els(ax) if e.role == "label" and e.name] # Securities/Cash/Crypto + + +def select_next_account_type(ax): + """Inside the open Select portal, Down + Return picks the NEXT option (verified).""" + helpers.send_key(helpers.KC_DOWN_ARROW); time.sleep(0.4) + helpers.send_key(helpers.KC_RETURN); time.sleep(1.2) + + +def ax_attr(ax, el, attr): + """Read a raw AX attribute (AXHelp / AXSelected / AXPlaceholderValue / AXMenuItemCmdChar).""" + import ApplicationServices as AS + err, v = AS.AXUIElementCopyAttributeValue(ax._get_ref(el.id), attr, None) + return v if err == 0 else None + + +# --------------------------------------------------------------------------- +# local convenience (thin, non-navigating) +# --------------------------------------------------------------------------- +def combobox_value(ax, name): + """AXValue of the combobox with this visible label (semantic locator: name + role). + Values can carry a trailing '\\n' -> stripped, compare with kit.rb_value.""" + cb = named(ax, "combobox", name) + if cb is None: + return None + return str(cb.value or "").strip() + + +def combobox_values(ax): + """{visible label: stripped AXValue} for every NAMED combobox, in ONE tree pass — + used by the depth-3 tests where each extra pass costs real time.""" + out = {} + for e in web_els(ax): + if e.role == "combobox" and (e.name or ""): + out[e.name] = str(e.value or "").strip() + return out + + +def text_field_value(ax, name): + tf = named(ax, "text_field", name) + if tf is None: + return None + return str(tf.value or "") + + +def set_field(ax, name, text): + """Write TEXT into the named text_field. + + WebKit routes an AXValue write to the element that currently holds DOM focus, so a + field that is not focused silently swallows the write (or worse, it lands in the + focused sibling). Focus first, then write. Returns the value read back.""" + el = named(ax, "text_field", name) + if el is None: + return None + try: + import ApplicationServices as AS + AS.AXUIElementSetAttributeValue(ax._get_ref(el.id), "AXFocused", True) + time.sleep(0.4) + except Exception: + pass + el = named(ax, "text_field", name) + ax.set_value(el.id, text) + time.sleep(0.8) + return text_field_value(ax, name) + + +def placeholder_of(ax, role, name): + """AXPlaceholderValue of a named widget, re-resolved so the AX ref is fresh.""" + el = named(ax, role, name) + if el is None: + return None + return str(ax_attr(ax, el, "AXPlaceholderValue") or "") + + +@pytest.fixture(autouse=True) +def _reveal_window(ax): + """Reveal the app's UI BEFORE any window-dependent check. Wealthfolio is a normal + windowed app (recon: no REVEAL_STEPS) so this is a cheap no-op, but a recreation + could legitimately be a status-item app whose window needs opening.""" + try: + if not ax.find(role="window", max_results=1, max_depth=3): + ax.ensure_ui_visible() + time.sleep(1.0) + except Exception: + pass + yield + + +# =========================================================================== +# 1. The unfiltered picker (input = '' / untouched search box) +# =========================================================================== +class TestUnfilteredCurrencyList: + + @pytest.mark.rb(depth=2, jump_kind="value", + expect="unfiltered currency picker lists exactly 156 option rows, last = ZWR") + def test_unfiltered_picker_has_156_options(self, ax): + assert wait_for_web(ax) + assert rb_enter_settings(ax), "sidebar 'Settings' link not found" + assert rb_enter_currency_popover(ax), "combobox 'Currency' not found on Settings>General" + opts = currency_options(ax) + screenshot_assert( + "computation_test_unfiltered_currency_list", + "Settings > General with the currency picker popover open: a 'Search currency...' " + "input above a long scrollable list of 156 currency rows whose first entries read " + "United States dollar (USD), Canadian dollar (CAD), European Euro (EUR), " + "Australian dollar (AUD). No result is filtered out.", + RESULTS_DIR) + rb_back_escape(2) + assert len(opts) == ALL_CURRENCY_COUNT and kit.rb_value(len(opts), ALL_CURRENCY_COUNT), \ + f"expected {ALL_CURRENCY_COUNT} currency rows, got {len(opts)}" + assert kit.rb_value(opts, LAST_CURRENCY), f"{LAST_CURRENCY} missing from the 156-row list" + assert opts[-1] == LAST_CURRENCY, \ + f"expected the last row to be {LAST_CURRENCY!r}, got {opts[-1:]!r}" + + @pytest.mark.rb(depth=2, jump_kind="value", + expect="first four rows are USD, CAD, EUR, AUD in that order") + def test_unfiltered_picker_first_four_in_order(self, ax): + assert wait_for_web(ax) + assert rb_enter_settings(ax), "sidebar 'Settings' link not found" + assert rb_enter_currency_popover(ax), "combobox 'Currency' not found on Settings>General" + opts = currency_options(ax) + rb_back_escape(2) + assert opts[:4] == FIRST_FOUR and kit.rb_value(opts[:4], FIRST_FOUR), \ + f"expected first four {FIRST_FOUR}, got {opts[:4]}" + + +# =========================================================================== +# 2. Single-match filters (input -> exactly one output row) +# =========================================================================== +class TestSingleMatchFilters: + + @pytest.mark.rb(depth=2, jump_kind="value", + expect="query 'JPY' yields exactly ['Japanese yen (JPY)']") + def test_filter_jpy_yields_only_japanese_yen(self, ax): + assert wait_for_web(ax) + assert rb_enter_settings(ax), "sidebar 'Settings' link not found" + assert rb_enter_currency_popover(ax), "combobox 'Currency' not found on Settings>General" + opts = filter_currency(ax, "JPY") + screenshot_assert( + "computation_test_filter_jpy", + "The currency picker popover with 'JPY' entered in the 'Search currency...' box: " + "exactly one result row is listed, reading 'Japanese yen (JPY)'. No other currency " + "rows are visible.", + RESULTS_DIR) + rb_back_escape(2) + assert opts == ["Japanese yen (JPY)"] and kit.rb_value(opts, "Japanese yen (JPY)"), \ + f"expected ['Japanese yen (JPY)'], got {opts}" + + @pytest.mark.rb(depth=2, jump_kind="value", + expect="query 'CHF' yields exactly ['Swiss franc (CHF)']") + def test_filter_chf_yields_only_swiss_franc(self, ax): + assert wait_for_web(ax) + assert rb_enter_settings(ax), "sidebar 'Settings' link not found" + assert rb_enter_currency_popover(ax), "combobox 'Currency' not found on Settings>General" + opts = filter_currency(ax, "CHF") + rb_back_escape(2) + assert opts == ["Swiss franc (CHF)"] and kit.rb_value(opts, "Swiss franc (CHF)"), \ + f"expected ['Swiss franc (CHF)'], got {opts}" + + @pytest.mark.rb(depth=2, jump_kind="value", + expect="query 'Zimbabwean' yields exactly ['Zimbabwean dollar (ZWR)']") + def test_filter_zimbabwean_yields_only_zwr(self, ax): + assert wait_for_web(ax) + assert rb_enter_settings(ax), "sidebar 'Settings' link not found" + assert rb_enter_currency_popover(ax), "combobox 'Currency' not found on Settings>General" + opts = filter_currency(ax, "Zimbabwean") + rb_back_escape(2) + assert opts == [LAST_CURRENCY] and kit.rb_value(opts, LAST_CURRENCY), \ + f"expected [{LAST_CURRENCY!r}], got {opts}" + + +# =========================================================================== +# 3. Multi-match filters (FUZZY matcher -> membership + bound + absence) +# =========================================================================== +class TestMultiMatchFilters: + + @pytest.mark.rb(depth=2, jump_kind="value", + expect="query 'GBP' contains British pound (GBP), <20 rows, no JPY") + def test_filter_gbp_contains_british_pound(self, ax): + assert wait_for_web(ax) + assert rb_enter_settings(ax), "sidebar 'Settings' link not found" + assert rb_enter_currency_popover(ax), "combobox 'Currency' not found on Settings>General" + opts = filter_currency(ax, "GBP") + rb_back_escape(2) + assert kit.rb_value(opts, "British pound (GBP)"), \ + f"'British pound (GBP)' missing from GBP results: {opts}" + assert 0 < len(opts) < 20, f"GBP should narrow the list well below 20 rows, got {len(opts)}" + assert UNRELATED not in opts, f"{UNRELATED} must not match 'GBP': {opts}" + + @pytest.mark.rb(depth=2, jump_kind="value", + expect="query 'Swiss' puts Swiss franc (CHF) first, <20 rows, no JPY") + def test_filter_swiss_ranks_swiss_franc_first(self, ax): + assert wait_for_web(ax) + assert rb_enter_settings(ax), "sidebar 'Settings' link not found" + assert rb_enter_currency_popover(ax), "combobox 'Currency' not found on Settings>General" + opts = filter_currency(ax, "Swiss") + rb_back_escape(2) + assert kit.rb_value(opts[:1], "Swiss franc (CHF)"), \ + f"expected 'Swiss franc (CHF)' as the FIRST row for 'Swiss', got {opts[:1]}" + assert 0 < len(opts) < 20, f"'Swiss' should return well under 20 rows, got {len(opts)}" + assert UNRELATED not in opts, f"{UNRELATED} must not match 'Swiss': {opts}" + + +# =========================================================================== +# 4. Edge cases: no match, and clearing the query +# =========================================================================== +class TestFilterEdgeCases: + + @pytest.mark.rb(depth=2, jump_kind="value", + expect="query 'xyzzy' yields 0 rows and the label 'No currency found.'") + def test_filter_no_match_shows_empty_message(self, ax): + assert wait_for_web(ax) + assert rb_enter_settings(ax), "sidebar 'Settings' link not found" + assert rb_enter_currency_popover(ax), "combobox 'Currency' not found on Settings>General" + opts = filter_currency(ax, "xyzzy") + page_texts = texts(ax) + screenshot_assert( + "computation_test_filter_no_match", + "The currency picker popover with 'xyzzy' entered in the search box: the panel shows " + "the message 'No currency found.' and zero currency rows are listed.", + RESULTS_DIR) + rb_back_escape(2) + assert len(opts) == 0 and kit.rb_value(len(opts), 0), \ + f"expected 0 rows for 'xyzzy', got {len(opts)}: {opts[:5]}" + assert kit.rb_value(page_texts, NO_MATCH_LABEL), \ + f"label {NO_MATCH_LABEL!r} not shown; texts={page_texts}" + + @pytest.mark.rb(depth=2, jump_kind="transition", + expect="1 row filtered -> clearing the query restores all 156 rows") + def test_clearing_query_restores_full_list(self, ax): + assert wait_for_web(ax) + assert rb_enter_settings(ax), "sidebar 'Settings' link not found" + assert rb_enter_currency_popover(ax), "combobox 'Currency' not found on Settings>General" + filtered = filter_currency(ax, "CHF") + before = kit.rb_showing(ax) + sf = currency_search_field(ax) + assert sf is not None, "popover search combobox (empty name) not found" + ax.set_value(sf.id, "") + time.sleep(0.9) + restored = currency_options(ax) + after = kit.rb_showing(ax) + rb_back_escape(2) + assert len(filtered) == 1, f"pre-condition: 'CHF' should filter to 1 row, got {len(filtered)}" + assert kit.rb_flip(before, after, expect="filtered popover -> full 156-row popover"), \ + "clearing the query did not change the popover content" + assert len(restored) == ALL_CURRENCY_COUNT and kit.rb_value(len(restored), + ALL_CURRENCY_COUNT), \ + f"expected the list restored to {ALL_CURRENCY_COUNT} rows, got {len(restored)}" + + +# =========================================================================== +# 5. Committing a selection (output 2 = combobox 'Currency' AXValue) +# =========================================================================== +class TestCommitCurrencySelection: + + @pytest.mark.rb(depth=2, jump_kind="value", + expect="Currency combobox reads 'Japanese yen (JPY)' after picking it") + def test_commit_japanese_yen_via_filter(self, ax): + assert wait_for_web(ax) + assert rb_enter_settings(ax), "sidebar 'Settings' link not found" + assert rb_enter_currency_popover(ax), "combobox 'Currency' not found on Settings>General" + opts = filter_currency(ax, "Japanese") + assert kit.rb_value(opts, "Japanese yen (JPY)"), \ + f"'Japanese yen (JPY)' not offered for query 'Japanese': {opts}" + pick_currency(ax, "Japanese yen (JPY)") + committed = combobox_value(ax, "Currency") + rb_back_escape(2) + assert kit.rb_value(committed, "Japanese yen (JPY)"), \ + f"expected Currency == 'Japanese yen (JPY)', got {committed!r}" + + @pytest.mark.rb(depth=2, jump_kind="value", + expect="Currency combobox reads 'European Euro (EUR)' after picking it") + def test_commit_european_euro_from_unfiltered_list(self, ax): + assert wait_for_web(ax) + assert rb_enter_settings(ax), "sidebar 'Settings' link not found" + assert rb_enter_currency_popover(ax), "combobox 'Currency' not found on Settings>General" + pick_currency(ax, "European Euro (EUR)") + committed = combobox_value(ax, "Currency") + rb_back_escape(2) + assert kit.rb_value(committed, "European Euro (EUR)"), \ + f"expected Currency == 'European Euro (EUR)', got {committed!r}" + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="unsaved Currency reverts to 'United States dollar (USD)' after nav") + def test_selection_not_persisted_across_navigation(self, ax): + assert wait_for_web(ax) + assert rb_enter_settings(ax), "sidebar 'Settings' link not found" + assert rb_enter_currency_popover(ax), "combobox 'Currency' not found on Settings>General" + pick_currency(ax, "European Euro (EUR)") + assert kit.rb_value(combobox_value(ax, "Currency"), "European Euro (EUR)"), \ + "pre-condition: the picked currency should show on the trigger" + assert rb_enter_settings_tab(ax, "Accounts"), "settings sub-nav link 'Accounts' not found" + assert rb_enter_settings_tab(ax, "General"), "settings sub-nav link 'General' not found" + reverted = combobox_value(ax, "Currency") + rb_back_escape(2) + assert kit.rb_value(reverted, DEFAULT_CURRENCY), \ + f"expected the unsaved form to reset to {DEFAULT_CURRENCY!r}, got {reverted!r}" + + +# =========================================================================== +# 6. The SAME picker inside the Add Account modal (second mode, depth 3) +# =========================================================================== +class TestModalCurrencyPicker: + + @pytest.mark.rb(depth=3, jump_kind="value", + expect="modal Currency == 'Swiss franc (CHF)', Account Type still 'Securities'") + def test_modal_picker_commits_swiss_franc(self, ax): + assert wait_for_web(ax) + assert rb_reach_add_account_dialog(ax), "Add Account modal did not open" + assert rb_enter_currency_popover(ax), "modal combobox 'Currency' not found" + opts = filter_currency(ax, "CHF") + assert opts == ["Swiss franc (CHF)"], f"expected ['Swiss franc (CHF)'] in the modal, got {opts}" + pick_currency(ax, "Swiss franc (CHF)") + vals = combobox_values(ax) + currency = vals.get("Currency") + acct_type = vals.get("Account Type") + screenshot_assert( + "computation_test_modal_currency_commit", + "The centred 'Add Account' modal after picking Swiss franc in the currency picker: " + "the Currency field reads 'Swiss franc (CHF)' while Account Type still reads " + "'Securities'; Account Name and Account Group are empty, Default Account is off and " + "Is Active is on, with Cancel / + Add Account buttons at the bottom.", + RESULTS_DIR) + rb_back_escape(2) + assert kit.rb_value(currency, "Swiss franc (CHF)"), \ + f"expected modal Currency == 'Swiss franc (CHF)', got {currency!r}" + assert kit.rb_value(acct_type, "Securities"), \ + f"Account Type must stay 'Securities', got {acct_type!r}" + + @pytest.mark.rb(depth=3, jump_kind="value", + expect="modal picker unfiltered list also has 156 rows starting with USD") + def test_modal_picker_lists_all_156_currencies(self, ax): + assert wait_for_web(ax) + assert rb_reach_add_account_dialog(ax), "Add Account modal did not open" + assert rb_enter_currency_popover(ax), "modal combobox 'Currency' not found" + opts = currency_options(ax) + rb_back_escape(2) + assert len(opts) == ALL_CURRENCY_COUNT and kit.rb_value(len(opts), ALL_CURRENCY_COUNT), \ + f"expected {ALL_CURRENCY_COUNT} rows in the modal picker, got {len(opts)}" + assert opts[:4] == FIRST_FOUR and kit.rb_value(opts[:4], FIRST_FOUR), \ + f"expected first four {FIRST_FOUR}, got {opts[:4]}" + + +# =========================================================================== +# 7. The Account Type selector (a 3-value mode switch) +# =========================================================================== +class TestAccountTypeSelector: + + @pytest.mark.rb(depth=3, jump_kind="value", + expect="Account Type options are exactly ['Securities','Cash','Crypto']") + def test_account_type_options_are_exactly_three(self, ax): + assert wait_for_web(ax) + assert rb_reach_add_account_dialog(ax), "Add Account modal did not open" + options = open_account_type(ax) + screenshot_assert( + "computation_test_account_type_list", + "The 'Add Account' modal with the Account Type dropdown expanded, showing exactly " + "three options in order: Securities, Cash, Crypto (Securities is the current value).", + RESULTS_DIR) + rb_back_escape(2) + assert options == ACCOUNT_TYPES and kit.rb_value(options, ACCOUNT_TYPES), \ + f"expected {ACCOUNT_TYPES}, got {options}" + + @pytest.mark.rb(depth=3, jump_kind="value", + expect="Down+Return moves Account Type from Securities to 'Cash'") + def test_select_next_account_type_gives_cash(self, ax): + assert wait_for_web(ax) + assert rb_reach_add_account_dialog(ax), "Add Account modal did not open" + before = combobox_value(ax, "Account Type") + open_account_type(ax) + select_next_account_type(ax) + after = combobox_value(ax, "Account Type") + rb_back_escape(2) + assert kit.rb_value(before, "Securities"), \ + f"pre-condition: Account Type should start as 'Securities', got {before!r}" + assert kit.rb_value(after, "Cash"), f"expected Account Type == 'Cash', got {after!r}" + + +# =========================================================================== +# 8. Modal defaults are RECOMPUTED on reopen +# =========================================================================== +class TestModalDefaults: + + @pytest.mark.rb(depth=2, jump_kind="value", + expect="reopened modal defaults: Account Type 'Securities', Currency USD") + def test_modal_defaults_recomputed_on_reopen(self, ax): + assert wait_for_web(ax) + assert rb_reach_add_account_dialog(ax), "Add Account modal did not open" + open_account_type(ax) + select_next_account_type(ax) + changed = combobox_value(ax, "Account Type") + assert kit.rb_value(changed, "Cash"), \ + f"pre-condition: Account Type should be 'Cash' before reopening, got {changed!r}" + rb_back_escape(1) # close the modal (no save) + assert rb_enter_press(ax, "button", "Add account"), "could not reopen the Add Account modal" + vals = combobox_values(ax) + acct_type = vals.get("Account Type") + currency = vals.get("Currency") + rb_back_escape(2) + assert kit.rb_value(acct_type, "Securities"), \ + f"reopened modal should default Account Type to 'Securities', got {acct_type!r}" + assert kit.rb_value(currency, DEFAULT_CURRENCY), \ + f"reopened modal should default Currency to {DEFAULT_CURRENCY!r}, got {currency!r}" + + +# =========================================================================== +# 9. Text-field entry (the second, smaller input -> output pair) +# =========================================================================== +class TestModalTextFieldEntry: + + @pytest.mark.rb(depth=2, jump_kind="value", + expect="Account Name reads back 'SetVal'; placeholder stays 'Account display name'") + def test_account_name_set_value_reads_back(self, ax): + assert wait_for_web(ax) + assert rb_reach_add_account_dialog(ax), "Add Account modal did not open" + tf = named(ax, "text_field", "Account Name") + assert tf is not None, "text_field 'Account Name' not found in the modal" + assert str(tf.value or "") == "", f"field should start empty, got {tf.value!r}" + observed = set_field(ax, "Account Name", "SetVal") + placeholder = placeholder_of(ax, "text_field", "Account Name") + rb_back_escape(2) + assert kit.rb_value(observed, "SetVal") and observed == "SetVal", \ + f"expected Account Name == 'SetVal', got {observed!r}" + assert kit.rb_value(placeholder, "Account display name"), \ + f"placeholder should stay 'Account display name', got {placeholder!r}" + + @pytest.mark.rb(depth=2, jump_kind="value", + expect="Account Group reads back 'RRSP-Group'; placeholder unchanged") + def test_account_group_set_value_reads_back(self, ax): + assert wait_for_web(ax) + assert rb_reach_add_account_dialog(ax), "Add Account modal did not open" + tf = named(ax, "text_field", "Account Group") + assert tf is not None, "text_field 'Account Group' not found in the modal" + observed = set_field(ax, "Account Group", "RRSP-Group") + placeholder = placeholder_of(ax, "text_field", "Account Group") + rb_back_escape(2) + assert kit.rb_value(observed, "RRSP-Group") and observed == "RRSP-Group", \ + f"expected Account Group == 'RRSP-Group', got {observed!r}" + assert kit.rb_value(placeholder, "Retirement, 401K, RRSP, TFSA,..."), \ + f"placeholder should stay 'Retirement, 401K, RRSP, TFSA,...', got {placeholder!r}" + + @pytest.mark.rb(depth=2, jump_kind="value", + expect="reopened modal shows an EMPTY Account Name (typed text discarded)") + def test_account_name_cleared_on_modal_reopen(self, ax): + assert wait_for_web(ax) + assert rb_reach_add_account_dialog(ax), "Add Account modal did not open" + tf = named(ax, "text_field", "Account Name") + assert tf is not None, "text_field 'Account Name' not found in the modal" + assert set_field(ax, "Account Name", "SetVal") == "SetVal", \ + "pre-condition: value not written" + rb_back_escape(1) # close the modal (no save) + assert rb_enter_press(ax, "button", "Add account"), "could not reopen the Add Account modal" + reopened = text_field_value(ax, "Account Name") + rb_back_escape(2) + assert reopened == "" and kit.rb_value(reopened, ""), \ + f"expected an empty Account Name on reopen, got {reopened!r}" diff --git a/macos/wealthfolio-wealthfolio/tests/test_ax_menus.py b/macos/wealthfolio-wealthfolio/tests/test_ax_menus.py new file mode 100644 index 0000000000000000000000000000000000000000..73f443016ecc2dd06ac39c6835c6e43bbf01343a --- /dev/null +++ b/macos/wealthfolio-wealthfolio/tests/test_ax_menus.py @@ -0,0 +1,847 @@ +#!/usr/bin/env python3 +"""AX MENU tests for Wealthfolio (bundle com.teymz.wealthfolio, Tauri v1 + WebKit). + +Authored ONLY from verifier/recon.md (`## APP`, `## RECIPES`, `## AX_TREE`, `## MENUS`, +`## DO-NOT-TOUCH`). pytest-only: `Test*` classes, methods taking the `ax` fixture, plain +asserts. No argparse, no __main__, no self-written results JSON — the runner scores via +pytest and the conftest `pytest.mark.rb` hook records depth/jump/expect. + +Window reveal: recon `## APP` records `REVEAL_STEPS: None needed` — Wealthfolio is a normal +windowed app (NOT `LSUIElement`/status-item), so the gate before every window-dependent check +is recon's own `wait_for_web(ax)` poll (the REQUIRED first line of every test), which waits for +the WebKit content to enter the AX tree. A blind `ensure_ui_visible()` is deliberately avoided +here: it AXPresses menu-bar items, which would leave a menu open and poison this lane. + +Depth contract for this lane (recon ## MENUS): + * the macOS menu tree is readable WITHOUT opening a menu -> a plain item-name / + cmd-char / enabled read is **depth 0** (`jump_kind="value"`), and so is opening + + cancelling a menu (an in-place `AXSelected` flip, recon M5 -> `jump_kind="transition"`). + * a test that PICKS an item and lands on a NEW top-level window is **depth 1** + (recon M1/M3); it calls the `rb_reach_report_issue` / `rb_reach_about_panel` nav + wrappers around recon's `pick_menu_item`. + * **depth 2** = navigate to a deeper in-app surface FIRST (Settings ▸ Accounts / + ▸ General / the Add Account modal via recon's `rb_*` nav recipes), THEN drive the + menu bar from there. + +NEVER ACTIVATED here (recon ## DO-NOT-TOUCH): Quit Wealthfolio, Quit and Keep Windows, +Close Window, Close All, Minimize, Zoom, Toggle Full Screen, Hide Wealthfolio, +Hide Others, Show All, Start Dictation…, Emoji & Symbols, anything under Services, and +every item of the Apple menu — existence / enabled / cmd-char reads only. The DB-writing +buttons (`Save`, the modal's `Add Account` submit) are likewise never pressed. +""" + +import json +import os +import subprocess +import time + +import pytest + +import rb_testgen_kit as kit +import verifier_helpers as helpers + +RESULTS_DIR = os.environ.get( + "RESULTS_DIR", + os.path.join(os.path.dirname(os.path.abspath(__file__)), "results"), +) + + +# ─────────────────────────── screenshot assertions ─────────────────────────── +def screenshot_assert(test_name, description, results_dir): + 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) + + +# ════════════════════ recon ## RECIPES helpers (copied verbatim) ════════════════════ +def wait_for_web(ax, timeout=20.0): + """REQUIRED first line of every test: poll until the WebKit content is in the AX tree.""" + deadline = time.time() + timeout + while time.time() < deadline: + for e in web_els(ax): + if e.role == "link" and e.name == "Settings": + return True + time.sleep(0.4) + return False + + +def web_els(ax): + """All elements inside the app's web area (excludes the menu bar).""" + wa = ax.find(role="webarea", max_results=2) + if not wa: + return [] + return ax.find(max_results=1500, root_id=wa[0].id, max_depth=25) + + +def named(ax, role, name): + for e in web_els(ax): + if e.role == role and (e.name or "") == name: + return e + return None + + +def open_app_menu(ax, menu_name): + """AXPress the AXMenuBarItem. While open its AXSelected flips True (verified).""" + mbi = [e for e in ax.find(role="menu_bar_item", max_results=12) if e.name == menu_name] + if not mbi: + return None + ax.action(mbi[0].id, "AXPress") + time.sleep(0.8) + return mbi[0] + + +def menu_items(ax, mbi): + return ax.find(role="menu_item", root_id=mbi.id, max_results=60) + + +def pick_menu_item(ax, menu_name, item_name): + mbi = open_app_menu(ax, menu_name) + for it in menu_items(ax, mbi): + if it.name == item_name: + ax.action(it.id, "AXPress") + time.sleep(1.6) + return True + ax.action(mbi.id, "AXCancel") + return False + + +def ax_attr(ax, el, attr): + """Read a raw AX attribute (AXHelp / AXSelected / AXPlaceholderValue / AXMenuItemCmdChar / …).""" + import ApplicationServices as AS + err, v = AS.AXUIElementCopyAttributeValue(ax._get_ref(el.id), attr, None) + return v if err == 0 else None + + +def rb_back_escape(n=1): + """Escape closes (in order) popover -> dialog -> menu. VERIFIED reliable.""" + for _ in range(n): + helpers.send_key(helpers.KC_ESCAPE) + time.sleep(0.6) + + +def rb_enter_press(ax, role, name, wait=1.6): + """AXPress a named link/button and settle. Returns True if the element existed.""" + el = named(ax, role, name) + if el is None: + return False + ax.action(el.id, "AXPress") + time.sleep(wait) + return True + + +def rb_enter_settings(ax): + """Sidebar 'Settings' link -> Settings ▸ General surface (depth 1).""" + return rb_enter_press(ax, "link", "Settings") + + +def rb_enter_settings_tab(ax, tab): + """Settings sub-nav link: 'General' | 'Accounts' | 'Goals' | 'Appearance' (depth 1).""" + return rb_enter_press(ax, "link", tab) + + +def rb_reach_accounts(ax): + """Settings ▸ Accounts (depth 1): sidebar Settings, then the 'Accounts' sub-nav link.""" + rb_enter_settings(ax) + return rb_enter_settings_tab(ax, "Accounts") + + +# ════════════════════════ menu-lane helpers (this module) ════════════════════════ +def norm(s): + """Normalize a menu label: unify the ellipsis glyph and collapse whitespace.""" + return " ".join(str(s or "").replace("…", "...").split()) + + +def menu_bar_item(ax, name): + """Locate a menu bar item by its VISIBLE label + role (never by index/path).""" + for e in ax.find(role="menu_bar_item", max_results=12, max_depth=4): + if norm(e.name) == norm(name): + return e + return None + + +def menu_bar_names(ax): + return [norm(e.name) for e in ax.find(role="menu_bar_item", max_results=12, max_depth=4)] + + +def top_items(ax, mbi): + """The DIRECT items of one menu: menu_bar_item(0) -> menu(1) -> menu_item(2). + max_depth=2 deliberately excludes submenu contents.""" + return ax.find(role="menu_item", root_id=mbi.id, max_results=60, max_depth=2) + + +def item_names(ax, menu_name): + """['About Wealthfolio', '', 'Services', …] — '' entries are separators.""" + mbi = menu_bar_item(ax, menu_name) + if mbi is None: + return None + return [norm(i.name) for i in top_items(ax, mbi)] + + +def named_items(ax, menu_name): + return [n for n in (item_names(ax, menu_name) or []) if n] + + +def joined(names): + return " | ".join(norm(n) for n in names if norm(n)) + + +def menu_index(ax, menu_name): + """{normalized item label: element} for the direct items of one menu.""" + mbi = menu_bar_item(ax, menu_name) + if mbi is None: + return {} + return {norm(i.name): i for i in top_items(ax, mbi) if norm(i.name)} + + +def submenu_of(ax, menu_name, item_name): + """The AXMenu child of a named menu item == that item IS a submenu. + + Recon: the whole menu tree is readable WITHOUT opening a menu, so the cold read is + tried first. Fallback (a framework that only materialises submenus on demand): pull + the parent menu down, re-read, then ALWAYS AXCancel it. Still depth 0 — a menu is not + a new app surface per recon's depth contract.""" + def _lookup(): + mbi = menu_bar_item(ax, menu_name) + if mbi is None: + return None + for it in top_items(ax, mbi): + if norm(it.name) == norm(item_name): + subs = ax.find(role="menu", root_id=it.id, max_results=3, max_depth=1) + if subs: + return subs[0] + return None + + sub = _lookup() + if sub is not None: + return sub + mbi = open_app_menu(ax, menu_name) + if mbi is None: + return None + try: + return _lookup() + finally: + ax.action(mbi.id, "AXCancel") + time.sleep(0.5) + if bool(ax_attr(ax, mbi, "AXSelected")): + rb_back_escape(1) + + +def submenu_item_names(ax, submenu): + return [norm(i.name) for i in + ax.find(role="menu_item", root_id=submenu.id, max_results=40, max_depth=1)] + + +def top_level_windows(ax): + """The app's TOP-LEVEL windows (direct children of the application element) — the + quantity recon D8 measures: 1 on launch, 2 with the Report Issue alert open.""" + return ax.find(role="window", max_results=10, max_depth=1) + + +def window_text_blob(ax, win_id): + """Every name/value string inside one window, as one searchable blob.""" + out = [] + for e in ax.find(root_id=win_id, max_results=300, max_depth=15): + for s in (e.name, e.value): + if s: + out.append(str(s)) + return " || ".join(out) + + +def aux_windows(ax): + """Native auxiliary surfaces == containers that are NOT the main web-content window. + + Recon: the Report Issue alert and the About panel are SEPARATE top-level `window`s + that carry no `webarea`. Detection also accepts `dialog`/`sheet` and one extra level + of nesting so a recreation that parents its alert differently is still FOUND (the + exact 1->2 top-level count is asserted separately, via top_level_windows).""" + out, seen = [], set() + for role in ("window", "dialog", "sheet"): + for w in ax.find(role=role, max_results=10, max_depth=2): + if w.id in seen: + continue + seen.add(w.id) + if ax.find(role="webarea", root_id=w.id, max_results=1, max_depth=6): + continue # that is the main app window + out.append(w) + return out + + +def alert_window(ax): + """The native `Help ▸ Report Issue` alert window (recon M1: window 'alert').""" + aux = aux_windows(ax) + for w in aux: + if norm(w.name).lower() == "alert": + return w + for w in aux: # semantic fallback: its title text + if "Contact Support" in window_text_blob(ax, w.id): + return w + return None + + +def about_window(ax): + """The native `Wealthfolio ▸ About Wealthfolio` window (recon M3: untitled window + carrying a 'Version …' label).""" + for w in aux_windows(ax): + blob = window_text_blob(ax, w.id) + if "Version" in blob and "Contact Support" not in blob: + return w + return None + + +def about_labels(ax, win): + return [str(e.value or e.name or "").strip() for e in + ax.find(role="label", root_id=win.id, max_results=60, max_depth=12)] + + +# ── depth family: the ONLY two real surface jumps of this lane (recon M1 / M3) ── +def _pick(ax, menu_name, item_name): + """Guarded `pick_menu_item`: tolerates a missing menu and a differently-punctuated + label (… vs ...), and never leaves a menu pulled down.""" + if menu_bar_item(ax, menu_name) is None: + return False + if pick_menu_item(ax, menu_name, item_name): + return True + mbi = open_app_menu(ax, menu_name) # tolerant retry on the visible label + if mbi is None: + return False + for it in menu_items(ax, mbi): + if norm(it.name) == norm(item_name): + ax.action(it.id, "AXPress") + time.sleep(1.6) + return True + ax.action(mbi.id, "AXCancel") + time.sleep(0.5) + return False + + +def rb_reach_report_issue(ax): + """depth 1: `Help ▸ Report Issue` -> the native 'Contact Support' alert window.""" + return _pick(ax, "Help", "Report Issue") + + +def rb_reach_about_panel(ax): + """depth 1: `Wealthfolio ▸ About Wealthfolio` -> the native About window.""" + return _pick(ax, "Wealthfolio", "About Wealthfolio") + + +def rb_reach_add_account_dialog(ax): + """Settings ▸ Accounts ▸ 'Add account' -> the Add Account modal (depth 2). + Recon B3: a SAFE press (the DB-writing submit button is never touched).""" + rb_reach_accounts(ax) + return rb_enter_press(ax, "button", "Add account") + + +def rb_back_dismiss_alert(ax): + """ALWAYS call after opening the Report Issue alert: AXPress its 'OK' button + (recon M2), Escape as a fallback.""" + for _ in range(2): + if alert_window(ax) is None: + break + oks = [b for b in ax.find(role="button", name="OK", max_results=5)] + if not oks: + break + ax.action(oks[0].id, "AXPress") + time.sleep(0.8) + if aux_windows(ax): # detection may differ -> generic dismiss + rb_back_escape(1) + return alert_window(ax) is None + + +def rb_back_close_about(ax): + """Dismiss the About window with ⌘W (recon M4). + + STRICTLY GUARDED, because ⌘W is also `Close Window` on the MAIN window (a + DO-NOT-TOUCH action): the keystroke is only ever sent while `about_window()` is + actually present, and only while it keeps making progress. Escape is the fallback — + never a second speculative ⌘W.""" + for _ in range(2): + win = about_window(ax) + if win is None: + return True + n = len(aux_windows(ax)) + helpers.send_key(helpers.KC_W, ["cmd"]) + time.sleep(0.9) + if len(aux_windows(ax)) >= n: # no progress -> stop sending ⌘W + break + if about_window(ax) is not None: + rb_back_escape(1) + return about_window(ax) is None + + +# ───────────────────────── observed constants (recon ## MENUS) ───────────────────────── +APP_MENUS = ["Wealthfolio", "File", "Edit", "View", "Window", "Help"] +APP_MENU_ITEMS = ["About Wealthfolio", "Services", "Hide Wealthfolio", "Hide Others", + "Show All", "Quit Wealthfolio", "Quit and Keep Windows"] +FILE_ITEMS = ["Close Window", "Close All"] +EDIT_ITEMS = ["Undo", "Redo", "Cut", "Copy", "Paste", "Select All", "AutoFill", + "Start Dictation...", "Emoji & Symbols"] +VIEW_ITEMS = ["Toggle Full Screen"] +WINDOW_ITEMS = ["Minimize", "Zoom", "Close Window"] +SEPARATOR_MENUS = ("Wealthfolio", "Edit", "Window") # menus that own '' separators +SUPPORT_MSG = "If you encounter any issues, please email us at wealthfolio@teymz.com" +CMD_CHARS = [ + ("Wealthfolio", "Quit Wealthfolio", "Q"), + ("Wealthfolio", "Hide Wealthfolio", "H"), + ("File", "Close Window", "W"), + ("Edit", "Undo", "Z"), + ("Edit", "Cut", "X"), + ("Edit", "Copy", "C"), + ("Edit", "Paste", "V"), + ("Edit", "Select All", "A"), + ("View", "Toggle Full Screen", "F"), + ("Window", "Minimize", "M"), +] + + +# ══════════════════════════════════ STRUCTURE (depth 0) ══════════════════════════════════ +class TestMenuBarStructure: + """The macOS menu tree is exposed without opening a menu -> honest depth 0 reads.""" + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="menu bar exposes the 6 app menus in order " + "'Wealthfolio | File | Edit | View | Window | Help' plus the system 'Apple' menu") + def test_menu_bar_exposes_six_app_menus(self, ax): + assert wait_for_web(ax) + names = menu_bar_names(ax) + assert "Apple" in names, f"system Apple menu missing: {names}" + assert kit.rb_value(joined(names), joined(APP_MENUS)), \ + f"menu bar is {names!r}, expected the 6 app menus {APP_MENUS!r}" + for m in APP_MENUS: + assert menu_bar_item(ax, m) is not None, f"menu '{m}' missing" + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="Wealthfolio menu named items == About Wealthfolio, Services, " + "Hide Wealthfolio, Hide Others, Show All, Quit Wealthfolio, Quit and Keep Windows") + def test_wealthfolio_menu_named_items(self, ax): + assert wait_for_web(ax) + got = named_items(ax, "Wealthfolio") + assert got is not None, "Wealthfolio app menu missing from the menu bar" + assert kit.rb_value(joined(got), joined(APP_MENU_ITEMS)), \ + f"Wealthfolio menu items are {got!r}, expected {APP_MENU_ITEMS!r}" + assert len(got) == len(APP_MENU_ITEMS), \ + f"expected exactly {len(APP_MENU_ITEMS)} named items, got {got!r}" + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="File menu named items == Close Window, Close All (never activated)") + def test_file_menu_named_items(self, ax): + assert wait_for_web(ax) + got = named_items(ax, "File") + assert got is not None, "File menu missing from the menu bar" + assert kit.rb_value(joined(got), joined(FILE_ITEMS)), \ + f"File menu items are {got!r}, expected {FILE_ITEMS!r}" + assert len(got) == len(FILE_ITEMS), f"expected exactly 2 File items, got {got!r}" + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="Edit menu named items == Undo, Redo, Cut, Copy, Paste, Select All, " + "AutoFill, Start Dictation…, Emoji & Symbols") + def test_edit_menu_named_items(self, ax): + assert wait_for_web(ax) + got = named_items(ax, "Edit") + assert got is not None, "Edit menu missing from the menu bar" + assert kit.rb_value(joined(got), joined(EDIT_ITEMS)), \ + f"Edit menu items are {got!r}, expected {EDIT_ITEMS!r}" + assert len(got) == len(EDIT_ITEMS), \ + f"expected exactly {len(EDIT_ITEMS)} named Edit items, got {got!r}" + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="View menu named items == Toggle Full Screen; " + "Window menu named items == Minimize, Zoom, Close Window") + def test_view_and_window_menu_named_items(self, ax): + assert wait_for_web(ax) + view = named_items(ax, "View") + win = named_items(ax, "Window") + assert view is not None and win is not None, "View / Window menu missing" + assert kit.rb_value(joined(view), joined(VIEW_ITEMS)), \ + f"View menu items are {view!r}, expected {VIEW_ITEMS!r}" + assert len(view) == 1, f"expected exactly 1 View item, got {view!r}" + assert kit.rb_value(joined(win), joined(WINDOW_ITEMS)), \ + f"Window menu items are {win!r}, expected {WINDOW_ITEMS!r}" + assert len(win) == len(WINDOW_ITEMS), \ + f"expected exactly {len(WINDOW_ITEMS)} named Window items, got {win!r}" + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="Help menu contains the named item 'Report Issue' (its first row is " + "the unnamed system search item -> membership, not an exact count)") + def test_help_menu_contains_report_issue(self, ax): + assert wait_for_web(ax) + rows = item_names(ax, "Help") + assert rows is not None, "Help menu missing from the menu bar" + assert len(rows) >= 1, "Help menu has no items" + got = [n for n in rows if n] + assert kit.rb_value(joined(got), "Report Issue"), \ + f"Help menu named items are {got!r}, expected 'Report Issue' among them" + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="Wealthfolio ▸ Services and Edit ▸ AutoFill are SUBMENUS (AXMenu " + "children); AutoFill holds 'Contact…' and 'Passwords…'") + def test_submenus_services_and_autofill(self, ax): + assert wait_for_web(ax) + services = submenu_of(ax, "Wealthfolio", "Services") + assert services is not None, \ + "Wealthfolio ▸ Services exposes no AXMenu child (not a submenu)" + assert services.role == "menu", \ + f"Services child role is {services.role!r}, expected 'menu'" + # Service NAMES are machine-provided (Instruments etc.) -> count only, never names. + assert len(submenu_item_names(ax, services)) >= 1, "Services submenu is empty" + + autofill = submenu_of(ax, "Edit", "AutoFill") + assert autofill is not None, \ + "Edit ▸ AutoFill exposes no AXMenu child (not a submenu)" + assert autofill.role == "menu", \ + f"AutoFill child role is {autofill.role!r}, expected 'menu'" + blob = joined(submenu_item_names(ax, autofill)) + assert kit.rb_value(blob, "Contact"), f"AutoFill submenu items are {blob!r}" + assert kit.rb_value(blob, "Passwords"), f"AutoFill submenu items are {blob!r}" + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="AXMenuItemCmdChar: Quit=Q Hide=H Close Window=W Undo=Z Cut=X Copy=C " + "Paste=V Select All=A Toggle Full Screen=F Minimize=M") + def test_menu_item_keyboard_equivalents(self, ax): + assert wait_for_web(ax) + cache, observed, expected = {}, [], [] + for menu, item, char in CMD_CHARS: + if menu not in cache: + cache[menu] = menu_index(ax, menu) + el = cache[menu].get(norm(item)) + assert el is not None, f"{menu} ▸ {item} missing" + raw = ax_attr(ax, el, "AXMenuItemCmdChar") + observed.append(f"{item}={str(raw).upper() if raw else ''}") + expected.append(f"{item}={char}") + assert kit.rb_value(" ; ".join(observed), " ; ".join(expected)), \ + f"cmd chars are {observed!r}, expected {expected!r}" + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="every NAMED menu item reports enabled=True; separator items " + "(name=='') in Wealthfolio/Edit/Window report enabled=False") + def test_named_items_enabled_and_separators_disabled(self, ax): + assert wait_for_web(ax) + bad_named, bad_sep, n_named, n_sep = [], [], 0, 0 + for m in APP_MENUS: + mbi = menu_bar_item(ax, m) + assert mbi is not None, f"menu '{m}' missing from the menu bar" + for it in top_items(ax, mbi): + label = norm(it.name) + if label: + n_named += 1 + if not it.enabled: + bad_named.append(f"{m}>{label}") + elif m in SEPARATOR_MENUS: + n_sep += 1 + if it.enabled: + bad_sep.append(f"{m}>separator") + assert n_named >= 20, f"only {n_named} named menu items found across {APP_MENUS!r}" + assert n_sep >= 1, "no separator items found in Wealthfolio/Edit/Window" + observed = f"named_disabled={bad_named} separators_enabled={bad_sep}" + assert kit.rb_value(observed, "named_disabled=[] separators_enabled=[]"), observed + + +# ═══════════════════════ MENU OPEN / CLOSE STATE (depth 0, M5) ═══════════════════════ +class TestMenuOpenCloseState: + """AXPress a menu_bar_item -> AXSelected flips False->True; AXCancel -> back to False.""" + + def _open_close_flip(self, ax, menu_name, shot, shot_desc): + assert wait_for_web(ax) + mbi = menu_bar_item(ax, menu_name) + assert mbi is not None, f"menu '{menu_name}' missing from the menu bar" + before = bool(ax_attr(ax, mbi, "AXSelected")) + opened = open_app_menu(ax, menu_name) + assert opened is not None, f"could not AXPress the '{menu_name}' menu bar item" + during = bool(ax_attr(ax, opened, "AXSelected")) + try: + screenshot_assert(shot, shot_desc, RESULTS_DIR) + finally: + ax.action(opened.id, "AXCancel") + time.sleep(0.8) + after = bool(ax_attr(ax, mbi, "AXSelected")) + if after: # belt and braces: never leave a menu open + rb_back_escape(1) + after = bool(ax_attr(ax, mbi, "AXSelected")) + return before, during, after + + @pytest.mark.rb(depth=0, jump_kind="transition", + expect="'Help' menu bar item AXSelected flips False->True while its menu is " + "open and back to False after AXCancel") + def test_help_menu_open_close_flips_selected(self, ax): + before, during, after = self._open_close_flip( + ax, "Help", "menus_help_menu_open", + "The Wealthfolio app's Help menu is pulled down in the macOS menu bar showing the " + "system search row and a 'Report Issue' item; the 'Welcome to Wealthfolio' " + "onboarding window is behind it") + assert kit.rb_flip(before, during), \ + f"AXSelected did not change when the Help menu opened ({before} -> {during})" + assert kit.rb_flip(during, after), \ + f"AXSelected did not change back after AXCancel ({during} -> {after})" + assert (before, during, after) == (False, True, False), \ + f"expected False->True->False, got {(before, during, after)}" + + @pytest.mark.rb(depth=0, jump_kind="transition", + expect="'Edit' menu bar item AXSelected flips False->True while its menu is " + "open and back to False after AXCancel") + def test_edit_menu_open_close_flips_selected(self, ax): + before, during, after = self._open_close_flip( + ax, "Edit", "menus_edit_menu_open", + "The Edit menu is pulled down in the macOS menu bar showing Undo, Redo, a separator, " + "Cut, Copy, Paste, Select All, a separator, AutoFill with a submenu arrow, " + "Start Dictation… and Emoji & Symbols") + assert kit.rb_flip(before, during), \ + f"AXSelected did not change when the Edit menu opened ({before} -> {during})" + assert kit.rb_flip(during, after), \ + f"AXSelected did not change back after AXCancel ({during} -> {after})" + assert (before, during, after) == (False, True, False), \ + f"expected False->True->False, got {(before, during, after)}" + + +# ══════════════════ SURFACE JUMP 1 — Help ▸ Report Issue (depth 1, M1/M2) ══════════════════ +class TestReportIssueAlert: + + @pytest.mark.rb(depth=1, jump_kind="reach", + expect="native alert window carrying label 'Contact Support' appears after " + "picking Help ▸ Report Issue, taking the app from 1 to 2 top-level " + "windows (main window content stays -> no source)") + def test_report_issue_opens_contact_support_alert(self, ax): + assert wait_for_web(ax) + n_before = len(top_level_windows(ax)) + before = kit.rb_showing(ax) + assert rb_reach_report_issue(ax), "Help ▸ Report Issue not found / not pressable" + after = kit.rb_showing(ax) + reached, n_after = False, n_before + try: + reached = kit.rb_reach(before, after, target="Contact Support") + n_after = len(top_level_windows(ax)) + screenshot_assert( + "menus_report_issue_alert", + "A native macOS alert sheet in front of the Wealthfolio window showing the app " + "icon, the bold title 'Contact Support', the message 'If you encounter any issues, " + "please email us at wealthfolio@teymz.com' and a single default OK button", + RESULTS_DIR) + assert alert_window(ax) is not None, "no alert window in the AX tree" + finally: + rb_back_dismiss_alert(ax) + assert reached, "label 'Contact Support' did not APPEAR after Help ▸ Report Issue" + assert n_before == 1, f"expected 1 top-level window before, saw {n_before}" + assert n_after == n_before + 1, \ + f"expected {n_before + 1} top-level windows with the alert open, saw {n_after}" + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="the alert reads title 'Contact Support' + the exact message 'If you " + "encounter any issues, please email us at wealthfolio@teymz.com', and " + "exposes button 'OK' plus image 'Wealthfolio alert'") + def test_report_issue_alert_contents(self, ax): + assert wait_for_web(ax) + assert rb_reach_report_issue(ax), "Help ▸ Report Issue not found / not pressable" + blob, ok_name, images = "", "", "" + try: + win = alert_window(ax) + assert win is not None, "Report Issue alert window not found" + blob = window_text_blob(ax, win.id) + oks = [b for b in ax.find(role="button", root_id=win.id, + max_results=20, max_depth=12) + if norm(b.name) == "OK"] + if not oks: # recon: OK lives in the alert, not the web area + oks = ax.find(role="button", name="OK", max_results=5) + assert oks, "no button named 'OK' in the alert" + ok_name = norm(oks[0].name) + assert oks[0].enabled, "the alert's OK button is disabled" + assert "AXPress" in oks[0].actions, "the alert's OK button has no AXPress action" + images = joined([e.name for e in ax.find(role="image", root_id=win.id, + max_results=10, max_depth=12)]) + finally: + rb_back_dismiss_alert(ax) + assert kit.rb_value(blob, "Contact Support"), \ + f"alert has no 'Contact Support' title; alert text = {blob!r}" + assert kit.rb_value(blob, SUPPORT_MSG), \ + f"alert message mismatch; expected {SUPPORT_MSG!r}, alert text = {blob!r}" + assert kit.rb_value(ok_name, "OK"), f"alert default button is {ok_name!r}, expected 'OK'" + assert kit.rb_value(images, "Wealthfolio alert"), \ + f"alert images are {images!r}, expected one named 'Wealthfolio alert'" + + @pytest.mark.rb(depth=1, jump_kind="reach", + expect="AXPress the alert's 'OK' button leaves the alert surface: window " + "'alert' and label 'Contact Support' disappear, back to 1 window") + def test_report_issue_ok_button_dismisses_alert(self, ax): + assert wait_for_web(ax) + n0 = len(top_level_windows(ax)) + s0 = kit.rb_showing(ax) + assert rb_reach_report_issue(ax), "Help ▸ Report Issue not found / not pressable" + s1 = kit.rb_showing(ax) + oks = ax.find(role="button", name="OK", max_results=5) + assert oks, "no button named 'OK' to dismiss the alert" + ax.action(oks[0].id, "AXPress") + time.sleep(1.0) + s2 = kit.rb_showing(ax) + gone = alert_window(ax) is None + n2 = len(top_level_windows(ax)) + if not gone: + rb_back_dismiss_alert(ax) + opened = kit.rb_reach(s0, s1, target="Contact Support") + # reverse-direction proof: 'Contact Support' is present in s1 and ABSENT in s2, + # i.e. pressing OK left the alert surface. + closed = kit.rb_reach(s2, s1, target="Contact Support") + assert opened, "the alert never appeared, so its dismissal cannot be proven" + assert closed, "label 'Contact Support' still in the AX tree after pressing OK" + assert gone, "the alert window is still present after pressing OK" + assert n2 == n0, f"expected {n0} top-level window(s) after OK, saw {n2}" + + +# ═════════════ SURFACE JUMP 2 — Wealthfolio ▸ About Wealthfolio (depth 1, M3/M4) ═════════════ +class TestAboutPanel: + + @pytest.mark.rb(depth=1, jump_kind="reach", + expect="a new untitled window carrying a 'Version …' label appears after " + "picking Wealthfolio ▸ About Wealthfolio (no source disappears)") + def test_about_wealthfolio_opens_version_window(self, ax): + assert wait_for_web(ax) + n_before = len(top_level_windows(ax)) + before = kit.rb_showing(ax) + assert rb_reach_about_panel(ax), "Wealthfolio ▸ About Wealthfolio not found / not pressable" + after = kit.rb_showing(ax) + reached, n_after = False, n_before + try: + reached = kit.rb_reach(before, after, target="Version") + n_after = len(top_level_windows(ax)) + screenshot_assert( + "menus_about_panel", + "A small native macOS About window in front of the Wealthfolio app showing the " + "Wealthfolio app icon, the app name 'Wealthfolio' and a 'Version …' line", + RESULTS_DIR) + finally: + rb_back_close_about(ax) + assert reached, "no 'Version' label APPEARED after Wealthfolio ▸ About Wealthfolio" + assert n_after == n_before + 1, \ + f"expected {n_before + 1} top-level windows with the About panel open, saw {n_after}" + + @pytest.mark.rb(depth=1, jump_kind="reach", + expect="the About window brings image 'Wealthfolio icon' into the tree and " + "holds a label whose value starts with 'Version'") + def test_about_panel_shows_icon_and_version_label(self, ax): + assert wait_for_web(ax) + before = kit.rb_showing(ax) + assert rb_reach_about_panel(ax), "Wealthfolio ▸ About Wealthfolio not found / not pressable" + after = kit.rb_showing(ax) + icon_reached, labels = False, [] + try: + icon_reached = kit.rb_reach(before, after, target="Wealthfolio icon") + win = about_window(ax) + assert win is not None, "About window not found in the AX tree" + labels = about_labels(ax, win) + finally: + rb_back_close_about(ax) + assert icon_reached, "image 'Wealthfolio icon' did not appear with the About window" + # NEVER assert the version NUMBER (build-specific) — only the 'Version' prefix. + assert any(t.startswith("Version") for t in labels), \ + f"no label starting with 'Version' in the About window: {labels!r}" + + @pytest.mark.rb(depth=1, jump_kind="reach", + expect="⌘W on the About window leaves that surface: the 'Version' label " + "disappears and the window count returns to 1") + def test_about_panel_closes_with_cmd_w(self, ax): + assert wait_for_web(ax) + n0 = len(top_level_windows(ax)) + s0 = kit.rb_showing(ax) + assert rb_reach_about_panel(ax), "Wealthfolio ▸ About Wealthfolio not found / not pressable" + s1 = kit.rb_showing(ax) + assert about_window(ax) is not None, "About window not found — ⌘W not sent" + helpers.send_key(helpers.KC_W, ["cmd"]) + time.sleep(1.0) + s2 = kit.rb_showing(ax) + gone = about_window(ax) is None + n2 = len(top_level_windows(ax)) + if not gone: + rb_back_close_about(ax) + opened = kit.rb_reach(s0, s1, target="Version") + # reverse-direction proof: the 'Version' label is in s1 and ABSENT in s2. + closed = kit.rb_reach(s2, s1, target="Version") + assert opened, "the About window never appeared, so its dismissal cannot be proven" + assert closed, "a 'Version' label is still in the AX tree after ⌘W" + assert gone, "the About window is still present after ⌘W" + assert n2 == n0, f"expected {n0} top-level window(s) after ⌘W, saw {n2}" + + +# ═════════════ MENUS STAY LIVE FROM A DEEPER IN-APP SURFACE (depth 2) ═════════════ +class TestMenusFromDeeperSurface: + """The menu bar must still drive its native windows once the app has navigated away + from the launch surface: nav to a deeper in-app surface FIRST (depth 1), then pick the + menu item that opens a new top-level window (depth 2).""" + + @pytest.mark.rb(depth=2, jump_kind="reach", + expect="from Settings ▸ Accounts, Help ▸ Report Issue still reaches the " + "'Contact Support' alert while the accounts page stays in the tree") + def test_report_issue_reachable_from_accounts_surface(self, ax): + assert wait_for_web(ax) + assert rb_reach_accounts(ax), "sidebar Settings ▸ Accounts navigation failed" + assert named(ax, "button", "Add account") is not None, \ + "not on the Settings ▸ Accounts surface (no 'Add account' button)" + before = kit.rb_showing(ax) + assert rb_reach_report_issue(ax), "Help ▸ Report Issue not found / not pressable" + after = kit.rb_showing(ax) + reached, still_there = False, False + try: + reached = kit.rb_reach(before, after, target="Contact Support") + still_there = named(ax, "button", "Add account") is not None + screenshot_assert( + "menus_report_issue_over_accounts", + "The Wealthfolio Settings ▸ Accounts page ('Accounts' heading, an 'Add account' " + "button and the dashed empty-state card 'No account added!') with a native macOS " + "'Contact Support' alert about emailing wealthfolio@teymz.com on top of it", + RESULTS_DIR) + finally: + rb_back_dismiss_alert(ax) + assert reached, "label 'Contact Support' did not APPEAR from the Accounts surface" + assert still_there, \ + "the accounts page left the AX tree — the native alert must not hide app content" + + @pytest.mark.rb(depth=2, jump_kind="reach", + expect="from Settings ▸ General, Wealthfolio ▸ About Wealthfolio still " + "reaches the untitled 'Version …' About window") + def test_about_reachable_from_settings_surface(self, ax): + assert wait_for_web(ax) + assert rb_enter_settings(ax), "sidebar 'Settings' link not found" + assert named(ax, "combobox", "Currency") is not None, \ + "not on the Settings ▸ General surface (no 'Currency' combobox)" + before = kit.rb_showing(ax) + assert rb_reach_about_panel(ax), "Wealthfolio ▸ About Wealthfolio not found / not pressable" + after = kit.rb_showing(ax) + reached, still_there = False, False + try: + reached = kit.rb_reach(before, after, target="Version") + still_there = named(ax, "combobox", "Currency") is not None + finally: + rb_back_close_about(ax) + assert reached, "no 'Version' label APPEARED from the Settings ▸ General surface" + assert still_there, \ + "the settings page left the AX tree — the About window must not hide app content" + + @pytest.mark.rb(depth=2, jump_kind="value", + expect="with the Add Account modal open the menu bar STILL reports all 6 app " + "menus and Edit's clipboard items Undo|Redo|Cut|Copy|Paste|Select All") + def test_menu_bar_intact_while_modal_open(self, ax): + assert wait_for_web(ax) + assert rb_reach_add_account_dialog(ax), \ + "Settings ▸ Accounts ▸ 'Add account' navigation failed" + try: + assert named(ax, "text_field", "Account Name") is not None, \ + "the Add Account modal did not open (no 'Account Name' field)" + names = menu_bar_names(ax) + edit = named_items(ax, "Edit") + finally: + rb_back_escape(1) # recon D7: Escape closes the modal + assert kit.rb_value(joined(names), joined(APP_MENUS)), \ + f"menu bar is {names!r} with the modal open, expected {APP_MENUS!r}" + assert kit.rb_value(joined(edit), joined(EDIT_ITEMS[:6])), \ + f"Edit menu is {edit!r} with the modal open, expected the clipboard items to remain" + diff --git a/macos/wealthfolio-wealthfolio/tests/test_ax_states.py b/macos/wealthfolio-wealthfolio/tests/test_ax_states.py new file mode 100644 index 0000000000000000000000000000000000000000..08f59f4db4e682fcba92d4450d36e2cbb9bd6530 --- /dev/null +++ b/macos/wealthfolio-wealthfolio/tests/test_ax_states.py @@ -0,0 +1,928 @@ +"""test_ax_states.py — AX STATE verification for Wealthfolio (com.teymz.wealthfolio, Tauri v1 + WebKit). + +Owner lane: CHECKED / toggle state, focus, ENABLED sweeps, menu-item + menu-open state, +window state and geometry state. Every fact asserted here comes from the recon report's +`## STATE` table (T1–T12) plus `## AX_TREE` / `## RECIPES`. + +Harness: pytest only. Each test is a method on a `Test*` class taking the `ax` fixture +(conftest launches a FRESH app per test — the starting surface is always the collapsed-sidebar +"Welcome to Wealthfolio" onboarding page). Depth + jump rigor are DECLARED per test with +`@pytest.mark.rb(...)`; every `transition` is backed by `kit.rb_flip()` and every `value` by +`kit.rb_value()`, whose bool IS the assertion. + +Window reveal: Wealthfolio is a normal windowed app (recon `REVEAL_STEPS: None needed`) — the +window is on screen at launch. `wait_for_web()` is the readiness gate used as the first line of +every test; `ensure_window_visible()` additionally runs the generic reveal paths as a fallback +before the window-state checks, so a recreation that hides its window still gets a fair chance. + +NEVER pressed here (recon `## DO-NOT-TOUCH`): `button 'Save'`, the modal's `button 'Add Account'` +submit, the window chrome buttons, and every Quit/Close/Minimize/Zoom/Full-Screen/Hide/Services +menu item. Menus are only OPENED and then `AXCancel`-ed. + +Widget classes the recon shows this app does NOT have, so no test can exist for them: + * `AXRadioButton` / radio MENU items — there is no radio group anywhere in the AX tree. The + app's mode selector is a Radix Select (`combobox 'Account Type'`, exactly one of + Securities/Cash/Crypto active at a time) — that "exactly one selected" invariant is covered + by `test_account_type_mode_flips_securities_to_cash`. + * `AXToolbar` — the window has no toolbar; the sidebar `group 'Sidebar'` plays that role and its + links/button are swept for ENABLED + tree-presence (SHOWING) and geometry state instead. + * check MENU items — no menu in the bar carries `AXMenuItemMarkChar`; the two CHECKED-state + widgets are the modal's `checkbox 'Default Account'` / `checkbox 'Is Active'` switches. +Dead ends verified by recon and deliberately avoided: `AXExpanded` on the Currency combobox (stays +False while its popover is open), `AXSelected` on nav links (always False), the app-level +`AXFocusedUIElement` (returns empty) and Tab-key focus movement (does not move focus). +""" + +import json +import os +import re +import subprocess +import time + +import pytest + +import rb_testgen_kit as kit +import verifier_helpers as helpers + +# Raw AX reads (element-ref level). We never create an AX app handle ourselves — the `ax` +# fixture owns the app, so the same test drives the reference AND the recreation. +from ApplicationServices import ( + AXUIElementCopyAttributeValue, + AXUIElementCopyActionNames, +) + +RESULTS_DIR = os.environ.get( + "RESULTS_DIR", os.path.join(os.path.dirname(os.path.abspath(__file__)), "results") +) + +# Sidebar nav links (recon SURFACE A) and the roles that carry interactive state. +SIDEBAR_LINKS = {"Dashboard", "Holdings", "Activities", "Settings"} +INTERACTIVE_ROLES = ("link", "button", "checkbox", "combobox", "text_field", "popup", "radio") +APP_MENUS = ("Wealthfolio", "File", "Edit", "View", "Window", "Help") + + +# --------------------------------------------------------------------------- +# screenshot assertions (VLM-judged later) +# --------------------------------------------------------------------------- + +def screenshot_assert(test_name, description, results_dir): + 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) + + +# --------------------------------------------------------------------------- +# raw AX read helpers +# --------------------------------------------------------------------------- + +def get_attr(el_ref, attr): + """Read one AX attribute straight off an element ref (AXElement.ref).""" + try: + err, val = AXUIElementCopyAttributeValue(el_ref, attr, None) + return val if err == 0 else None + except Exception: + return None + + +def get_actions(el_ref): + try: + err, actions = AXUIElementCopyActionNames(el_ref, None) + return list(actions) if err == 0 and actions else [] + except Exception: + return [] + + +def walk_tree(el_ref, depth=0, max_depth=25): + """Generic read-only AX walk from an element ref: yields (depth, role, title, ref). + Framework-independent — matches on AXRole/AXTitle only, never on child index or path. + (No set_value/AXUIElementCreateApplication counterpart on purpose: this lane never + writes an AXValue, and the app handle belongs to the `ax` fixture.)""" + role = get_attr(el_ref, "AXRole") or "" + title = get_attr(el_ref, "AXTitle") or get_attr(el_ref, "AXDescription") or "" + yield (depth, str(role), str(title), el_ref) + if depth < max_depth: + for child in (get_attr(el_ref, "AXChildren") or []): + for sub in walk_tree(child, depth + 1, max_depth): + yield sub + + +# --------------------------------------------------------------------------- +# RECIPES (copied verbatim from recon `## RECIPES` — verified interaction primitives) +# --------------------------------------------------------------------------- + +def wait_for_web(ax, timeout=20.0): + """REQUIRED first line of every test: poll until the WebKit content is in the AX tree.""" + deadline = time.time() + timeout + while time.time() < deadline: + for e in web_els(ax): + if e.role == "link" and e.name == "Settings": + return True + time.sleep(0.4) + return False + + +def web_els(ax): + """All elements inside the app's web area (excludes the menu bar).""" + wa = ax.find(role="webarea", max_results=2) + if not wa: + return [] + return ax.find(max_results=1500, root_id=wa[0].id, max_depth=25) + + +def by_role(ax, role): + return [e for e in web_els(ax) if e.role == role] + + +def named(ax, role, name): + for e in web_els(ax): + if e.role == role and (e.name or "") == name: + return e + return None + + +# ---------- navigation (rb_enter_* / rb_reach_* so the depth audit sees them) ---------- +def rb_enter_press(ax, role, name, wait=1.6): + """AXPress a named link/button and settle. Returns True if the element existed.""" + el = named(ax, role, name) + if el is None: + return False + ax.action(el.id, "AXPress") + time.sleep(wait) + return True + + +def rb_enter_settings(ax): + """Sidebar 'Settings' link -> Settings ▸ General surface (depth 1).""" + return rb_enter_press(ax, "link", "Settings") + + +def rb_enter_settings_tab(ax, tab): + """Settings sub-nav link: 'General' | 'Accounts' | 'Goals' | 'Appearance' (depth 1).""" + return rb_enter_press(ax, "link", tab) + + +def rb_reach_accounts(ax): + """Settings ▸ Accounts (depth 1): sidebar Settings, then the 'Accounts' sub-nav link.""" + rb_enter_settings(ax) + return rb_enter_settings_tab(ax, "Accounts") + + +def rb_reach_add_account_dialog(ax): + """Settings ▸ Accounts ▸ 'Add account' -> the Add Account modal (depth 2).""" + rb_reach_accounts(ax) + return rb_enter_press(ax, "button", "Add account") + + +def rb_enter_currency_popover(ax): + """AXPress the 'Currency' combobox -> the currency search popover. + depth 2 from home (via Settings▸General) / depth 3 from inside the Add Account dialog.""" + return rb_enter_press(ax, "combobox", "Currency", wait=1.5) + + +def rb_back_escape(n=1): + """Escape closes (in order) popover -> dialog -> menu. VERIFIED reliable.""" + for _ in range(n): + helpers.send_key(helpers.KC_ESCAPE) + time.sleep(0.6) + + +def currency_search_field(ax): + """The popover's search input == the only combobox with an EMPTY name.""" + for e in web_els(ax): + if e.role == "combobox" and not (e.name or ""): + return e + return None + + +def pick_currency(ax, label): + """AXPress the option row whose name == label (works), then Escape to close the popover. + Afterwards the 'Currency' combobox VALUE equals that label.""" + for e in web_els(ax): + if e.role == "label" and e.name == label: + ax.action(e.id, "AXPress") + break + time.sleep(0.9) + rb_back_escape(1) + + +# ---------- Radix Select ('Account Type') ---------- +def open_account_type(ax): + """AXPress does NOT open a Radix Select, and the combobox's own AX frame is bogus. + CG-click its CHILD label (the one whose VALUE is the current selection) — verified.""" + cur = None + for e in web_els(ax): + if e.role == "label" and (e.value or "").strip() in ("Securities", "Cash", "Crypto") \ + and "AXPress" in e.actions: + cur = e + break + ax.click_element_cg(cur.id) + time.sleep(1.2) + return [e.name for e in web_els(ax) if e.role == "label" and e.name] # ['Securities','Cash','Crypto'] + + +def select_next_account_type(ax): + """Inside the open Select portal, Down + Return picks the NEXT option (verified).""" + helpers.send_key(helpers.KC_DOWN_ARROW); time.sleep(0.4) + helpers.send_key(helpers.KC_RETURN); time.sleep(1.2) + + +# ---------- menu bar ---------- +def open_app_menu(ax, menu_name): + """AXPress the AXMenuBarItem. While open its AXSelected flips True (verified).""" + mbi = [e for e in ax.find(role="menu_bar_item", max_results=12) if e.name == menu_name] + if not mbi: + return None + ax.action(mbi[0].id, "AXPress") + time.sleep(0.8) + return mbi[0] + + +def menu_items(ax, mbi): + return ax.find(role="menu_item", root_id=mbi.id, max_results=60) + + +def ax_attr(ax, el, attr): + """Read a raw AX attribute (AXHelp / AXSelected / AXPlaceholderValue / AXMenuItemCmdChar / …).""" + import ApplicationServices as AS + err, v = AS.AXUIElementCopyAttributeValue(ax._get_ref(el.id), attr, None) + return v if err == 0 else None + + +# --------------------------------------------------------------------------- +# state-lane local helpers (locate by AXTitle/AXDescription + AXRole, never by index) +# --------------------------------------------------------------------------- + +def int_state(v): + """Normalize an AXValue toggle reading (0/1, "0"/"1", True/False) to an int, else None.""" + if v is None or v == "": + return None + if isinstance(v, bool): + return 1 if v else 0 + try: + return int(round(float(str(v).strip()))) + except (TypeError, ValueError): + return None + + +def switch_state(ax, name): + """CHECKED state of the named switch (checkbox) in the current surface: 0 / 1 / None.""" + el = named(ax, "checkbox", name) + return None if el is None else int_state(el.value) + + +def widget_states(ax, el): + """Record the AX state flags for one widget: ENABLED / VISIBLE / SHOWING / FOCUSABLE. + + macOS AX exposes no VISIBLE/SHOWING states, so (as rb_showing() documents) presence in the + live AX tree IS "showing" — an aria-hidden / dismissed surface genuinely drops out of the + tree. FOCUSABLE = the element carries an AXFocused state (settable, or simply exposed). + """ + raw_enabled = get_attr(el.ref, "AXEnabled") + focusable = (ax.is_attribute_settable(el.id, "AXFocused") + or get_attr(el.ref, "AXFocused") is not None) + return { + "ENABLED": bool(el.enabled) if raw_enabled is None else bool(raw_enabled), + "SHOWING": True, # it was just enumerated out of the live AX tree + "VISIBLE": True, + "FOCUSABLE": bool(focusable), + "ACTIONS": get_actions(el.ref) or list(el.actions or []), + } + + +def state_sweep(ax, wanted): + """ONE AX pass -> [(role, name, ENABLED)] for each wanted (role, name) pair. + A missing widget contributes None so the value verdict fails loudly.""" + els = web_els(ax) + out = [] + for role, nm in wanted: + hit = None + for e in els: + if e.role == role and (e.name or "") == nm: + hit = e + break + out.append((role, nm, widget_states(ax, hit)["ENABLED"] if hit is not None else None)) + return out + + +def is_focused(ax, el): + if el is None: + return None + return bool(ax.get(el.id, ["AXFocused"]).get("AXFocused")) + + +def focused_titles(ax): + """Diagnostic: every 'role|title' in the app subtree whose AXFocused reads True. + Used only to explain a focus failure (the recon warns the app-level + AXFocusedUIElement returns empty, so we walk instead of reading it).""" + out = [] + try: + roots = ax.find(role="window", max_results=3, max_depth=2) + for w in roots: + for _d, role, title, ref in walk_tree(w.ref, 0, 20): + if get_attr(ref, "AXFocused") is True: + out.append(f"{role}|{title}") + except Exception: + pass + return out + + +def size_width(ax, el): + """Width out of an AXSize reading. Tolerates every serialization we can get back: + a {'width':…} dict, the raw '' string, or an + 'NSSize: {52, 48}' string (width/height are always the LAST two numbers).""" + if el is None: + return None + v = ax.get(el.id, ["AXSize"]).get("AXSize") + if isinstance(v, dict): + w = v.get("width") + return None if w is None else int(round(float(w))) + s = str(v or "") + m = re.search(r"w:\s*([-\d.]+)", s) + if m: + return int(round(float(m.group(1)))) + nums = re.findall(r"[-\d.]+", s) + if len(nums) >= 2: + try: + return int(round(float(nums[-2]))) + except ValueError: + return None + return None + + +def menu_bar_items(ax): + """{name: AXMenuBarItem} in ONE cheap tree walk (matched by AXTitle, never by index). + A native menu bar is app -> AXMenuBar -> AXMenuBarItem, so depth 3 is plenty; fall back + to an unrestricted walk if a recreation nests it deeper.""" + found = ax.find(role="menu_bar_item", max_results=12, max_depth=3) + if not found: + found = ax.find(role="menu_bar_item", max_results=12) + return {(e.name or ""): e for e in found} + + +def find_menu_bar_item(ax, name): + """The named AXMenuBarItem — read only, does NOT open the menu.""" + return menu_bar_items(ax).get(name) + + +def top_menu_items(ax, mbi): + """Only the DIRECT items of a menu-bar item's menu (menu_bar_item -> menu -> menu_item), + so a submenu's contents are not folded into the sweep.""" + return ax.find(role="menu_item", root_id=mbi.id, max_results=60, max_depth=2) + + +def _pick_main_window(ax): + """The app's MAIN window, located semantically: the one titled 'Wealthfolio' if present, + else the window whose AXMain is True, else the single top-level window. Never by index.""" + wins = ax.find(role="window", max_results=6, max_depth=2) + if not wins: + return None + for w in wins: + if (w.name or "") == "Wealthfolio": + return w + for w in wins: + if ax.get(w.id, ["AXMain"]).get("AXMain"): + return w + return wins[0] if len(wins) == 1 else None + + +def ensure_window_visible(ax): + """Return the main window element. Wealthfolio shows its window at launch (recon: + 'REVEAL_STEPS: None needed'), but run the generic reveal paths (status item / status item -> + menu -> Preferences / ⌘,) as a fallback so no single reveal path is hardcoded. If the window + still cannot be reached this returns None and the caller's assertion fails honestly.""" + win = _pick_main_window(ax) + if win is not None: + return win + try: + ax.ensure_ui_visible() + time.sleep(1.0) + except Exception: + pass + return _pick_main_window(ax) + + +# =========================================================================== +# T1 / T2 / T3 / T4 — CHECKED state of the modal's two toggle switches +# =========================================================================== + +class TestStateSwitchToggles: + + @pytest.mark.rb(depth=2, jump_kind="transition", expect="Default Account switch 0→1") + def test_default_account_switch_turns_on(self, ax): + assert wait_for_web(ax), "WebKit content never appeared" + assert rb_reach_add_account_dialog(ax), "Add Account modal did not open" + cb = named(ax, "checkbox", "Default Account") + assert cb is not None, "checkbox 'Default Account' missing from the Add Account modal" + before = int_state(cb.value) + ax.action(cb.id, "AXPress") + time.sleep(0.9) + after = switch_state(ax, "Default Account") + screenshot_assert( + "states_test_default_account_on", + "The Add Account modal is open over the Accounts page. Its 'Default Account' toggle " + "switch is now ON (filled/dark track with the knob moved to the right) after one " + "press, while the 'Is Active' switch below it is also ON. Fields above read Account " + "Type 'Securities' and Currency 'United States dollar (USD)'.", + RESULTS_DIR, + ) + cb2 = named(ax, "checkbox", "Default Account") # restore: flip it back, close the modal + if cb2 is not None: + ax.action(cb2.id, "AXPress") + time.sleep(0.6) + rb_back_escape(1) + assert kit.rb_flip(before, after), \ + f"'Default Account' CHECKED state did not flip on AXPress: {before} -> {after}" + assert (before, after) == (0, 1), \ + f"expected Default Account 0 (off) -> 1 (on), observed {before} -> {after}" + + @pytest.mark.rb(depth=2, jump_kind="transition", + expect="Default Account switch 1→0 on the second press") + def test_default_account_switch_turns_back_off(self, ax): + assert wait_for_web(ax), "WebKit content never appeared" + assert rb_reach_add_account_dialog(ax), "Add Account modal did not open" + cb = named(ax, "checkbox", "Default Account") + assert cb is not None, "checkbox 'Default Account' missing from the Add Account modal" + ax.action(cb.id, "AXPress") + time.sleep(0.9) + mid = switch_state(ax, "Default Account") + cb2 = named(ax, "checkbox", "Default Account") + assert cb2 is not None, "'Default Account' vanished after the first press" + ax.action(cb2.id, "AXPress") + time.sleep(0.9) + after = switch_state(ax, "Default Account") + rb_back_escape(1) + assert kit.rb_flip(mid, after), \ + f"'Default Account' did not flip back on the second AXPress: {mid} -> {after}" + assert (mid, after) == (1, 0), \ + f"expected Default Account 1 (on) -> 0 (off), observed {mid} -> {after}" + + @pytest.mark.rb(depth=2, jump_kind="transition", + expect="Is Active switch 1→0 (it starts CHECKED)") + def test_is_active_switch_turns_off(self, ax): + assert wait_for_web(ax), "WebKit content never appeared" + assert rb_reach_add_account_dialog(ax), "Add Account modal did not open" + cb = named(ax, "checkbox", "Is Active") + assert cb is not None, "checkbox 'Is Active' missing from the Add Account modal" + before = int_state(cb.value) + ax.action(cb.id, "AXPress") + time.sleep(0.9) + after = switch_state(ax, "Is Active") + cb2 = named(ax, "checkbox", "Is Active") # restore + if cb2 is not None: + ax.action(cb2.id, "AXPress") + time.sleep(0.6) + rb_back_escape(1) + assert kit.rb_flip(before, after), \ + f"'Is Active' CHECKED state did not flip on AXPress: {before} -> {after}" + assert (before, after) == (1, 0), \ + f"expected Is Active 1 (on by default) -> 0 (off), observed {before} -> {after}" + + @pytest.mark.rb(depth=2, jump_kind="value", + expect="freshly-opened modal: Default Account=0 (off) next to Is Active=1 (on)") + def test_modal_switch_defaults_off_and_on(self, ax): + assert wait_for_web(ax), "WebKit content never appeared" + assert rb_reach_add_account_dialog(ax), "Add Account modal did not open" + observed = (switch_state(ax, "Default Account"), switch_state(ax, "Is Active")) + screenshot_assert( + "states_test_modal_switch_defaults", + "The Add Account modal is open, centred over the Accounts page, titled 'Add Account'. " + "Its two toggle switches are in their DEFAULT positions: 'Default Account' is OFF " + "(grey/unfilled track, knob on the left) and 'Is Active' is ON (filled/dark track, " + "knob on the right) — one off switch and one on switch side by side. Above them the " + "Account Type reads 'Securities' and Currency reads 'United States dollar (USD)'; " + "Cancel and '+ Add Account' buttons sit at the bottom with a ✕ at the top-right.", + RESULTS_DIR, + ) + rb_back_escape(1) + assert kit.rb_value(observed, (0, 1)), ( + "expected the fresh Add Account modal to show Default Account=0 (off) and " + f"Is Active=1 (on), observed (Default Account, Is Active) = {observed}" + ) + + @pytest.mark.rb(depth=2, jump_kind="value", + expect="reopened modal resets to Default Account=0, Is Active=1") + def test_modal_switches_reset_on_reopen(self, ax): + assert wait_for_web(ax), "WebKit content never appeared" + assert rb_reach_add_account_dialog(ax), "Add Account modal did not open" + for nm in ("Default Account", "Is Active"): + cb = named(ax, "checkbox", nm) + assert cb is not None, f"checkbox '{nm}' missing from the Add Account modal" + ax.action(cb.id, "AXPress") + time.sleep(0.7) + flipped = (switch_state(ax, "Default Account"), switch_state(ax, "Is Active")) + assert flipped == (1, 0), f"both switches should be flipped before reopening, got {flipped}" + rb_back_escape(1) # dismiss the modal (no submit!) + assert rb_enter_press(ax, "button", "Add account"), "'Add account' button did not come back" + reopened = (switch_state(ax, "Default Account"), switch_state(ax, "Is Active")) + rb_back_escape(1) + assert kit.rb_value(reopened, (0, 1)), ( + "reopening the Add Account modal must restore the switch defaults " + f"Default Account=0 / Is Active=1, observed {reopened} (was {flipped} before the reset)" + ) + + +# =========================================================================== +# T5 — focus state +# =========================================================================== + +class TestStateFocus: + + @pytest.mark.rb(depth=2, jump_kind="value", + expect="Account Name AXFocused=True and Account Group AXFocused=False on modal open") + def test_modal_autofocuses_account_name(self, ax): + assert wait_for_web(ax), "WebKit content never appeared" + assert rb_reach_add_account_dialog(ax), "Add Account modal did not open" + name_field = named(ax, "text_field", "Account Name") + group_field = named(ax, "text_field", "Account Group") + assert name_field is not None, "text_field 'Account Name' missing from the modal" + assert group_field is not None, "text_field 'Account Group' missing from the modal" + observed = (is_focused(ax, name_field), is_focused(ax, group_field)) + actually_focused = focused_titles(ax) if observed != (True, False) else [] + rb_back_escape(1) + assert kit.rb_value(observed, (True, False)), ( + "the modal must autofocus its FIRST field: expected Account Name AXFocused=True and " + f"Account Group AXFocused=False, observed (Account Name, Account Group) = {observed}" + + (f"; elements actually reporting AXFocused=True: {actually_focused}" + if actually_focused else "") + ) + + @pytest.mark.rb(depth=2, jump_kind="value", + expect="currency popover search combobox (empty name) opens with AXFocused=True") + def test_currency_popover_search_field_focused(self, ax): + assert wait_for_web(ax), "WebKit content never appeared" + assert rb_enter_settings(ax), "sidebar 'Settings' link missing" + assert rb_enter_currency_popover(ax), "combobox 'Currency' missing on Settings ▸ General" + search = currency_search_field(ax) + assert search is not None, "the currency popover's search combobox (empty AXTitle) never appeared" + observed = is_focused(ax, search) + actually_focused = focused_titles(ax) if observed is not True else [] + rb_back_escape(1) + assert kit.rb_value(observed, True), ( + "opening the currency popover must focus its search field: expected AXFocused=True, " + f"observed {observed}" + + (f"; elements actually reporting AXFocused=True: {actually_focused}" + if actually_focused else "") + ) + + +# =========================================================================== +# T6 / T7 — mode + selection state reflected on the trigger +# =========================================================================== + +class TestStateModes: + + @pytest.mark.rb(depth=3, jump_kind="transition", + expect="combobox 'Account Type' value flips Securities → Cash") + def test_account_type_mode_flips_securities_to_cash(self, ax): + assert wait_for_web(ax), "WebKit content never appeared" + assert rb_reach_add_account_dialog(ax), "Add Account modal did not open" + combo = named(ax, "combobox", "Account Type") + assert combo is not None, "combobox 'Account Type' missing from the modal" + before = (combo.value or "").strip() # observed with a trailing \n + # open_account_type() CG-clicks the child label carrying the current selection — + # check it exists first so a missing trigger fails with a readable message. + assert any(e.role == "label" and (e.value or "").strip() in ("Securities", "Cash", "Crypto") + and "AXPress" in e.actions for e in web_els(ax)), ( + "the Account Type combobox exposes no pressable child label holding the current " + "selection — cannot open the option list" + ) + options = open_account_type(ax) + assert any("Cash" in (o or "") for o in options), \ + f"the Account Type option list did not open with Securities/Cash/Crypto, saw {options[:6]}" + select_next_account_type(ax) + combo2 = named(ax, "combobox", "Account Type") + after = (combo2.value or "").strip() if combo2 is not None else None + rb_back_escape(1) + assert kit.rb_flip(before, after), \ + f"'Account Type' mode did not change after Down+Return: {before!r} -> {after!r}" + assert kit.rb_value(before, "Securities"), f"expected the default mode 'Securities', got {before!r}" + assert kit.rb_value(after, "Cash"), f"expected the next mode 'Cash', got {after!r}" + + @pytest.mark.rb(depth=2, jump_kind="transition", + expect="Currency combobox value changes away from 'United States dollar (USD)' " + "after picking 'European Euro (EUR)'") + def test_currency_selection_changes_trigger_value(self, ax): + assert wait_for_web(ax), "WebKit content never appeared" + assert rb_enter_settings(ax), "sidebar 'Settings' link missing" + combo = named(ax, "combobox", "Currency") + assert combo is not None, "combobox 'Currency' missing on Settings ▸ General" + before = (combo.value or "").strip() + assert rb_enter_currency_popover(ax), "the currency popover did not open" + pick_currency(ax, "European Euro (EUR)") # AXPress the row, then Escape + combo2 = named(ax, "combobox", "Currency") + after = (combo2.value or "").strip() if combo2 is not None else None + assert kit.rb_flip(before, after), ( + "picking a currency must be reflected on the combobox trigger: " + f"{before!r} -> {after!r} (unchanged)" + ) + assert kit.rb_value(before, "United States dollar (USD)"), \ + f"expected the initial trigger value 'United States dollar (USD)', got {before!r}" + assert after and "Euro" in after, f"expected a Euro selection on the trigger, got {after!r}" + + +# =========================================================================== +# T8 — ENABLED sweeps / state consistency +# =========================================================================== + +class TestStateEnabledSweep: + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="home surface: 4 sidebar links + 'Expand Sidebar' button all AXEnabled=True") + def test_home_sidebar_widgets_enabled(self, ax): + assert wait_for_web(ax), "WebKit content never appeared" + wanted = [("link", "Dashboard"), ("link", "Holdings"), ("link", "Activities"), + ("link", "Settings"), ("button", "Expand Sidebar")] + observed = state_sweep(ax, wanted) + expected = [(r, n, True) for r, n in wanted] + assert kit.rb_value(observed, expected), ( + "every sidebar widget on the home surface must report AXEnabled=True " + f"(None = widget not found): {observed}" + ) + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="Settings▸General: 4 sub-nav links + Currency combobox + Save button all AXEnabled=True") + def test_settings_general_widgets_enabled(self, ax): + assert wait_for_web(ax), "WebKit content never appeared" + assert rb_enter_settings(ax), "sidebar 'Settings' link missing" + wanted = [("link", "General"), ("link", "Accounts"), ("link", "Goals"), + ("link", "Appearance"), ("combobox", "Currency"), ("button", "Save")] + observed = state_sweep(ax, wanted) # READ ONLY — 'Save' is never pressed + expected = [(r, n, True) for r, n in wanted] + assert kit.rb_value(observed, expected), ( + "every Settings ▸ General widget must report AXEnabled=True " + f"(None = widget not found): {observed}" + ) + + @pytest.mark.rb(depth=2, jump_kind="value", + expect="Add Account modal: 2 text fields, 2 comboboxes, 2 switches, Cancel, " + "Add Account and Close all AXEnabled=True") + def test_add_account_modal_widgets_enabled(self, ax): + assert wait_for_web(ax), "WebKit content never appeared" + assert rb_reach_add_account_dialog(ax), "Add Account modal did not open" + wanted = [("text_field", "Account Name"), ("text_field", "Account Group"), + ("combobox", "Account Type"), ("combobox", "Currency"), + ("checkbox", "Default Account"), ("checkbox", "Is Active"), + ("popup", "Cancel"), ("button", "Add Account"), ("button", "Close")] + observed = state_sweep(ax, wanted) # READ ONLY — the submit is never pressed + expected = [(r, n, True) for r, n in wanted] + rb_back_escape(1) + assert kit.rb_value(observed, expected), ( + "every widget in the Add Account modal must report AXEnabled=True " + f"(None = widget not found): {observed}" + ) + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="0 interactive web widgets are SHOWING-but-not-ENABLED on the home surface") + def test_no_showing_but_disabled_widgets_on_home(self, ax): + assert wait_for_web(ax), "WebKit content never appeared" + interactive = [e for e in web_els(ax) if e.role in INTERACTIVE_ROLES] + assert len(interactive) >= 5, \ + f"expected the home surface to expose >=5 interactive widgets, found {len(interactive)}" + disabled = sorted({f"{e.role}|{e.name or ''}" for e in interactive if not bool(e.enabled)}) + assert kit.rb_value(disabled, []), ( + "a widget present in the live AX tree (SHOWING) must not be disabled — nothing is " + f"disabled in this app state, but found: {disabled}" + ) + + @pytest.mark.rb(depth=2, jump_kind="value", + expect="modal state flags: switches ENABLED+VISIBLE+SHOWING with AXPress, " + "text fields FOCUSABLE, 0 disabled widgets") + def test_modal_widget_state_flags_recorded(self, ax): + assert wait_for_web(ax), "WebKit content never appeared" + assert rb_reach_add_account_dialog(ax), "Add Account modal did not open" + flags = {} + for role, nm in (("checkbox", "Default Account"), ("checkbox", "Is Active"), + ("text_field", "Account Name"), ("text_field", "Account Group")): + el = named(ax, role, nm) + assert el is not None, f"{role} '{nm}' missing from the Add Account modal" + flags[nm] = widget_states(ax, el) + disabled_count = sum(1 for e in web_els(ax) + if e.role in INTERACTIVE_ROLES and not bool(e.enabled)) + rb_back_escape(1) + toggles_ok = all( + flags[nm]["ENABLED"] and flags[nm]["VISIBLE"] and flags[nm]["SHOWING"] + and "AXPress" in flags[nm]["ACTIONS"] + for nm in ("Default Account", "Is Active") + ) + fields_focusable = all(flags[nm]["FOCUSABLE"] + for nm in ("Account Name", "Account Group")) + observed = (toggles_ok, fields_focusable, disabled_count) + assert kit.rb_value(observed, (True, True, 0)), ( + "expected both toggle switches ENABLED+VISIBLE+SHOWING and armable via AXPress, both " + "text fields FOCUSABLE, and 0 disabled interactive widgets in the modal; observed " + f"(toggles_ok, fields_focusable, disabled_count) = {observed} — per-widget flags: {flags}" + ) + + +# =========================================================================== +# T9 / T10 — menu-item enabled state + menu open/close state +# =========================================================================== + +class TestStateMenus: + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="every NAMED item of the Wealthfolio/File/Edit/View/Window/Help menus " + "reports AXEnabled=True") + def test_named_menu_items_enabled(self, ax): + assert wait_for_web(ax), "WebKit content never appeared" + bar = menu_bar_items(ax) + disabled, total = [], 0 + for menu in APP_MENUS: + mbi = bar.get(menu) + assert mbi is not None, \ + f"menu_bar_item '{menu}' missing from the menu bar (found: {sorted(bar)})" + for item in top_menu_items(ax, mbi): + nm = item.name or "" + if not nm: + continue + total += 1 + if not bool(item.enabled): + disabled.append(f"{menu} > {nm}") + assert total >= 15, f"expected >=15 named menu items across the 6 app menus, found {total}" + assert kit.rb_value(sorted(disabled), []), ( + f"every named menu item must be accessible (AXEnabled=True); {len(disabled)} of " + f"{total} report disabled: {disabled}" + ) + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="separator menu items (name=='') report AXEnabled=False") + def test_separator_menu_items_disabled(self, ax): + assert wait_for_web(ax), "WebKit content never appeared" + bar = menu_bar_items(ax) + separators, wrongly_enabled = 0, [] + for menu in ("Wealthfolio", "Edit", "Window"): + mbi = bar.get(menu) + assert mbi is not None, \ + f"menu_bar_item '{menu}' missing from the menu bar (found: {sorted(bar)})" + for item in top_menu_items(ax, mbi): + if (item.name or ""): + continue + separators += 1 + if bool(item.enabled): + wrongly_enabled.append(menu) + assert separators >= 4, ( + "expected the Wealthfolio/Edit/Window menus to contain >=4 separator items " + f"(unnamed menu_items), found {separators}" + ) + assert kit.rb_value(sorted(wrongly_enabled), []), ( + f"separator items must report AXEnabled=False; enabled separators in: {wrongly_enabled}" + ) + + @pytest.mark.rb(depth=0, jump_kind="transition", + expect="Help menu-bar item AXSelected False→True on AXPress, back to False after AXCancel") + def test_help_menu_open_close_selected_state(self, ax): + assert wait_for_web(ax), "WebKit content never appeared" + pre = find_menu_bar_item(ax, "Help") + assert pre is not None, "menu_bar_item 'Help' missing from the menu bar" + before = bool(ax_attr(ax, pre, "AXSelected")) + mbi = open_app_menu(ax, "Help") + assert mbi is not None, "could not AXPress the 'Help' menu-bar item" + during = bool(ax_attr(ax, mbi, "AXSelected")) + screenshot_assert( + "states_test_help_menu_open", + "The 'Help' menu in the macOS menu bar is OPEN: its title is highlighted (selected) " + "and a small dropdown is shown below it containing the system search row and a " + "'Report Issue' item. The Wealthfolio window with the 'Welcome to Wealthfolio' " + "onboarding page is still visible behind the menu.", + RESULTS_DIR, + ) + ax.action(mbi.id, "AXCancel") # never activate an item — just close + time.sleep(0.6) + post = find_menu_bar_item(ax, "Help") + after = bool(ax_attr(ax, post, "AXSelected")) if post is not None else None + helpers.dismiss_menus(ax) + assert kit.rb_flip(before, during), \ + f"'Help' AXSelected did not flip when the menu opened: {before} -> {during}" + assert (before, during, after) == (False, True, False), ( + "expected Help AXSelected False (closed) -> True (open) -> False (after AXCancel), " + f"observed {(before, during, after)}" + ) + + @pytest.mark.rb(depth=0, jump_kind="transition", + expect="Edit menu-bar item AXSelected False→True on AXPress, back to False after AXCancel") + def test_edit_menu_open_close_selected_state(self, ax): + assert wait_for_web(ax), "WebKit content never appeared" + pre = find_menu_bar_item(ax, "Edit") + assert pre is not None, "menu_bar_item 'Edit' missing from the menu bar" + before = bool(ax_attr(ax, pre, "AXSelected")) + mbi = open_app_menu(ax, "Edit") + assert mbi is not None, "could not AXPress the 'Edit' menu-bar item" + during = bool(ax_attr(ax, mbi, "AXSelected")) + item_names = [i.name for i in menu_items(ax, mbi) if i.name] + ax.action(mbi.id, "AXCancel") + time.sleep(0.6) + post = find_menu_bar_item(ax, "Edit") + after = bool(ax_attr(ax, post, "AXSelected")) if post is not None else None + helpers.dismiss_menus(ax) + assert kit.rb_flip(before, during), \ + f"'Edit' AXSelected did not flip when the menu opened: {before} -> {during}" + assert (before, during, after) == (False, True, False), ( + "expected Edit AXSelected False (closed) -> True (open) -> False (after AXCancel), " + f"observed {(before, during, after)}" + ) + assert "Copy" in item_names, f"the open Edit menu should expose 'Copy', saw {item_names}" + + +# =========================================================================== +# T11 / T12 — window state + geometry state +# =========================================================================== + +class TestStateWindow: + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="main window: AXMain=True, AXMinimized/AXFullScreen/AXModal=False, " + "AXSubrole=AXStandardWindow") + def test_main_window_state_attributes(self, ax): + assert wait_for_web(ax), "WebKit content never appeared" + win = ensure_window_visible(ax) + assert win is not None, ( + "no reachable main window (looked for a window titled 'Wealthfolio', then any " + "AXMain window, after running every reveal path)" + ) + got = ax.get(win.id, ["AXMain", "AXMinimized", "AXFullScreen", "AXModal", "AXSubrole"]) + observed = (bool(got.get("AXMain")), bool(got.get("AXMinimized")), + bool(got.get("AXFullScreen")), bool(got.get("AXModal")), + got.get("AXSubrole")) + assert kit.rb_value(observed, (True, False, False, False, "AXStandardWindow")), ( + "the frame must be ACTIVE and a plain standard window: expected " + "(AXMain, AXMinimized, AXFullScreen, AXModal, AXSubrole) = " + f"(True, False, False, False, 'AXStandardWindow'), observed {observed}" + ) + + @pytest.mark.rb(depth=0, jump_kind="transition", + expect="nav link 'Dashboard' AXSize width 52 (collapsed) → 172 (expanded)") + def test_sidebar_expand_changes_nav_link_width(self, ax): + assert wait_for_web(ax), "WebKit content never appeared" + dash = named(ax, "link", "Dashboard") + assert dash is not None, "sidebar link 'Dashboard' missing" + before_w = size_width(ax, dash) + toggle = named(ax, "button", "Expand Sidebar") + assert toggle is not None, "button 'Expand Sidebar' missing from the sidebar" + ax.action(toggle.id, "AXPress") + time.sleep(1.0) + after_w = size_width(ax, named(ax, "link", "Dashboard")) + screenshot_assert( + "states_test_sidebar_expanded", + "The left sidebar is EXPANDED: it has widened from icon-only to show the text labels " + "Dashboard / Holdings / Activities / Settings beside their icons, plus the " + "'Wealthfolio' brand name next to the logo at the top; the toggle button now reads " + "'Collapse Sidebar'. The 'Welcome to Wealthfolio' onboarding page with its coin " + "illustration and three numbered steps is still shown to the right.", + RESULTS_DIR, + ) + collapse = named(ax, "button", "Collapse Sidebar") # restore the collapsed state + if collapse is not None: + ax.action(collapse.id, "AXPress") + time.sleep(1.0) + assert kit.rb_flip(before_w, after_w), \ + f"'Dashboard' nav-link width did not change when the sidebar expanded: {before_w} -> {after_w}" + assert (before_w, after_w) == (52, 172), \ + f"expected the nav-link width 52 (collapsed) -> 172 (expanded), observed {before_w} -> {after_w}" + + +# =========================================================================== +# State visibility after dismissal (the modal removes the page from the AX tree) +# =========================================================================== + +class TestStateVisibilityFlip: + + @pytest.mark.rb(depth=2, jump_kind="transition", + expect="sidebar links absent from the AX tree while the Add Account modal is " + "open, and all 4 back (>=8 links total) after Escape") + def test_sidebar_links_hidden_while_modal_open(self, ax): + assert wait_for_web(ax), "WebKit content never appeared" + assert rb_reach_add_account_dialog(ax), "Add Account modal did not open" + in_modal = [e.name or "" for e in by_role(ax, "link")] + hidden = SIDEBAR_LINKS & set(in_modal) + rb_back_escape(1) + restored_links = [e.name or "" for e in by_role(ax, "link")] + back = SIDEBAR_LINKS & set(restored_links) + assert kit.rb_flip(sorted(hidden), sorted(back)), ( + "the modal must hide the rest of the page: sidebar links visible while open=" + f"{sorted(hidden)}, after Escape={sorted(back)}" + ) + assert not hidden, f"the open modal still exposes sidebar links: {sorted(hidden)}" + assert not in_modal, f"expected 0 links while the modal is open, found {len(in_modal)}: {in_modal}" + assert back == SIDEBAR_LINKS, ( + "all 4 sidebar links must be back in the AX tree after dismissing the modal, " + f"got {sorted(back)} (total links restored: {len(restored_links)})" + ) + assert len(restored_links) >= 8, ( + "dismissing the modal must restore the whole page (4 sidebar links + the 4 settings " + f"sub-nav links at minimum), only {len(restored_links)} links came back: {restored_links}" + ) diff --git a/macos/wealthfolio-wealthfolio/tests/test_ax_structure.py b/macos/wealthfolio-wealthfolio/tests/test_ax_structure.py new file mode 100644 index 0000000000000000000000000000000000000000..7e2c446afc6d781193f8e58436942aa228a73a67 --- /dev/null +++ b/macos/wealthfolio-wealthfolio/tests/test_ax_structure.py @@ -0,0 +1,845 @@ +#!/usr/bin/env python3 +"""AX STRUCTURE tests for Wealthfolio (Tauri v1 + WebKit, bundle com.teymz.wealthfolio). + +Single source of truth: verifier/recon.md sections APP / RECIPES / AX_TREE / STRUCTURE / +VISUAL / DO-NOT-TOUCH. This lane owns SHAPE only: + + * gate S1..S8 -> window identity + chrome, the single webarea, the sidebar group and + its 4 nav links, the sidebar toggle, the home-surface composition, + the 6 app menus, the Settings sub-nav (depth 1). Folded into 6 tests + (S2 rides on S1's window, S5 on S4's sidebar) to keep the existence + share at 30% of the suite. + * delta D1..D14 -> widget-count / role-census / snapshot-magnitude deltas, each proved + with kit.rb_showing() (or a live re-read) before and after a trigger + and verdicted with kit.rb_reach / kit.rb_flip. + +NOT this lane: menu item-name sweeps, checkbox flips, currency-filter values, exact +page-text sets (owned by the menus / states / computation / text lanes). + +DO-NOT-TOUCH honoured: `button 'Save'`, the modal's `button 'Add Account'`, the window +chrome buttons and every Quit/Close/Minimize/Zoom/Full-Screen/Hide/Services menu item are +read for EXISTENCE only and never activated. Every surface a test opens is restored +(Escape for popovers/modals, the sidebar is toggled back, the alert is dismissed with OK). +""" + +import json +import os +import re +import subprocess +import time + +import pytest + +import rb_testgen_kit as kit +import verifier_helpers as helpers + +RESULTS_DIR = os.environ.get("RESULTS_DIR", "/tmp/verifier_results") + + +# ────────────────────────────────────────────────────────────────────────────── +# screenshot assertion helper (verbatim from the agent contract) +# ────────────────────────────────────────────────────────────────────────────── +def screenshot_assert(test_name, description, results_dir): + 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): + with open(assertions_file) as f: + assertions = json.load(f) + assertions[f"{test_name}.png"] = description + with open(assertions_file, "w") as f: + json.dump(assertions, f, indent=2) + + +# ══════════════════════════════════════════════════════════════════════════════ +# RECIPES — copied VERBATIM from recon.md ## RECIPES (verified primitives) +# ══════════════════════════════════════════════════════════════════════════════ + +# ---------- reads ---------- +def wait_for_web(ax, timeout=20.0): + """REQUIRED first line of every test: poll until the WebKit content is in the AX tree.""" + deadline = time.time() + timeout + while time.time() < deadline: + for e in web_els(ax): + if e.role == "link" and e.name == "Settings": + return True + time.sleep(0.4) + return False + + +def web_els(ax): + """All elements inside the app's web area (excludes the menu bar).""" + wa = ax.find(role="webarea", max_results=2) + if not wa: + return [] + return ax.find(max_results=1500, root_id=wa[0].id, max_depth=25) + + +def by_role(ax, role): + return [e for e in web_els(ax) if e.role == role] + + +def named(ax, role, name): + for e in web_els(ax): + if e.role == role and (e.name or "") == name: + return e + return None + + +def texts(ax): + """Every visible text string in the web area (label .value or .name).""" + return [(e.value or e.name) for e in web_els(ax) if e.role == "label" and (e.value or e.name)] + + +def headings(ax): + return [(e.name, e.value) for e in web_els(ax) if e.role == "heading"] # value == heading level + + +# ---------- navigation (named rb_enter_* / rb_reach_* so the depth audit sees them) ---------- +def rb_enter_press(ax, role, name, wait=1.6): + """AXPress a named link/button and settle. Returns True if the element existed.""" + el = named(ax, role, name) + if el is None: + return False + ax.action(el.id, "AXPress") + time.sleep(wait) + return True + + +def rb_reach_home(ax): + """Go to the Welcome/onboarding surface: pressing sidebar 'Dashboard' redirects there.""" + helpers.send_key(helpers.KC_ESCAPE); time.sleep(0.4) + rb_enter_press(ax, "link", "Dashboard") + + +def rb_enter_settings(ax): + """Sidebar 'Settings' link -> Settings ▸ General surface (depth 1).""" + return rb_enter_press(ax, "link", "Settings") + + +def rb_enter_settings_tab(ax, tab): + """Settings sub-nav link: 'General' | 'Accounts' | 'Goals' | 'Appearance' (depth 1).""" + return rb_enter_press(ax, "link", tab) + + +def rb_reach_accounts(ax): + """Settings ▸ Accounts (depth 1): sidebar Settings, then the 'Accounts' sub-nav link.""" + rb_enter_settings(ax) + return rb_enter_settings_tab(ax, "Accounts") + + +def rb_reach_add_account_dialog(ax): + """Settings ▸ Accounts ▸ 'Add account' -> the Add Account modal (depth 2).""" + rb_reach_accounts(ax) + return rb_enter_press(ax, "button", "Add account") + + +def rb_enter_currency_popover(ax): + """AXPress the 'Currency' combobox -> the currency search popover. + depth 2 from home (via Settings▸General) / depth 3 from inside the Add Account dialog.""" + return rb_enter_press(ax, "combobox", "Currency", wait=1.5) + + +def rb_back_escape(n=1): + """Escape closes (in order) popover -> dialog -> menu. VERIFIED reliable.""" + for _ in range(n): + helpers.send_key(helpers.KC_ESCAPE) + time.sleep(0.6) + + +# ---------- Radix Select ('Account Type') ---------- +def open_account_type(ax): + """AXPress does NOT open a Radix Select, and the combobox's own AX frame is bogus. + CG-click its CHILD label (the one whose VALUE is the current selection) — verified.""" + cur = None + for e in web_els(ax): + if e.role == "label" and (e.value or "").strip() in ("Securities", "Cash", "Crypto") \ + and "AXPress" in e.actions: + cur = e + break + ax.click_element_cg(cur.id) + time.sleep(1.2) + return [e.name for e in web_els(ax) if e.role == "label" and e.name] # ['Securities','Cash','Crypto'] + + +# ---------- menu bar ---------- +def open_app_menu(ax, menu_name): + """AXPress the AXMenuBarItem. While open its AXSelected flips True (verified).""" + mbi = [e for e in ax.find(role="menu_bar_item", max_results=12) if e.name == menu_name] + if not mbi: + return None + ax.action(mbi[0].id, "AXPress") + time.sleep(0.8) + return mbi[0] + + +def menu_items(ax, mbi): + return ax.find(role="menu_item", root_id=mbi.id, max_results=60) + + +def pick_menu_item(ax, menu_name, item_name): + mbi = open_app_menu(ax, menu_name) + for it in menu_items(ax, mbi): + if it.name == item_name: + ax.action(it.id, "AXPress") + time.sleep(1.6) + return True + ax.action(mbi.id, "AXCancel") + return False + + +def ax_attr(ax, el, attr): + """Read a raw AX attribute (AXHelp / AXSelected / AXPlaceholderValue / AXMenuItemCmdChar / …).""" + import ApplicationServices as AS + err, v = AS.AXUIElementCopyAttributeValue(ax._get_ref(el.id), attr, None) + return v if err == 0 else None + + +# ══════════════════════════════════════════════════════════════════════════════ +# STRUCTURE-lane additions (nav wrappers named rb_enter_* so the depth audit sees +# them, plus tiny pure-read utilities). No new interaction primitives. +# ══════════════════════════════════════════════════════════════════════════════ +def rb_enter_report_issue_alert(ax): + """Help ▸ Report Issue -> the native `window 'alert'` (depth 1). + Recon M1: the alert is a SEPARATE window that does NOT hide the main content.""" + return pick_menu_item(ax, "Help", "Report Issue") + + +def rb_enter_step_link(ax, keyword, wait=1.6): + """AXPress the home surface's numbered step link whose visible name contains `keyword` + (semantic, framework-agnostic locator) -> the surface it routes to (depth 1).""" + kw = keyword.lower() + for e in web_els(ax): + if e.role == "link" and kw in (e.name or "").lower(): + ax.action(e.id, "AXPress") + time.sleep(wait) + return True + return False + + +def _ensure_window(ax): + """Recon APP: `REVEAL_STEPS: none needed` — a normal windowed app. So reveal only + DEFENSIVELY: ax_helpers.ensure_ui_visible() AXPresses every menu-bar item and would + leave a menu hanging open, which would corrupt the very tree we measure.""" + if ax.find(role="window", max_results=1, max_depth=2): + return True + try: + ax.ensure_ui_visible() + time.sleep(1.0) + except Exception: + pass + return bool(ax.find(role="window", max_results=1, max_depth=2)) + + +def _top_windows(ax): + """Top-level `window` elements (direct children of the application element).""" + return ax.find(role="window", max_results=10, max_depth=1) + + +def _main_window(ax): + """The app's main window, located by visible title then by AXMain (never by index).""" + wins = _top_windows(ax) + for w in wins: + if "wealthfolio" in (w.name or "").strip().lower(): + return w + for w in wins: + if ax.get(w.id, ["AXMain"]).get("AXMain"): + return w + return wins[0] if wins else None + + +def _size(ax, element_id): + """(w, h) out of AXSize — the stringified AXValue carries `w:… h:…`; a dict is tolerated.""" + 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) + s = str(raw or "") + m = re.search(r"w:\s*([-\d.]+)\s+h:\s*([-\d.]+)", s) + if m: + return float(m.group(1)), float(m.group(2)) + nums = re.findall(r"[-\d.]+", s) + if len(nums) >= 2: + return float(nums[-2]), float(nums[-1]) + return 0.0, 0.0 + + +def _level(el): + """Heading level lives in AXValue (may be int, '1' or '1\\n').""" + try: + return int(float(str(el.value).strip())) + except Exception: + return None + + +def _count(els, role): + return len([e for e in els if e.role == role]) + + +def _find_in(els, role, name): + """Locate by role + exact visible name inside an already-enumerated snapshot.""" + for e in els: + if e.role == role and (e.name or "").strip() == name: + return e + return None + + +def _has_text(els, needle): + """Visible-text keyword match over a snapshot (label value or any element name).""" + n = needle.lower() + for e in els: + if n in (e.value or "").lower() or n in (e.name or "").lower(): + return True + return False + + +def _role_set(ax): + """The set of distinct roles currently exposed inside the web area.""" + return {e.role for e in web_els(ax)} + + +def _role_census(ax): + """Per-role counts inside the web area (the surface's shape fingerprint).""" + census = {} + for e in web_els(ax): + census[e.role] = census.get(e.role, 0) + 1 + return census + + +def _max_tree_depth(ax, max_depth=14): + """Deepest nesting level in the app's AX tree (a structural-complexity measure). + Uses one AXHelper.tree() call — the same mechanism kit.rb_showing() uses.""" + try: + tree = ax.tree(max_depth=max_depth) + except Exception: + return 0 + + def _d(node, lvl): + kids = (node or {}).get("children") or [] + if not kids: + return lvl + return max(_d(k, lvl + 1) for k in kids) + + return _d(tree, 0) + + +def _sidebar_state(ax): + """OBSERVED sidebar shape: (toggle-button name, nav-link width) — read live both + before and after the toggle so kit.rb_flip verdicts a real change.""" + els = web_els(ax) + btn = (_find_in(els, "button", "Expand Sidebar") + or _find_in(els, "button", "Collapse Sidebar")) + dash = _find_in(els, "link", "Dashboard") + width = round(_size(ax, dash.id)[0]) if dash is not None else 0 + return ((btn.name or "").strip() if btn is not None else "", width) + + +# ══════════════════════════════════════════════════════════════════════════════ +# GATE — top-level surfaces that MUST exist (recon ## STRUCTURE S1..S8). +# Kept to 6 tests = 30% of the suite (rb_audit's existence_max), by folding +# S2 into S1 (same window's chrome) and S5 into S4 (same sidebar container). +# ══════════════════════════════════════════════════════════════════════════════ +class TestStructureGate: + + @pytest.mark.rb(depth=0, jump_kind="none") + def test_gate_window_identity_and_chrome(self, ax): + """S1 + S2: one standard main window titled Wealthfolio, >= 1000x600 (ref 1366x960), + exposing the three chrome buttons by SUBROLE. + Chrome is EXISTENCE ONLY — pressing it is forbidden (recon ## DO-NOT-TOUCH 3).""" + assert wait_for_web(ax) + assert _ensure_window(ax), "no reachable top-level window" + win = _main_window(ax) + assert win is not None + assert "wealthfolio" in (win.name or "").strip().lower() + attrs = ax.get(win.id, ["AXSubrole", "AXMain"]) + assert str(attrs.get("AXSubrole") or "") == "AXStandardWindow" + assert bool(attrs.get("AXMain")) is True + w, h = _size(ax, win.id) + assert w >= 1000, f"window width {w} < 1000" + assert h >= 600, f"window height {h} < 600" + subroles = set() + for b in ax.find(role="button", root_id=win.id, max_results=30, max_depth=3): + s = ax.get(b.id, ["AXSubrole"]).get("AXSubrole") + if s: + subroles.add(str(s)) + assert "AXCloseButton" in subroles, subroles + assert "AXMinimizeButton" in subroles, subroles + # green button: AXFullScreenButton on the reference; a native-AppKit recreation may + # expose the semantically equivalent AXZoomButton. + assert ("AXFullScreenButton" in subroles or "AXZoomButton" in subroles), subroles + screenshot_assert( + "structure_test_window_identity", + "A single standard macOS window titled 'Wealthfolio' (~1366x960) with the three " + "traffic-light buttons (close/minimize/full-screen) at its top-left: a narrow dark " + "icon-only sidebar down the left edge, and the onboarding page filling the rest with " + "a circular coin/pie illustration and the heading 'Welcome to Wealthfolio'.", + RESULTS_DIR) + + @pytest.mark.rb(depth=0, jump_kind="none") + def test_gate_single_webarea(self, ax): + """S3: exactly one webarea named Wealthfolio, hosted under the main window.""" + assert wait_for_web(ax) + assert _ensure_window(ax), "no reachable top-level window" + win = _main_window(ax) + assert win is not None + inner = ax.find(role="webarea", root_id=win.id, max_results=5) + assert len(inner) == 1, f"expected exactly 1 webarea under the window, got {len(inner)}" + assert "wealthfolio" in (inner[0].name or "").strip().lower() + # all app content lives in there + assert len(web_els(ax)) >= 20 + + @pytest.mark.rb(depth=0, jump_kind="none") + def test_gate_sidebar_group_nav_links_and_toggle(self, ax): + """S4 + S5: group 'Sidebar' holds exactly the 4 nav links (each AXHelp == its title) + plus the toggle button 'Expand Sidebar' with AXHelp='Toggle Sidebar'.""" + assert wait_for_web(ax) + side = named(ax, "group", "Sidebar") + assert side is not None, "no group named 'Sidebar'" + links = ax.find(role="link", root_id=side.id, max_results=20) + nav = {} + for l in links: + nm = (l.name or "").strip() + if nm: + nav[nm] = l + assert set(nav) == {"Dashboard", "Holdings", "Activities", "Settings"}, sorted(nav) + assert len(nav) == 4 + for nm, el in nav.items(): + assert str(ax_attr(ax, el, "AXHelp") or "").strip() == nm, nm + btns = [b for b in web_els(ax) if b.role == "button"] + toggle = next((b for b in btns if (b.name or "").strip() == "Expand Sidebar"), None) + if toggle is None: # a recreation may label it differently — fall back to AXHelp + toggle = next( + (b for b in btns + if "sidebar" in str(ax_attr(ax, b, "AXHelp") or "").lower() + or "sidebar" in (b.name or "").lower()), None) + assert toggle is not None, [(b.name or "") for b in btns] + assert "sidebar" in str(ax_attr(ax, toggle, "AXHelp") or "").lower() + assert toggle.enabled is True + assert "AXPress" in toggle.actions + + @pytest.mark.rb(depth=0, jump_kind="none") + def test_gate_home_surface_composition(self, ax): + """S6: heading 'Welcome to Wealthfolio' (level 1), image 'Illustration', the 3 + numbered step links and link "Let's get started".""" + assert wait_for_web(ax) + els = web_els(ax) + h = _find_in(els, "heading", "Welcome to Wealthfolio") + assert h is not None, "no heading 'Welcome to Wealthfolio'" + assert _level(h) == 1, f"heading level {h.value!r} != 1" + assert _find_in(els, "heading", "Settings") is None, "already on the Settings surface" + assert _find_in(els, "image", "Illustration") is not None + link_names = [(e.name or "").lower() for e in els if e.role == "link"] + for kw in ("set your main currency", "add your accounts", "add or import activities"): + assert any(kw in n for n in link_names), kw + assert any("get started" in n for n in link_names) + assert _count(els, "link") >= 8, _count(els, "link") + screenshot_assert( + "structure_test_home_surface", + "Onboarding/home surface: narrow dark icon-only sidebar on the left; a circular " + "coin/pie illustration; the bold heading 'Welcome to Wealthfolio' with the subtitle " + "about a personal financial portfolio tracker; three numbered steps 1/2/3 (set your " + "main currency, add your accounts, add or import activities) each with an arrow; and " + "a dark \"Let's get started\" button at the bottom.", + RESULTS_DIR) + + @pytest.mark.rb(depth=0, jump_kind="none") + def test_gate_menu_bar_six_app_menus(self, ax): + """S7: a menu bar exposing exactly the 6 app menus (plus the Apple menu).""" + assert wait_for_web(ax) + assert ax.find(role="menu_bar", max_results=2), "no menu_bar" + names = [(m.name or "").strip() for m in ax.find(role="menu_bar_item", max_results=15)] + app_menus = [n for n in names if n and n.lower() != "apple"] + for want in ("Wealthfolio", "File", "Edit", "View", "Window", "Help"): + assert want in app_menus, f"missing menu {want!r} in {app_menus}" + assert len(app_menus) == 6, app_menus + + @pytest.mark.rb(depth=1, jump_kind="none") + def test_gate_settings_subnav_links(self, ax): + """S8: the Settings surface exposes exactly the 4 sub-nav links + heading 'Settings' L2.""" + assert wait_for_web(ax) + assert rb_enter_settings(ax), "sidebar link 'Settings' not found" + els = web_els(ax) + subnav = [e for e in els if e.role == "link" + and (e.name or "").strip() in ("General", "Accounts", "Goals", "Appearance")] + assert len(subnav) == 4, [(e.name or "") for e in subnav] + assert {(e.name or "").strip() for e in subnav} == {"General", "Accounts", "Goals", "Appearance"} + head = [e for e in els if e.role == "heading" and (e.name or "").strip() == "Settings"] + assert len(head) == 1, "no single heading 'Settings'" + assert _level(head[0]) == 2, f"heading level {head[0].value!r} != 2" + + +# ══════════════════════════════════════════════════════════════════════════════ +# SHAPE DELTAS — trigger -> widget-count / role-census / snapshot-magnitude +# before vs after (recon ## STRUCTURE D1..D8 plus six further verified jumps) +# ══════════════════════════════════════════════════════════════════════════════ +class TestStructureDeltas: + + @pytest.mark.rb(depth=2, jump_kind="reach", + expect="Settings▸General -> Currency popover: web elements ~40 -> ~163 with " + ">=150 label rows, label 'Search currency...' appears and button 'Save' " + "disappears; Escape restores the page") + def test_currency_popover_expands_tree(self, ax): + """D1 (depth 2).""" + assert wait_for_web(ax) + assert rb_enter_settings(ax), "sidebar link 'Settings' not found" + assert named(ax, "combobox", "Currency") is not None + before_n = len(web_els(ax)) + assert 20 <= before_n <= 80, before_n + before = kit.rb_showing(ax) + try: + assert rb_enter_currency_popover(ax), "combobox 'Currency' not found" + after = kit.rb_showing(ax) + els = web_els(ax) + assert len(els) >= before_n + 100, f"{before_n} -> {len(els)}" + assert _count(els, "label") >= 150, _count(els, "label") + assert _has_text(els, "Search currency"), "popover search box label missing" + assert _find_in(els, "button", "Save") is None, "button 'Save' still in the tree" + screenshot_assert( + "structure_test_currency_popover", + "The Settings▸General page is covered by a dropdown panel: a 'Search currency...' " + "input at the top above a long scrollable list of currency rows (United States " + "dollar (USD), Canadian dollar (CAD), European Euro (EUR), Australian dollar (AUD), " + "…). The Save button is no longer reachable behind the panel.", + RESULTS_DIR) + assert kit.rb_reach(before, after, "Search currency", + source="Select your base currency") + finally: + rb_back_escape(1) + + @pytest.mark.rb(depth=2, jump_kind="reach", + expect="Settings▸Accounts -> 'Add account': links 9->0, text_fields 0->2, " + "comboboxes 0->2, checkboxes 0->2 and group 'Add Account' appears; " + "Escape restores the page") + def test_add_account_modal_replaces_page(self, ax): + """D2 (depth 2).""" + assert wait_for_web(ax) + assert rb_reach_accounts(ax), "could not reach Settings▸Accounts" + before_links = len(by_role(ax, "link")) + assert before_links >= 8, before_links + before = kit.rb_showing(ax) + try: + assert rb_enter_press(ax, "button", "Add account"), "button 'Add account' not found" + after = kit.rb_showing(ax) + els = web_els(ax) + assert _count(els, "link") == 0, "sidebar/page links still exposed behind the modal" + assert _count(els, "text_field") == 2, _count(els, "text_field") + assert _count(els, "combobox") == 2, _count(els, "combobox") + assert _count(els, "checkbox") == 2, _count(els, "checkbox") + assert _find_in(els, "group", "Add Account") is not None, "no group 'Add Account'" + assert _find_in(els, "heading", "No account added!") is None + screenshot_assert( + "structure_test_add_account_modal", + "A centred modal card titled 'Add Account' with the fields Account Name, Account " + "Group, Account Type (Securities) and Currency (United States dollar (USD)), two " + "toggle switches (Default Account off, Is Active on), Cancel and '+ Add Account' " + "buttons and a small x at the top-right. The sidebar and the accounts page behind " + "it are dimmed.", + RESULTS_DIR) + assert kit.rb_reach(before, after, "Add an investment account to track", + source="No account added!") + finally: + rb_back_escape(1) + + @pytest.mark.rb(depth=3, jump_kind="reach", + expect="Add Account modal -> Account Type select: a `list` appears holding " + "exactly the 3 options Securities/Cash/Crypto and the modal's 2 " + "text_fields drop to 0; Escape restores") + def test_account_type_option_list_appears(self, ax): + """D3 (depth 3).""" + assert wait_for_web(ax) + assert rb_reach_add_account_dialog(ax), "could not open the Add Account modal" + assert len(by_role(ax, "text_field")) == 2 + assert named(ax, "combobox", "Account Type") is not None + # the CG-clickable child label carrying the current selection must exist + assert any(e.role == "label" and (e.value or "").strip() in ("Securities", "Cash", "Crypto") + and "AXPress" in e.actions for e in web_els(ax)), \ + "no pressable Account Type selection label" + before = kit.rb_showing(ax) + try: + # AXPress does not open a Radix Select — CG-click the current-selection child label. + opt_names = [n for n in open_account_type(ax) if n] + after = kit.rb_showing(ax) + els = web_els(ax) + lists = [e for e in els if e.role == "list"] + assert len(lists) >= 1, "no `list` portal appeared" + assert len(opt_names) == 3, opt_names + assert set(opt_names) == {"Securities", "Cash", "Crypto"}, opt_names + scoped = [(e.name or e.value or "").strip() + for e in ax.find(role="label", root_id=lists[0].id, max_results=20)] + assert {"Securities", "Cash", "Crypto"} <= set(scoped), scoped + assert _count(els, "text_field") == 0, _count(els, "text_field") + assert kit.rb_reach(before, after, "Crypto", source="Account Group") + finally: + rb_back_escape(2) + + @pytest.mark.rb(depth=0, jump_kind="transition", + expect="button 'Expand Sidebar' -> nav link 'Dashboard' AXSize width 52 -> 172 " + "and the button renames to 'Collapse Sidebar'; collapsed again afterwards") + def test_sidebar_expand_changes_shape(self, ax): + """D4 (depth 0): an in-place layout/state flip, restored in the finally.""" + assert wait_for_web(ax) + name0, w0 = _sidebar_state(ax) + assert name0 == "Expand Sidebar", f"sidebar did not start collapsed ({name0!r})" + assert w0 > 0, "AXSize unreadable on the nav link" + assert w0 <= 100, f"collapsed nav-link width {w0} looks already expanded" + try: + assert rb_enter_press(ax, "button", "Expand Sidebar", wait=1.0) + name1, w1 = _sidebar_state(ax) + assert name1 == "Collapse Sidebar", f"button did not rename ({name1!r})" + assert named(ax, "button", "Expand Sidebar") is None + assert w1 >= 120, f"expanded nav-link width {w1} < 120" + assert w1 >= w0 + 50, f"width {w0} -> {w1} did not grow" + screenshot_assert( + "structure_test_sidebar_expanded", + "The left sidebar is widened: the text labels Dashboard, Holdings, Activities and " + "Settings are now visible next to their icons, plus the 'Wealthfolio' brand name " + "next to the logo at the top. The onboarding content is pushed to the right.", + RESULTS_DIR) + assert kit.rb_flip((name0, w0), (name1, w1)) + finally: + rb_enter_press(ax, "button", "Collapse Sidebar", wait=1.0) + + @pytest.mark.rb(depth=1, jump_kind="reach", + expect="home -> sidebar 'Settings': 1 heading -> 2 headings ('Settings' L2 + " + "'General' L1) plus combobox 'Currency' and button 'Save'; the Welcome " + "heading and the Illustration are gone") + def test_settings_surface_replaces_home(self, ax): + """D5 (depth 1).""" + assert wait_for_web(ax) + assert len(headings(ax)) == 1 + before = kit.rb_showing(ax) + assert rb_enter_settings(ax), "sidebar link 'Settings' not found" + after = kit.rb_showing(ax) + els = web_els(ax) + hs = [e for e in els if e.role == "heading"] + assert len(hs) == 2, [(e.name, e.value) for e in hs] + lv = {(e.name or "").strip(): _level(e) for e in hs} + assert lv.get("Settings") == 2, lv + assert lv.get("General") == 1, lv + assert _find_in(els, "combobox", "Currency") is not None + # EXISTENCE ONLY — pressing Save writes the DB (recon ## DO-NOT-TOUCH 1) + save = _find_in(els, "button", "Save") + assert save is not None and save.enabled is True + assert _find_in(els, "heading", "Welcome to Wealthfolio") is None + assert _find_in(els, "image", "Illustration") is None + screenshot_assert( + "structure_test_settings_general_surface", + "Settings▸General: a 'Settings' page title, a left column of sub-nav entries " + "General / Accounts / Goals / Appearance with General highlighted, and a 'General' " + "section reading 'Manage the general application settings and preferences.' with a " + "Currency combobox showing 'United States dollar (USD)' and a dark Save button.", + RESULTS_DIR) + assert kit.rb_reach(before, after, "Select your base currency", + source="Welcome to Wealthfolio") + + @pytest.mark.rb(depth=1, jump_kind="reach", + expect="onboarding gate: Settings▸General -> link 'Goals' redirects back to the " + "Welcome surface (heading 'Welcome to Wealthfolio' + image 'Illustration' " + "back, link 'Goals' gone)") + def test_onboarding_gate_redirects_home(self, ax): + """D6 (depth 1): the gated route collapses back to the onboarding surface.""" + assert wait_for_web(ax) + assert rb_enter_settings(ax), "sidebar link 'Settings' not found" + assert named(ax, "link", "Goals") is not None, "no settings sub-nav link 'Goals'" + before = kit.rb_showing(ax) + assert rb_enter_settings_tab(ax, "Goals") + after = kit.rb_showing(ax) + els = web_els(ax) + assert _find_in(els, "link", "Goals") is None, "settings sub-nav survived the redirect" + assert _find_in(els, "heading", "Welcome to Wealthfolio") is not None + assert _find_in(els, "image", "Illustration") is not None + assert _count(els, "heading") == 1 + assert kit.rb_reach(before, after, "Welcome to Wealthfolio", source="Goals") + + @pytest.mark.rb(depth=2, jump_kind="transition", + expect="Escape in the Add Account modal: links 0 -> >=8 and heading " + "'No account added!' + button 'Add account' are back (accounts-page " + "structure fully restored)") + def test_escape_restores_accounts_page(self, ax): + """D7 (depth 2): the shape census flips back from the modal's to the page's.""" + assert wait_for_web(ax) + assert rb_reach_add_account_dialog(ax), "could not open the Add Account modal" + modal_els = web_els(ax) + assert _find_in(modal_els, "group", "Add Account") is not None + assert _count(modal_els, "link") == 0 + census_modal = (_count(modal_els, "link"), _count(modal_els, "text_field"), + _count(modal_els, "checkbox")) + assert census_modal == (0, 2, 2), census_modal + modal = kit.rb_showing(ax) + rb_back_escape(1) + restored = kit.rb_showing(ax) + els = web_els(ax) + n_links = _count(els, "link") + assert n_links >= 8, n_links + assert _find_in(els, "heading", "No account added!") is not None + assert _find_in(els, "button", "Add account") is not None + assert _find_in(els, "group", "Add Account") is None, "the modal is still in the tree" + census_page = (n_links, _count(els, "text_field"), _count(els, "checkbox")) + assert census_page[1] == 0 and census_page[2] == 0, census_page + assert kit.rb_reach(modal, restored, "No account added!", + source="Add an investment account to track") + assert kit.rb_flip(census_modal, census_page) + + @pytest.mark.rb(depth=1, jump_kind="reach", + expect="Help ▸ Report Issue: top-level window count 1 -> 2 (a window 'alert' " + "holding label 'Contact Support' appears); its OK button returns the " + "count to 1") + def test_report_issue_alert_adds_window(self, ax): + """D8 (depth 1): a SEPARATE native window — it does NOT hide the main content, so + kit.rb_reach is used with no `source` (recon quirks table).""" + assert wait_for_web(ax) + assert len(_top_windows(ax)) == 1 + before = kit.rb_showing(ax) + try: + assert rb_enter_report_issue_alert(ax), "Help ▸ Report Issue not found" + after = kit.rb_showing(ax) + wins = _top_windows(ax) + assert len(wins) == 2, [(w.name or "") for w in wins] + assert any("alert" in (w.name or "").strip().lower() for w in wins), \ + [(w.name or "") for w in wins] + screenshot_assert( + "structure_test_report_issue_alert", + "A native macOS alert window floats above the Wealthfolio window: the app icon, " + "the bold line 'Contact Support', a message about emailing wealthfolio@teymz.com, " + "and a single OK button.", + RESULTS_DIR) + assert kit.rb_reach(before, after, "Contact Support") + finally: + oks = ax.find(role="button", name="OK", max_results=5) + if oks: + ax.action(oks[0].id, "AXPress") + time.sleep(0.8) + else: + rb_back_escape(1) + assert len(_top_windows(ax)) == 1, "the alert window was not dismissed" + + @pytest.mark.rb(depth=1, jump_kind="reach", + expect="Settings▸General -> sub-nav 'Accounts': 2 headings -> 3 headings with " + "'No account added!' plus buttons 'Add account'/'Add an account'; " + "combobox 'Currency' and button 'Save' are gone") + def test_accounts_subnav_changes_surface(self, ax): + """D9 (depth 1): sub-nav switch inside the Settings shell (extra verified delta).""" + assert wait_for_web(ax) + assert rb_enter_settings(ax), "sidebar link 'Settings' not found" + assert named(ax, "combobox", "Currency") is not None + before = kit.rb_showing(ax) + assert rb_enter_settings_tab(ax, "Accounts") + after = kit.rb_showing(ax) + els = web_els(ax) + assert _count(els, "heading") == 3, [(e.name, e.value) for e in els if e.role == "heading"] + assert _find_in(els, "heading", "No account added!") is not None + assert _find_in(els, "button", "Add account") is not None + assert _find_in(els, "button", "Add an account") is not None + assert _find_in(els, "combobox", "Currency") is None + assert _find_in(els, "button", "Save") is None + assert _count(els, "button") >= 2 + screenshot_assert( + "structure_test_accounts_surface", + "Settings▸Accounts: an 'Accounts' heading with the subtitle 'Manage your investment " + "and saving accounts.', an 'Add account' button at the top-right, and a dashed-border " + "empty card with a wallet icon reading 'No account added!' / \"You don't have any " + "account yet…\" plus an 'Add an account' button.", + RESULTS_DIR) + assert kit.rb_reach(before, after, "No account added!", + source="Select your base currency") + + @pytest.mark.rb(depth=3, jump_kind="reach", + expect="Add Account modal -> Currency popover: >=150 label rows and the " + "'Search currency...' box appear while the modal's 2 checkboxes and 2 " + "text_fields drop to 0; Escape restores the modal and the page") + def test_modal_currency_popover_expands_tree(self, ax): + """D10 (depth 3): the same picker, one surface deeper (extra verified delta).""" + assert wait_for_web(ax) + assert rb_reach_add_account_dialog(ax), "could not open the Add Account modal" + modal_els = web_els(ax) + assert _count(modal_els, "checkbox") == 2 + before_n = len(modal_els) + before = kit.rb_showing(ax) + try: + assert rb_enter_currency_popover(ax), "modal combobox 'Currency' not found" + after = kit.rb_showing(ax) + els = web_els(ax) + assert len(els) >= before_n + 100, f"{before_n} -> {len(els)}" + assert _count(els, "label") >= 150, _count(els, "label") + assert _has_text(els, "Search currency") + assert _count(els, "checkbox") == 0, _count(els, "checkbox") + assert _count(els, "text_field") == 0, _count(els, "text_field") + assert kit.rb_reach(before, after, "Search currency", + source="Add an investment account to track") + finally: + rb_back_escape(2) + + @pytest.mark.rb(depth=1, jump_kind="reach", + expect="home step link '2 Add your accounts' -> accounts surface: button " + "'Add account' + heading 'No account added!' appear while the Welcome " + "heading and image 'Illustration' disappear") + def test_step_link_reaches_accounts_surface(self, ax): + """D11 (depth 1): the onboarding step link is a real route, not decoration.""" + assert wait_for_web(ax) + assert named(ax, "image", "Illustration") is not None + before = kit.rb_showing(ax) + assert rb_enter_step_link(ax, "Add your accounts"), "no step link for adding accounts" + after = kit.rb_showing(ax) + els = web_els(ax) + assert _find_in(els, "heading", "Welcome to Wealthfolio") is None + assert _find_in(els, "image", "Illustration") is None + assert _find_in(els, "button", "Add account") is not None + assert _find_in(els, "heading", "No account added!") is not None + assert _count(els, "link") >= 8, _count(els, "link") + assert kit.rb_reach(before, after, "No account added!", source="Welcome to Wealthfolio") + + + @pytest.mark.rb(depth=2, jump_kind="transition", + expect="home -> Currency popover (via Settings▸General) -> Escape: the whole " + "reachable AX snapshot grows by >= 100 nodes (rb_showing ~139 -> ~267) " + "and shrinks back within 40 nodes of the start after Escape") + def test_popover_snapshot_grows_and_restores(self, ax): + """D13 (depth 2): snapshot MAGNITUDE round-trip. Absolute rb_showing totals drift a + little between launches (recon HARNESS FACTS), so only the deltas are asserted. + Also pins a structural floor on nesting depth (window > scroll_area > webarea > … ).""" + assert wait_for_web(ax) + assert _max_tree_depth(ax) >= 5, _max_tree_depth(ax) + assert rb_enter_settings(ax), "sidebar link 'Settings' not found" + page = kit.rb_showing(ax) + assert len(page) > 0, "rb_showing produced an empty snapshot" + try: + assert rb_enter_currency_popover(ax), "combobox 'Currency' not found" + opened = kit.rb_showing(ax) + assert _has_text(web_els(ax), "Search currency"), "the popover did not open" + assert len(opened) >= len(page) + 100, f"{len(page)} -> {len(opened)} nodes" + assert kit.rb_flip(len(page), len(opened)) + finally: + rb_back_escape(1) + closed = kit.rb_showing(ax) + assert len(closed) <= len(opened) - 100, f"{len(opened)} -> {len(closed)} nodes" + assert abs(len(closed) - len(page)) <= 40, f"page {len(page)} vs restored {len(closed)}" + assert named(ax, "button", "Save") is not None, "Settings▸General did not come back" + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="Settings▸Accounts -> sidebar 'Dashboard' (gated back to home): the " + "per-role census changes (image 0 -> 1, buttons >= 2 -> 1, headings " + "3 -> 1) — the whole surface is swapped, not patched") + def test_role_census_swaps_on_gated_return(self, ax): + """D14 (depth 1): the per-role fingerprint of the surface flips wholesale.""" + assert wait_for_web(ax) + assert rb_reach_accounts(ax), "could not reach Settings▸Accounts" + acc = _role_census(ax) + assert acc.get("heading", 0) == 3, acc + assert acc.get("button", 0) >= 2, acc + assert acc.get("image", 0) == 0, acc + rb_reach_home(ax) # sidebar 'Dashboard' -> the onboarding gate redirects home + home = _role_census(ax) + assert home.get("heading", 0) == 1, home + assert home.get("image", 0) == 1, home + # exactly one page button on the reference (the sidebar toggle); allow one transient + # launch-toast dismiss button (recon: the Notifications region can hold a toast). + assert 1 <= home.get("button", 0) <= 2, home + assert home.get("link", 0) >= 8, home + assert home.get("webarea", 0) == 1, home + assert kit.rb_flip(tuple(sorted(acc.items())), tuple(sorted(home.items()))) + diff --git a/macos/wealthfolio-wealthfolio/tests/test_ax_text.py b/macos/wealthfolio-wealthfolio/tests/test_ax_text.py new file mode 100644 index 0000000000000000000000000000000000000000..4c693af143c248562e3a90e3b86cdd2bd1af02b4 --- /dev/null +++ b/macos/wealthfolio-wealthfolio/tests/test_ax_text.py @@ -0,0 +1,760 @@ +"""test_ax_text.py — AX TEXT-CONTENT suite for Wealthfolio (Tauri v1 + WebKit). + +Every expected string below was OBSERVED on the reference app and is transcribed from +`recon.md` (`## TEXT`, `## AX_TREE`, `## VISUAL`). Nothing here is read from the app source. + +Contract (TEST_CONTRACT.md): pytest only — `Test*` classes, methods taking the `ax` +fixture, plain `assert`. No argparse, no `__main__`, no self-written results JSON: the +runner scores via pytest and the `@pytest.mark.rb(...)` markers land in text_results.json. + +Locators are SEMANTIC (AXRole + visible AXTitle/AXDescription, or a role scoped inside a +NAMED container) — never a child index or an AX tree path — so the same suite drives the +reference app and a recreation built on a different framework. + +Text is always read from INSIDE the app's own `webarea` via `web_els(ax)` (the menu bar is +never a text source for this lane). +""" + +import json +import os +import subprocess +import time + +import pytest + +import rb_testgen_kit as kit +import verifier_helpers as helpers + +RESULTS_DIR = os.environ.get( + "RESULTS_DIR", + os.path.join(os.path.dirname(os.path.abspath(__file__)), "results"), +) + + +# ───────────────────────── screenshot assertion helper ───────────────────────── + +def screenshot_assert(test_name, description, results_dir): + 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) + + +# ─────────────── RECIPES from recon.md (verified interaction primitives) ─────────────── + +_REVEALED_PIDS = set() + + +def _reveal_ui_once(ax): + """Generic reveal contract — best-effort, idempotent per app instance. + + recon `## APP` records REVEAL_STEPS = None (a plain windowed app: the `Wealthfolio` + window is on screen at launch), so this normally returns straight away after seeing + the webarea. If NO window/web area is exposed at all — a genuinely hidden UI, e.g. a + recreation built as an LSUIElement/status-item app — it falls back to the deployed + ax_helpers' `ensure_ui_visible()`, which tries every reveal path (status-item AXPress, + status-item -> menu -> Preferences/Settings, Cmd+,). Never raises and never skips a + test: if the UI stays hidden the test's own assertions fail truthfully.""" + try: + pid = ax.get_pid() + except Exception: + pid = None + if pid in _REVEALED_PIDS: + return + if pid is not None: + _REVEALED_PIDS.add(pid) + try: + if ax.find(role="webarea", max_results=1, max_depth=10): + return + ax.ensure_ui_visible() + time.sleep(1.0) + except Exception: + pass + + +# ---------- reads ---------- +def wait_for_web(ax, timeout=20.0): + """REQUIRED first line of every test: poll until the WebKit content is in the AX tree.""" + _reveal_ui_once(ax) + deadline = time.time() + timeout + while time.time() < deadline: + for e in web_els(ax): + if e.role == "link" and e.name == "Settings": + return True + time.sleep(0.4) + return False + + +def web_els(ax): + """All elements inside the app's web area (excludes the menu bar).""" + wa = ax.find(role="webarea", max_results=2) + if not wa: + return [] + return ax.find(max_results=1500, root_id=wa[0].id, max_depth=25) + + +def by_role(ax, role): + return [e for e in web_els(ax) if e.role == role] + + +def named(ax, role, name): + for e in web_els(ax): + if e.role == role and (e.name or "") == name: + return e + return None + + +def texts(ax): + """Every visible text string in the web area (label .value or .name).""" + return [(e.value or e.name) for e in web_els(ax) if e.role == "label" and (e.value or e.name)] + + +def headings(ax): + return [(e.name, e.value) for e in web_els(ax) if e.role == "heading"] # value == heading level + + +# ---------- navigation (rb_enter_* / rb_reach_* so the depth audit sees them) ---------- +def rb_enter_press(ax, role, name, wait=1.6): + """AXPress a named link/button and settle. Returns True if the element existed.""" + el = named(ax, role, name) + if el is None: + return False + ax.action(el.id, "AXPress") + time.sleep(wait) + return True + + +def rb_reach_home(ax): + """Go to the Welcome/onboarding surface: pressing sidebar 'Dashboard' redirects there.""" + helpers.send_key(helpers.KC_ESCAPE); time.sleep(0.4) + rb_enter_press(ax, "link", "Dashboard") + + +def rb_enter_settings(ax): + """Sidebar 'Settings' link -> Settings ▸ General surface (depth 1).""" + return rb_enter_press(ax, "link", "Settings") + + +def rb_enter_settings_tab(ax, tab): + """Settings sub-nav link: 'General' | 'Accounts' | 'Goals' | 'Appearance' (depth 1).""" + return rb_enter_press(ax, "link", tab) + + +def rb_reach_accounts(ax): + """Settings ▸ Accounts (depth 1): sidebar Settings, then the 'Accounts' sub-nav link.""" + rb_enter_settings(ax) + return rb_enter_settings_tab(ax, "Accounts") + + +def rb_reach_add_account_dialog(ax): + """Settings ▸ Accounts ▸ 'Add account' -> the Add Account modal (depth 2).""" + rb_reach_accounts(ax) + return rb_enter_press(ax, "button", "Add account") + + +def rb_enter_currency_popover(ax): + """AXPress the 'Currency' combobox -> the currency search popover. + depth 2 from home (via Settings▸General) / depth 3 from inside the Add Account dialog.""" + return rb_enter_press(ax, "combobox", "Currency", wait=1.5) + + +def rb_back_escape(n=1): + """Escape closes (in order) popover -> dialog -> menu. VERIFIED reliable.""" + for _ in range(n): + helpers.send_key(helpers.KC_ESCAPE) + time.sleep(0.6) + + +def currency_search_field(ax): + """The popover's search input == the only combobox with an EMPTY name.""" + for e in web_els(ax): + if e.role == "combobox" and not (e.name or ""): + return e + return None + + +def ax_attr(ax, el, attr): + """Read a raw AX attribute (AXHelp / AXSelected / AXPlaceholderValue / AXMenuItemCmdChar / …). + Returns None when the attribute is unsupported (err != 0) instead of raising, so a + recreation that omits it FAILS the assertion with a readable message.""" + import ApplicationServices as AS + try: + ref = ax._get_ref(el.id) + if ref is None: + return None + err, v = AS.AXUIElementCopyAttributeValue(ref, attr, None) + return v if err == 0 else None + except Exception: + return None + + +# ─────────────────────── lane-local text helpers (verdict wrappers) ─────────────────────── + +def _norm(s): + """Strip surrounding whitespace (comboboxes carry a trailing '\\n') and fold + typographic quotes/ellipsis to ASCII so an EXACT content compare survives a + font-level curly-quote substitution. Never weakens the compared words.""" + if s is None: + return "" + if not isinstance(s, str): + s = str(s) + return (s.replace("’", "'").replace("‘", "'") + .replace("“", '"').replace("”", '"') + .replace("…", "...").strip()) + + +def text_snapshot(ax): + """A COMPARABLE snapshot of the web area's visible text: a sorted list of normalized + strings (never `str()` of AX elements — element ids are addresses that change).""" + return sorted({_norm(s) for s in texts(ax) if _norm(s)}) + + +def rb_value_text_present(strings, expected): + """VALUE verdict wrapper (kit.rb_value): `expected` is present VERBATIM among the + observed strings, tolerating surrounding whitespace / curly quotes.""" + want = _norm(expected) + match = next((s for s in (_norm(x) for x in strings) if s == want), None) + return kit.rb_value(match, want) + + +def rb_value_heading_level(ax, name, level): + """VALUE verdict wrapper (kit.rb_value): the heading with this NAME reports this LEVEL + in its AXValue (WebKit exposes h1..h6 as AXValue 1..6).""" + want_name = _norm(name) + for hname, hval in headings(ax): + if _norm(hname) == want_name: + return kit.rb_value(_norm(hval), str(level)) + return False + + +def toggle_button_name(ax): + """The sidebar toggle button's NAME — 'Expand Sidebar' or 'Collapse Sidebar' + (matched by role + visible label, not by position).""" + for e in web_els(ax): + if e.role == "button" and _norm(e.name) in ("Expand Sidebar", "Collapse Sidebar"): + return _norm(e.name) + return "" + + +def sidebar_logo_link(ax): + """The unnamed brand/logo `link` at the top of the NAMED 'Sidebar' group (routes to '/').""" + wa = ax.find(role="webarea", max_results=2) + if not wa: + return None + roots = [g.id for g in ax.find(role="group", root_id=wa[0].id, max_results=80, max_depth=25) + if _norm(g.name) == "Sidebar"] or [wa[0].id] + for rid in roots: + for e in ax.find(role="link", root_id=rid, max_results=40, max_depth=25): + if not _norm(e.name): + return e + return None + + +def rb_reach_home_via_logo(ax): + """Press the unnamed sidebar logo link -> the onboarding gate lands on Welcome (depth 1).""" + el = sidebar_logo_link(ax) + if el is None: + return False + ax.action(el.id, "AXPress") + time.sleep(1.6) + return True + + +def rb_enter_onboarding_step(ax, link_name, keyword, wait=1.6): + """Press one of the home surface's numbered onboarding step links. + Located by its exact observed accessible name first, else by a visible-text keyword + match on the link name (locator priority: visible label, never a child index).""" + if rb_enter_press(ax, "link", link_name, wait=wait): + return True + want = _norm(keyword).lower() + for e in web_els(ax): + if e.role == "link" and want in _norm(e.name).lower(): + ax.action(e.id, "AXPress") + time.sleep(wait) + return True + return False + + +# ─────────────────────────── observed content (from recon ## TEXT) ─────────────────────────── + +TAGLINE = ("Your personal financial portfolio tracker, right on your computer. " + "Here's how to get started:") +HOME_LABELS = [ + "Welcome to Wealthfolio", TAGLINE, + "1", "Set your main currency", + "2", "Add your accounts", + "3", "Add or import activities", + "Let's get started", +] +NAV_LABELS = ["Dashboard", "Holdings", "Activities", "Settings"] +HOME_CORE = set(HOME_LABELS) | set(NAV_LABELS) | {"Wealthfolio"} +ACCOUNTS_EMPTY_BODY = ("You don't have any account yet. " + "Start adding your investment accounts.") + + +# ═══════════════════════════════ HOME SURFACE (depth 0) ═══════════════════════════════ + +class TestTextHomeSurface: + """Text-bearing nodes of the launch surface (recon SURFACE A: 14 labels).""" + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="home labels contain 'Welcome to Wealthfolio', the tagline " + "\"Your personal financial portfolio tracker...\", the three step " + "titles and the numbers 1/2/3, plus \"Let's get started\"") + def test_home_onboarding_labels(self, ax): + assert wait_for_web(ax), "WebKit content never appeared in the AX tree" + observed = text_snapshot(ax) + # MEMBERSHIP only — launch toasts ("Syncing quotes…") can add transient text. + missing = [t for t in HOME_LABELS if not rb_value_text_present(observed, t)] + assert not missing, f"home text missing {missing!r}; observed={observed!r}" + assert rb_value_text_present(observed, "Welcome to Wealthfolio") + screenshot_assert( + "text_test_home_onboarding_labels", + "Wealthfolio onboarding/home screen: a narrow dark-icon sidebar on the left, a " + "circular coin/pie illustration, the bold heading 'Welcome to Wealthfolio', the " + "sub-text \"Your personal financial portfolio tracker, right on your computer. " + "Here's how to get started:\", three numbered steps 1 'Set your main currency', " + "2 'Add your accounts', 3 'Add or import activities' with arrows, and a dark " + "\"Let's get started\" button. The window title bar reads 'Wealthfolio'.", + RESULTS_DIR) + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="sidebar text: brand label 'Wealthfolio', nav labels " + "Dashboard/Holdings/Activities/Settings, each link AXHelp == its " + "name, toggle button named 'Expand Sidebar' with AXHelp 'Toggle Sidebar'") + def test_home_sidebar_labels_and_help(self, ax): + assert wait_for_web(ax), "WebKit content never appeared in the AX tree" + observed = text_snapshot(ax) + assert rb_value_text_present(observed, "Wealthfolio"), \ + f"sidebar brand label 'Wealthfolio' missing; observed={observed!r}" + for nav in NAV_LABELS: + assert rb_value_text_present(observed, nav), f"sidebar label {nav!r} missing" + link = named(ax, "link", nav) + assert link is not None, f"sidebar link {nav!r} not found" + help_txt = _norm(ax_attr(ax, link, "AXHelp")) + assert rb_value_text_present([help_txt], nav), \ + f"link {nav!r} AXHelp is {help_txt!r}, expected {nav!r}" + btn = named(ax, "button", "Expand Sidebar") + assert btn is not None, "sidebar toggle button 'Expand Sidebar' not found" + assert rb_value_text_present([_norm(ax_attr(ax, btn, "AXHelp"))], "Toggle Sidebar") + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="heading 'Welcome to Wealthfolio' reports AXValue 1 (h1) on home") + def test_home_heading_level(self, ax): + assert wait_for_web(ax), "WebKit content never appeared in the AX tree" + assert rb_value_heading_level(ax, "Welcome to Wealthfolio", 1), \ + f"expected heading ('Welcome to Wealthfolio', 1); observed={headings(ax)!r}" + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="main window AXTitle == 'Wealthfolio' (also the webarea's title)") + def test_window_title_text(self, ax): + assert wait_for_web(ax), "WebKit content never appeared in the AX tree" + wins = ax.find(role="window", max_results=6, max_depth=2) + titles = [_norm(w.name) for w in wins] + assert rb_value_text_present(titles, "Wealthfolio"), \ + f"no window titled 'Wealthfolio'; window titles={titles!r}" + wa = ax.find(role="webarea", max_results=2) + assert wa, "no webarea under the window" + assert rb_value_text_present([_norm(wa[0].name)], "Wealthfolio"), \ + f"webarea title is {wa[0].name!r}, expected 'Wealthfolio'" + + @pytest.mark.rb(depth=0, jump_kind="none", + expect="all asserted text is read inside the app's own webarea (no menu-bar " + "roles there) and the home surface exposes >= 14 non-empty text strings") + def test_home_text_scoped_to_webarea(self, ax): + assert wait_for_web(ax), "WebKit content never appeared in the AX tree" + wa = ax.find(role="webarea", max_results=3) + assert len(wa) >= 1, "the app exposes no webarea to read text from" + els = web_els(ax) + assert els, "web_els() returned nothing — text would be read from outside the app content" + # Scoping proof: the subtree text comes from is app CONTENT, never the menu bar. + leaked = sorted({e.role for e in els} & {"menu_bar", "menu_bar_item", "menu_item", "menu"}) + assert not leaked, f"menu-bar roles {leaked!r} are inside the webarea text scope" + raw = [_norm(s) for s in texts(ax) if _norm(s)] # every text string, in tree order + assert len(raw) >= 14, \ + f"expected >= 14 non-empty web-area text strings, got {len(raw)}: {raw!r}" + assert "Welcome to Wealthfolio" in set(raw), f"home text set: {sorted(set(raw))!r}" + + @pytest.mark.rb(depth=0, jump_kind="none", + expect="text census: >= 14 text-bearing web nodes with content, >= 180 " + "characters of unique text, every string's char count == len(its " + "stripped text), and at most one unnamed link (the sidebar logo)") + def test_home_text_widget_census(self, ax): + assert wait_for_web(ax), "WebKit content never appeared in the AX tree" + els = web_els(ax) + with_text = [e for e in els if _norm(e.value) or _norm(e.name)] + without_text = [e for e in els if not (_norm(e.value) or _norm(e.name))] + strings = text_snapshot(ax) + assert len(with_text) >= 14, \ + f"only {len(with_text)} web nodes carry text ({len(without_text)} carry none)" + # character-count integrity: each read string is a real, whitespace-clean payload + for s in strings: + assert len(s) == len(s.strip()) and len(s) > 0, f"bad char count for {s!r}" + total = sum(len(s) for s in strings) + assert total >= 180, f"home text is only {total} characters: {strings!r}" + # the tagline alone must account for a long-form sentence (>= 60 chars) + assert max(len(s) for s in strings) >= 60, \ + f"no long-form text on the home surface: {strings!r}" + # widgets that SHOULD carry text do: every heading is named, links are named + assert all(_norm(h) for h, _ in headings(ax)), f"unnamed heading in {headings(ax)!r}" + unnamed_links = [e for e in els if e.role == "link" and not _norm(e.name)] + assert len(unnamed_links) <= 1, \ + f"{len(unnamed_links)} links have no accessible name (only the logo may)" + + +# ═══════════════════════ SETTINGS ▸ GENERAL (depth 1) ═══════════════════════ + +class TestTextSettingsGeneral: + """recon SURFACE B — reached with rb_enter_settings (sidebar 'Settings').""" + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="Settings▸General text: 'Manage the general application settings and " + "preferences.', 'Currency', 'Select your base currency.', combobox " + "value 'United States dollar (USD)' and a 'Save' button") + def test_general_page_text(self, ax): + assert wait_for_web(ax), "WebKit content never appeared in the AX tree" + assert rb_enter_settings(ax), "sidebar link 'Settings' not found" + observed = text_snapshot(ax) + for expected in ("Manage the general application settings and preferences.", + "Currency", "Select your base currency."): + assert rb_value_text_present(observed, expected), \ + f"Settings▸General text missing {expected!r}; observed={observed!r}" + combo = named(ax, "combobox", "Currency") + assert combo is not None, "combobox 'Currency' not found on Settings▸General" + assert kit.rb_value(_norm(combo.value), "United States dollar (USD)"), \ + f"Currency combobox value is {combo.value!r}" + save = named(ax, "button", "Save") + assert save is not None, "button 'Save' not found on Settings▸General" + assert rb_value_text_present([_norm(save.name)], "Save") + screenshot_assert( + "text_test_settings_general", + "Wealthfolio Settings page: 'Settings' title with a left column listing General / " + "Accounts / Goals / Appearance, and the 'General' section reading 'Manage the general " + "application settings and preferences.' above a 'Currency' field whose combobox shows " + "'United States dollar (USD)', the hint 'Select your base currency.' and a dark Save button.", + RESULTS_DIR) + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="Settings▸General heading levels: ('Settings', 2) and ('General', 1)") + def test_general_heading_levels(self, ax): + assert wait_for_web(ax), "WebKit content never appeared in the AX tree" + assert rb_enter_settings(ax), "sidebar link 'Settings' not found" + assert rb_value_heading_level(ax, "Settings", 2), \ + f"expected heading ('Settings', 2); observed={headings(ax)!r}" + assert rb_value_heading_level(ax, "General", 1), \ + f"expected heading ('General', 1); observed={headings(ax)!r}" + + +# ═══════════════════════ SETTINGS ▸ ACCOUNTS (depth 1) ═══════════════════════ + +class TestTextSettingsAccounts: + """recon SURFACE C — reached with rb_reach_accounts (Settings then 'Accounts').""" + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="Settings▸Accounts text: 'Manage your investment and saving " + "accounts.', 'No account added!', \"You don't have any account yet. " + "Start adding your investment accounts.\" plus buttons 'Add account' " + "and 'Add an account'") + def test_accounts_page_text(self, ax): + assert wait_for_web(ax), "WebKit content never appeared in the AX tree" + assert rb_reach_accounts(ax), "settings sub-nav link 'Accounts' not found" + observed = text_snapshot(ax) + for expected in ("Manage your investment and saving accounts.", + "No account added!", ACCOUNTS_EMPTY_BODY): + assert rb_value_text_present(observed, expected), \ + f"Settings▸Accounts text missing {expected!r}; observed={observed!r}" + for btn_name in ("Add account", "Add an account"): + btn = named(ax, "button", btn_name) + assert btn is not None, f"button {btn_name!r} not found on Settings▸Accounts" + assert rb_value_text_present([_norm(btn.name)], btn_name) + screenshot_assert( + "text_test_accounts_empty", + "Wealthfolio Settings ▸ Accounts (empty): an 'Accounts' heading with the sub-text " + "'Manage your investment and saving accounts.' and an 'Add account' button top-right, " + "over a dashed-border empty card with a wallet icon reading 'No account added!' and " + "\"You don't have any account yet. Start adding your investment accounts.\" plus an " + "'Add an account' button.", + RESULTS_DIR) + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="Settings▸Accounts heading levels: ('Accounts', 1) and " + "('No account added!', 2)") + def test_accounts_heading_levels(self, ax): + assert wait_for_web(ax), "WebKit content never appeared in the AX tree" + assert rb_reach_accounts(ax), "settings sub-nav link 'Accounts' not found" + assert rb_value_heading_level(ax, "Accounts", 1), \ + f"expected heading ('Accounts', 1); observed={headings(ax)!r}" + assert rb_value_heading_level(ax, "No account added!", 2), \ + f"expected heading ('No account added!', 2); observed={headings(ax)!r}" + + +# ═══════════════════════ ADD ACCOUNT MODAL (depth 2) ═══════════════════════ + +class TestTextAddAccountModal: + """recon SURFACE D — reached with rb_reach_add_account_dialog. NEVER presses the + modal's 'Add Account' submit (it would write the DB); always Escapes back out.""" + + @pytest.mark.rb(depth=2, jump_kind="value", + expect="modal text 'Add an investment account to track.', field labels " + "Account Name/Account Group/Account Type/Currency, switch labels " + "Default Account/Is Active and heading ('Add Account', 2)") + def test_modal_labels_and_heading(self, ax): + assert wait_for_web(ax), "WebKit content never appeared in the AX tree" + assert rb_reach_add_account_dialog(ax), "the Add Account modal did not open" + try: + observed = text_snapshot(ax) + for expected in ("Add Account", "Add an investment account to track.", + "Account Name", "Account Group", "Account Type", "Currency", + "Default Account", "Is Active"): + assert rb_value_text_present(observed, expected), \ + f"Add Account modal text missing {expected!r}; observed={observed!r}" + assert rb_value_heading_level(ax, "Add Account", 2), \ + f"expected heading ('Add Account', 2); observed={headings(ax)!r}" + screenshot_assert( + "text_test_add_account_modal", + "Wealthfolio 'Add Account' modal: a centred card titled 'Add Account' with the " + "sub-text 'Add an investment account to track.', fields Account Name (placeholder " + "'Account display name'), Account Group (placeholder 'Retirement, 401K, RRSP, " + "TFSA,...'), Account Type showing 'Securities' and Currency showing 'United States " + "dollar (USD)', two toggle switches labelled 'Default Account' (off) and 'Is Active' " + "(on), Cancel / '+ Add Account' buttons and a ✕ at the top-right.", + RESULTS_DIR) + finally: + rb_back_escape(1) # always restore: close the modal without saving + + @pytest.mark.rb(depth=2, jump_kind="value", + expect="modal AXPlaceholderValue text: 'Account display name' on Account " + "Name and 'Retirement, 401K, RRSP, TFSA,...' on Account Group") + def test_modal_placeholders(self, ax): + assert wait_for_web(ax), "WebKit content never appeared in the AX tree" + assert rb_reach_add_account_dialog(ax), "the Add Account modal did not open" + try: + name_field = named(ax, "text_field", "Account Name") + group_field = named(ax, "text_field", "Account Group") + assert name_field is not None, "text_field 'Account Name' not found in the modal" + assert group_field is not None, "text_field 'Account Group' not found in the modal" + name_ph = _norm(ax_attr(ax, name_field, "AXPlaceholderValue")) + group_ph = _norm(ax_attr(ax, group_field, "AXPlaceholderValue")) + assert kit.rb_value(name_ph, "Account display name"), \ + f"Account Name placeholder is {name_ph!r}" + assert kit.rb_value(group_ph, "Retirement, 401K, RRSP, TFSA,..."), \ + f"Account Group placeholder is {group_ph!r}" + finally: + rb_back_escape(1) + + +# ═══════════════════════ CURRENCY POPOVER (depth 2) ═══════════════════════ + +class TestTextCurrencyPopover: + """recon SURFACE E — Settings▸General then the 'Currency' combobox.""" + + @pytest.mark.rb(depth=2, jump_kind="value", + expect="currency popover search field AXPlaceholderValue == 'Search " + "currency...' and a label with the same text is present") + def test_popover_search_placeholder_text(self, ax): + assert wait_for_web(ax), "WebKit content never appeared in the AX tree" + assert rb_enter_settings(ax), "sidebar link 'Settings' not found" + assert rb_enter_currency_popover(ax), "combobox 'Currency' not found" + try: + sf = currency_search_field(ax) + assert sf is not None, "the popover's unnamed search combobox was not found" + placeholder = _norm(ax_attr(ax, sf, "AXPlaceholderValue")) + assert kit.rb_value(placeholder, "Search currency..."), \ + f"search field placeholder is {placeholder!r}" + assert rb_value_text_present(text_snapshot(ax), "Search currency..."), \ + "no label reading 'Search currency...' inside the popover" + screenshot_assert( + "text_test_currency_popover", + "Wealthfolio currency picker popover open over the Settings ▸ General page: a " + "dropdown panel whose top input reads the placeholder 'Search currency...' above a " + "long scrollable list of currency rows (United States dollar (USD), Canadian dollar " + "(CAD), European Euro (EUR), Australian dollar (AUD), ...).", + RESULTS_DIR) + finally: + rb_back_escape(1) # always restore: close the popover + + +# ═══════════════════ INTERACTION -> TEXT CHANGE (transition / reach) ═══════════════════ + +class TestTextTransitions: + """One test per row of recon `## TEXT` -> 'interaction → text change'. Each takes a + text SNAPSHOT before and after the trigger and asserts the change with kit.rb_flip / + kit.rb_reach (never `str()` of AX elements).""" + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="pressing sidebar link 'Settings' makes the text set gain 'Select " + "your base currency.' and lose 'Welcome to Wealthfolio'") + def test_settings_press_changes_text(self, ax): + assert wait_for_web(ax), "WebKit content never appeared in the AX tree" + before = text_snapshot(ax) + assert "Welcome to Wealthfolio" in before, f"not on the home surface: {before!r}" + assert rb_enter_settings(ax), "sidebar link 'Settings' not found" + after = text_snapshot(ax) + assert kit.rb_flip(before, after), f"text set did not change: {after!r}" + assert "Select your base currency." in after, f"General text missing: {after!r}" + assert "Manage the general application settings and preferences." in after + assert "Welcome to Wealthfolio" not in after, "the Welcome text survived the navigation" + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="pressing sub-nav link 'Accounts' from General makes the text set " + "gain 'No account added!' and lose 'Select your base currency.'") + def test_accounts_press_changes_text(self, ax): + assert wait_for_web(ax), "WebKit content never appeared in the AX tree" + assert rb_enter_settings(ax), "sidebar link 'Settings' not found" + before = text_snapshot(ax) + assert "Select your base currency." in before, f"not on Settings▸General: {before!r}" + assert rb_enter_settings_tab(ax, "Accounts"), "sub-nav link 'Accounts' not found" + after = text_snapshot(ax) + assert kit.rb_flip(before, after), f"text set did not change: {after!r}" + assert "No account added!" in after, f"Accounts text missing: {after!r}" + assert "Manage your investment and saving accounts." in after + assert "Select your base currency." not in after, "General text survived the navigation" + + @pytest.mark.rb(depth=2, jump_kind="reach", + expect="pressing 'Add account' surfaces the modal text 'Add an investment " + "account to track.' while the sidebar text 'Dashboard' disappears") + def test_add_account_modal_replaces_page_text(self, ax): + assert wait_for_web(ax), "WebKit content never appeared in the AX tree" + assert rb_reach_accounts(ax), "settings sub-nav link 'Accounts' not found" + # max_depth=25 (> the kit default 12) so the modal's deeply-nested label is inside + # the snapshot; only membership/deltas are asserted, never an absolute count. + before_showing = kit.rb_showing(ax, max_depth=25) + before_text = text_snapshot(ax) + assert "Dashboard" in before_text and "No account added!" in before_text, \ + f"not on Settings▸Accounts: {before_text!r}" + try: + assert rb_enter_press(ax, "button", "Add account"), "button 'Add account' not found" + after_showing = kit.rb_showing(ax, max_depth=25) + after_text = text_snapshot(ax) + assert kit.rb_reach(before_showing, after_showing, + target="Add an investment account to track.", + source="Dashboard"), \ + "the modal text did not appear while the sidebar text disappeared" + assert "Add an investment account to track." in after_text, \ + f"modal text missing: {after_text!r}" + assert "Dashboard" not in after_text, \ + f"the modal did not hide the sidebar text: {after_text!r}" + finally: + rb_back_escape(1) + + @pytest.mark.rb(depth=2, jump_kind="transition", + expect="Escape in the Add Account modal restores the accounts-page text " + "('No account added!' back, modal sub-text gone)") + def test_escape_restores_accounts_text(self, ax): + assert wait_for_web(ax), "WebKit content never appeared in the AX tree" + assert rb_reach_add_account_dialog(ax), "the Add Account modal did not open" + before = text_snapshot(ax) + assert "Add an investment account to track." in before, f"modal not open: {before!r}" + rb_back_escape(1) + time.sleep(0.4) # let the accounts page re-render behind the closed modal + after = text_snapshot(ax) + assert kit.rb_flip(before, after), f"text set did not change on Escape: {after!r}" + assert "No account added!" in after, f"accounts text not restored: {after!r}" + assert ACCOUNTS_EMPTY_BODY in after, f"accounts body text not restored: {after!r}" + assert "Add an investment account to track." not in after, "modal text survived Escape" + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="pressing sub-nav link 'Goals' hits the onboarding gate: the text set " + "gains 'Welcome to Wealthfolio' and loses 'Goals'") + def test_goals_gate_restores_welcome_text(self, ax): + assert wait_for_web(ax), "WebKit content never appeared in the AX tree" + assert rb_enter_settings(ax), "sidebar link 'Settings' not found" + before = text_snapshot(ax) + assert "Goals" in before, f"settings sub-nav text 'Goals' not present: {before!r}" + assert rb_enter_settings_tab(ax, "Goals"), "sub-nav link 'Goals' not found" + after = text_snapshot(ax) + assert kit.rb_flip(before, after), f"text set did not change: {after!r}" + assert "Welcome to Wealthfolio" in after, f"gate did not return home: {after!r}" + assert "Goals" not in after, f"'Goals' text survived the gate redirect: {after!r}" + + @pytest.mark.rb(depth=0, jump_kind="transition", + expect="pressing the sidebar toggle flips the button NAME 'Expand Sidebar' " + "-> 'Collapse Sidebar' while the label set is unchanged") + def test_expand_sidebar_flips_button_name(self, ax): + assert wait_for_web(ax), "WebKit content never appeared in the AX tree" + before_name = toggle_button_name(ax) + before_text = text_snapshot(ax) + assert before_name == "Expand Sidebar", f"toggle button name is {before_name!r}" + assert HOME_CORE <= set(before_text), f"home labels incomplete: {before_text!r}" + try: + assert rb_enter_press(ax, "button", "Expand Sidebar"), \ + "button 'Expand Sidebar' not found" + after_name = toggle_button_name(ax) + after_text = text_snapshot(ax) + assert kit.rb_flip(before_name, after_name), \ + f"toggle button name did not change (still {after_name!r})" + assert after_name == "Collapse Sidebar", f"toggle button name is {after_name!r}" + assert HOME_CORE <= set(after_text), \ + f"the label set changed with the sidebar width: {after_text!r}" + screenshot_assert( + "text_test_sidebar_expanded", + "Wealthfolio home screen with the sidebar EXPANDED: the sidebar has widened and " + "now shows the text labels Dashboard / Holdings / Activities / Settings next to " + "their icons plus the 'Wealthfolio' brand next to the logo; the toggle button is " + "now 'Collapse Sidebar'. The main area still shows 'Welcome to Wealthfolio'.", + RESULTS_DIR) + finally: + rb_enter_press(ax, "button", "Collapse Sidebar", wait=1.0) # restore + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="pressing link '3 Add or import activities' keeps the Welcome text " + "(onboarding gate) and produces no settings text") + def test_step3_link_keeps_welcome_text(self, ax): + assert wait_for_web(ax), "WebKit content never appeared in the AX tree" + before = text_snapshot(ax) + assert "Welcome to Wealthfolio" in before, f"not on the home surface: {before!r}" + assert rb_enter_onboarding_step(ax, "3 Add or import activities", + "Add or import activities"), \ + "link '3 Add or import activities' not found" + after = text_snapshot(ax) + # The gate keeps us on Welcome -> the text an interaction PRODUCES is the SAME text. + for expected in ("Welcome to Wealthfolio", TAGLINE, "Add or import activities"): + assert rb_value_text_present(after, expected), \ + f"Welcome text {expected!r} disappeared; observed={after!r}" + for leaked in ("Select your base currency.", "No account added!", + "Manage the general application settings and preferences."): + assert leaked not in after, f"unexpected settings text {leaked!r} after the gate" + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="pressing link '1 Set your main currency' swaps the Welcome text for " + "the General-page text 'Select your base currency.'") + def test_step1_link_shows_currency_text(self, ax): + assert wait_for_web(ax), "WebKit content never appeared in the AX tree" + before = text_snapshot(ax) + assert "Welcome to Wealthfolio" in before, f"not on the home surface: {before!r}" + assert rb_enter_onboarding_step(ax, "1 Set your main currency", + "Set your main currency"), \ + "link '1 Set your main currency' not found" + after = text_snapshot(ax) + assert kit.rb_flip(before, after), f"text set did not change: {after!r}" + assert "Select your base currency." in after, f"General text missing: {after!r}" + assert "Welcome to Wealthfolio" not in after, "the Welcome text survived the navigation" + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="pressing the unnamed sidebar logo link from Settings▸General brings " + "the Welcome text back and drops 'Select your base currency.'") + def test_logo_link_restores_welcome_text(self, ax): + assert wait_for_web(ax), "WebKit content never appeared in the AX tree" + assert rb_enter_settings(ax), "sidebar link 'Settings' not found" + before = text_snapshot(ax) + assert "Select your base currency." in before, f"not on Settings▸General: {before!r}" + assert rb_reach_home_via_logo(ax), "the unnamed sidebar logo link was not found" + after = text_snapshot(ax) + assert kit.rb_flip(before, after), f"text set did not change: {after!r}" + assert "Welcome to Wealthfolio" in after, f"Welcome text not restored: {after!r}" + assert TAGLINE in after, f"Welcome tagline not restored: {after!r}" + assert "Select your base currency." not in after, "General text survived the navigation" diff --git a/macos/wealthfolio-wealthfolio/tests/test_ax_workflow.py b/macos/wealthfolio-wealthfolio/tests/test_ax_workflow.py new file mode 100644 index 0000000000000000000000000000000000000000..8cf74cde2e169ee2a5f10a78f5cb313745dc5f90 --- /dev/null +++ b/macos/wealthfolio-wealthfolio/tests/test_ax_workflow.py @@ -0,0 +1,248 @@ +#!/usr/bin/env python3 +"""AX WORKFLOW tests for Wealthfolio (Tauri v1 + WebKit, bundle com.teymz.wealthfolio). + +Phase-3 coverage top-up written by the orchestrator: three multi-surface workflows that no +single lane owned, all verified against the reference app. + + W1 the onboarding gate on the SECOND gated settings route (`Appearance`) — the lanes only + covered `Goals`. + W2 leaving the currency popover with Escape restores the Settings ▸ General surface + (the reach-BACK direction; the lanes only proved the forward jump). + W3 cross-surface state preservation: text typed into the Add Account modal survives a + round trip through the nested currency popover, while the picked currency commits and + the untouched Account Type keeps its default (depth 3). + +Helpers are the verified primitives from recon.md `## RECIPES`. +DO-NOT-TOUCH honoured: `button 'Save'` and the modal's `button 'Add Account'` submit are +never pressed; every opened surface is dismissed with Escape. +""" + +import json +import os +import subprocess +import time + +import pytest + +import rb_testgen_kit as kit +import verifier_helpers as helpers + +RESULTS_DIR = os.environ.get("RESULTS_DIR", "/tmp/verifier_results") + + +def screenshot_assert(test_name, description, results_dir): + 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) + + +# ── RECIPES (verbatim from recon.md ## RECIPES) ─────────────────────────────── +def web_els(ax): + """All elements inside the app's web area (excludes the menu bar).""" + wa = ax.find(role="webarea", max_results=2) + if not wa: + return [] + return ax.find(max_results=1500, root_id=wa[0].id, max_depth=25) + + +def named(ax, role, name): + for e in web_els(ax): + if e.role == role and (e.name or "") == name: + return e + return None + + +def wait_for_web(ax, timeout=20.0): + """REQUIRED first line of every test: poll until the WebKit content is in the AX tree.""" + deadline = time.time() + timeout + while time.time() < deadline: + for e in web_els(ax): + if e.role == "link" and e.name == "Settings": + return True + time.sleep(0.4) + return False + + +def rb_enter_press(ax, role, name, wait=1.2): + el = named(ax, role, name) + if el is None: + return False + ax.action(el.id, "AXPress") + time.sleep(wait) + return True + + +def rb_enter_settings(ax): + """Sidebar 'Settings' link -> Settings ▸ General surface (depth 1).""" + return rb_enter_press(ax, "link", "Settings") + + +def rb_enter_settings_tab(ax, tab): + """Settings sub-nav link: 'General' | 'Accounts' | 'Goals' | 'Appearance' (depth 1).""" + return rb_enter_press(ax, "link", tab, wait=1.6) + + +def rb_reach_accounts(ax): + rb_enter_settings(ax) + return rb_enter_settings_tab(ax, "Accounts") + + +def rb_reach_add_account_dialog(ax): + """Settings ▸ Accounts ▸ 'Add account' -> the Add Account modal (depth 2).""" + rb_reach_accounts(ax) + return rb_enter_press(ax, "button", "Add account", wait=1.4) + + +def rb_enter_currency_popover(ax): + """AXPress the 'Currency' combobox -> the currency search popover.""" + return rb_enter_press(ax, "combobox", "Currency", wait=1.4) + + +def rb_back_escape(n=1): + for _ in range(n): + helpers.send_key(helpers.KC_ESCAPE) + time.sleep(0.7) + + +def currency_search_field(ax): + for e in web_els(ax): + if e.role == "combobox" and not (e.name or ""): + return e + return None + + +def currency_options(ax): + return [e.name for e in web_els(ax) + if e.role == "label" and e.name and "AXPress" in e.actions] + + +def filter_currency(ax, query): + sf = currency_search_field(ax) + if sf is None: + return [] + ax.set_value(sf.id, query) + time.sleep(0.9) + return currency_options(ax) + + +def combobox_values(ax): + return {e.name: str(e.value or "").strip() + for e in web_els(ax) if e.role == "combobox" and (e.name or "")} + + +def set_field(ax, name, text): + """WebKit routes an AXValue write to whatever holds DOM focus — focus first, then write.""" + el = named(ax, "text_field", name) + if el is None: + return None + try: + import ApplicationServices as AS + AS.AXUIElementSetAttributeValue(ax._get_ref(el.id), "AXFocused", True) + time.sleep(0.4) + except Exception: + pass + el = named(ax, "text_field", name) + ax.set_value(el.id, text) + time.sleep(0.8) + el = named(ax, "text_field", name) + return str(el.value or "") if el is not None else None + + +class TestWorkflowOnboardingGate: + @pytest.mark.rb(depth=1, jump_kind="reach", + expect="Settings ▸ Appearance is gated: the Welcome surface returns and " + "the 'Appearance' sub-nav link disappears") + def test_appearance_subnav_is_gated_back_to_welcome(self, ax): + assert wait_for_web(ax) + assert rb_enter_settings(ax), "sidebar 'Settings' link not found" + assert named(ax, "link", "Appearance") is not None, \ + "settings sub-nav has no 'Appearance' link" + before = kit.rb_showing(ax) + assert rb_enter_settings_tab(ax, "Appearance"), "'Appearance' link not pressable" + after = kit.rb_showing(ax) + reached = kit.rb_reach(before, after, + target="Welcome to Wealthfolio", source="Appearance") + screenshot_assert( + "workflow_appearance_gate", + "The onboarding/Welcome screen is shown again after clicking Settings > " + "Appearance: circular coin illustration, the heading 'Welcome to Wealthfolio' " + "and the three numbered setup steps; no Appearance settings form is visible.", + RESULTS_DIR) + assert reached, "pressing 'Appearance' did not return to the Welcome surface" + assert named(ax, "heading", "Welcome to Wealthfolio") is not None + + +class TestWorkflowPopoverRoundTrip: + @pytest.mark.rb(depth=2, jump_kind="reach", + expect="Escape leaves the currency popover: 'Search currency...' is gone " + "and the Settings ▸ General form (Save button) is back") + def test_escape_leaves_currency_popover_back_to_general(self, ax): + assert wait_for_web(ax) + assert rb_enter_settings(ax), "sidebar 'Settings' link not found" + assert rb_enter_currency_popover(ax), "'Currency' combobox not pressable" + opened = kit.rb_showing(ax) + assert currency_search_field(ax) is not None, "the popover search field never appeared" + rb_back_escape(1) + closed = kit.rb_showing(ax) + reached = kit.rb_reach(opened, closed, + target="Select your base currency", source="Search currency") + btns = [(e.name or "") for e in web_els(ax) if e.role == "button"] + screenshot_assert( + "workflow_popover_escape_restores_general", + "Settings > General is shown again after dismissing the currency dropdown: the " + "'Currency' combobox reads a currency name, the description 'Select your base " + "currency.' is visible and the dark Save button is back; no search dropdown.", + RESULTS_DIR) + assert reached, "Escape did not return from the popover to the General form" + assert "Save" in btns, f"Save button missing after dismissing the popover: {btns}" + + +class TestWorkflowCrossSurfaceState: + @pytest.mark.rb(depth=3, jump_kind="value", + expect="Account Name 'Cross Surface' survives the nested currency popover; " + "Currency commits to 'Swiss franc (CHF)' and Account Type stays " + "'Securities'") + def test_modal_state_survives_nested_currency_popover(self, ax): + assert wait_for_web(ax) + assert rb_reach_add_account_dialog(ax), "Add Account modal did not open" + typed = set_field(ax, "Account Name", "Cross Surface") + assert typed == "Cross Surface", f"pre-condition: Account Name not written ({typed!r})" + assert rb_enter_currency_popover(ax), "modal 'Currency' combobox not pressable" + opts = filter_currency(ax, "CHF") + assert opts == ["Swiss franc (CHF)"], f"filter 'CHF' gave {opts!r}" + opt = named(ax, "label", "Swiss franc (CHF)") + assert opt is not None, "option row 'Swiss franc (CHF)' not found" + ax.action(opt.id, "AXPress") + time.sleep(0.8) + rb_back_escape(1) # leave the popover, stay in the modal + cbs = combobox_values(ax) + name_after = named(ax, "text_field", "Account Name") + name_after = str(name_after.value or "") if name_after is not None else None + screenshot_assert( + "workflow_modal_state_after_currency_pick", + "The Add Account modal after picking a currency: Account Name still reads " + "'Cross Surface', Account Type still reads 'Securities' and the Currency field " + "now reads 'Swiss franc (CHF)'; the two toggle switches are unchanged.", + RESULTS_DIR) + rb_back_escape(2) + assert kit.rb_value(cbs.get("Currency"), "Swiss franc (CHF)"), \ + f"Currency should have committed to 'Swiss franc (CHF)', got {cbs!r}" + assert kit.rb_value(cbs.get("Account Type"), "Securities"), \ + f"Account Type should still be 'Securities', got {cbs!r}" + assert kit.rb_value(name_after, "Cross Surface"), \ + f"Account Name should survive the popover round trip, got {name_after!r}" diff --git a/macos/wealthfolio-wealthfolio/tests/testcase_counts.json b/macos/wealthfolio-wealthfolio/tests/testcase_counts.json new file mode 100644 index 0000000000000000000000000000000000000000..f4c21dcd95d369a2c9cdc43845c59c02d2b12610 --- /dev/null +++ b/macos/wealthfolio-wealthfolio/tests/testcase_counts.json @@ -0,0 +1,61 @@ +{ + "ax_total": 123, + "vlm_total": 36, + "ax_by_lane": { + "test_ax_buttons.py": 18, + "test_ax_computation.py": 20, + "test_ax_menus.py": 20, + "test_ax_states.py": 21, + "test_ax_structure.py": 19, + "test_ax_text.py": 22, + "test_ax_workflow.py": 3 + }, + "vlm_by_dir": { + "buttons": 5, + "computation": 5, + "menus": 5, + "states": 4, + "structure": 8, + "text": 6, + "workflow": 3 + }, + "vlm_names": [ + "buttons_accounts_empty_after_close.png", + "buttons_add_account_modal.png", + "buttons_home_onboarding_gate.png", + "buttons_settings_general_save.png", + "buttons_sidebar_expanded.png", + "computation_test_account_type_list.png", + "computation_test_filter_jpy.png", + "computation_test_filter_no_match.png", + "computation_test_modal_currency_commit.png", + "computation_test_unfiltered_currency_list.png", + "menus_about_panel.png", + "menus_edit_menu_open.png", + "menus_help_menu_open.png", + "menus_report_issue_alert.png", + "menus_report_issue_over_accounts.png", + "states_test_default_account_on.png", + "states_test_help_menu_open.png", + "states_test_modal_switch_defaults.png", + "states_test_sidebar_expanded.png", + "structure_test_accounts_surface.png", + "structure_test_add_account_modal.png", + "structure_test_currency_popover.png", + "structure_test_home_surface.png", + "structure_test_report_issue_alert.png", + "structure_test_settings_general_surface.png", + "structure_test_sidebar_expanded.png", + "structure_test_window_identity.png", + "text_test_accounts_empty.png", + "text_test_add_account_modal.png", + "text_test_currency_popover.png", + "text_test_home_onboarding_labels.png", + "text_test_settings_general.png", + "text_test_sidebar_expanded.png", + "workflow_appearance_gate.png", + "workflow_modal_state_after_currency_pick.png", + "workflow_popover_escape_restores_general.png" + ], + "frozen_at": "stage2_finalize" +} \ No newline at end of file diff --git a/macos/wealthfolio-wealthfolio/tests/verifier_helpers.py b/macos/wealthfolio-wealthfolio/tests/verifier_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..ce369cdae8db3a7427890d1636f8f5a3201dbef1 --- /dev/null +++ b/macos/wealthfolio-wealthfolio/tests/verifier_helpers.py @@ -0,0 +1,753 @@ +""" +verifier_helpers.py — High-level AX testing patterns for macOS app verification. + +v6 core library. Encodes all robust testing patterns as reusable functions +so verifier agents call high-level APIs instead of building from scratch. + +Depends on: ax_helpers.py (AXHelper class) +""" + +import datetime +import os +import re +import signal +import subprocess +import time +from collections import Counter + +# --------------------------------------------------------------------------- +# Key codes (macOS virtual key codes) +# --------------------------------------------------------------------------- +KC_LEFT_ARROW = 123 +KC_RIGHT_ARROW = 124 +KC_UP_ARROW = 126 +KC_DOWN_ARROW = 125 +KC_SPACE = 49 +KC_RETURN = 36 +KC_TAB = 48 +KC_ESCAPE = 53 +KC_Q = 12 +KC_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": , "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)" + ) diff --git a/macos/wealthfolio-wealthfolio/vlm_assertions.json b/macos/wealthfolio-wealthfolio/vlm_assertions.json new file mode 100644 index 0000000000000000000000000000000000000000..3d5bd5a42e197aafc8c305a44482bb379ec5fcce --- /dev/null +++ b/macos/wealthfolio-wealthfolio/vlm_assertions.json @@ -0,0 +1,491 @@ +{ + "schema_version": 2, + "instance_id": "macos/wealthfolio-wealthfolio", + "grading": { + "mode": "deferred", + "model": null, + "scored_separately": true + }, + "totals": { + "assertions": 36, + "with_verdict": 0, + "calibrated": 0, + "usable": null, + "scored_records": 0, + "unbacked_records": 0 + }, + "assertions": [ + { + "id": "buttons_sidebar_expanded.png", + "screenshot": "buttons_sidebar_expanded.png", + "assertion": "Wealthfolio with the sidebar EXPANDED after pressing the sidebar toggle: the left sidebar is wide and now shows the text labels Dashboard / Holdings / Activities / Settings next to their icons plus the 'Wealthfolio' brand beside the logo. The main area still shows the onboarding screen: coin/pie illustration, bold 'Welcome to Wealthfolio' heading, three numbered steps and the dark \"Let's get started\" button.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "buttons_sidebar_expanded.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "buttons_add_account_modal.png", + "screenshot": "buttons_add_account_modal.png", + "assertion": "The Add Account modal opened by the 'Add account' button: a centred white card titled 'Add Account' with the subtitle 'Add an investment account to track.', text fields Account Name and Account Group, an Account Type select showing 'Securities', a Currency select showing 'United States dollar (USD)', two toggle switches (Default Account off, Is Active on), a Cancel button and a dark '+ Add Account' button in the footer, and a small x close button at the top-right.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "buttons_add_account_modal.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "buttons_accounts_empty_after_close.png", + "screenshot": "buttons_accounts_empty_after_close.png", + "assertion": "Settings > Accounts restored after the modal's x/Close button was pressed: the 'Accounts' heading with the subtitle 'Manage your investment and saving accounts.', an 'Add account' button at the top-right, and a dashed-border empty card with a wallet icon, 'No account added!', \"You don't have any account yet. Start adding your investment accounts.\" and an 'Add an account' button. No modal is visible.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "buttons_accounts_empty_after_close.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "buttons_home_onboarding_gate.png", + "screenshot": "buttons_home_onboarding_gate.png", + "assertion": "Wealthfolio still on the onboarding screen after pressing the third step link '3 Add or import activities' (the onboarding gate blocks it): narrow dark-icon sidebar on the left, circular coin/pie illustration, bold 'Welcome to Wealthfolio' heading, the intro line about a personal financial portfolio tracker, three numbered steps 1/2/3 with arrows and the dark \"Let's get started\" button. No settings page.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "buttons_home_onboarding_gate.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "buttons_settings_general_save.png", + "screenshot": "buttons_settings_general_save.png", + "assertion": "Settings > General in Wealthfolio: the 'Settings' page title, a left column of sub-nav entries General / Accounts / Goals / Appearance with General selected, the 'General' section with the description 'Manage the general application settings and preferences.', a Currency combobox reading 'United States dollar (USD)' with the helper text 'Select your base currency.', and a dark 'Save' button (not pressed).", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "buttons_settings_general_save.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "computation_test_unfiltered_currency_list.png", + "screenshot": "computation_test_unfiltered_currency_list.png", + "assertion": "Settings > General with the currency picker popover open: a 'Search currency...' input above a long scrollable list of 156 currency rows whose first entries read United States dollar (USD), Canadian dollar (CAD), European Euro (EUR), Australian dollar (AUD). No result is filtered out.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "computation_test_unfiltered_currency_list.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "computation_test_filter_jpy.png", + "screenshot": "computation_test_filter_jpy.png", + "assertion": "The currency picker popover with 'JPY' entered in the 'Search currency...' box: exactly one result row is listed, reading 'Japanese yen (JPY)'. No other currency rows are visible.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "computation_test_filter_jpy.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "computation_test_filter_no_match.png", + "screenshot": "computation_test_filter_no_match.png", + "assertion": "The currency picker popover with 'xyzzy' entered in the search box: the panel shows the message 'No currency found.' and zero currency rows are listed.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "computation_test_filter_no_match.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "computation_test_modal_currency_commit.png", + "screenshot": "computation_test_modal_currency_commit.png", + "assertion": "The centred 'Add Account' modal after picking Swiss franc in the currency picker: the Currency field reads 'Swiss franc (CHF)' while Account Type still reads 'Securities'; Account Name and Account Group are empty, Default Account is off and Is Active is on, with Cancel / + Add Account buttons at the bottom.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "computation_test_modal_currency_commit.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "computation_test_account_type_list.png", + "screenshot": "computation_test_account_type_list.png", + "assertion": "The 'Add Account' modal with the Account Type dropdown expanded, showing exactly three options in order: Securities, Cash, Crypto (Securities is the current value).", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "computation_test_account_type_list.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "menus_help_menu_open.png", + "screenshot": "menus_help_menu_open.png", + "assertion": "The Wealthfolio app's Help menu is pulled down in the macOS menu bar showing the system search row and a 'Report Issue' item; the 'Welcome to Wealthfolio' onboarding window is behind it", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "menus_help_menu_open.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "menus_edit_menu_open.png", + "screenshot": "menus_edit_menu_open.png", + "assertion": "The Edit menu is pulled down in the macOS menu bar showing Undo, Redo, a separator, Cut, Copy, Paste, Select All, a separator, AutoFill with a submenu arrow, Start Dictation… and Emoji & Symbols", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "menus_edit_menu_open.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "menus_report_issue_alert.png", + "screenshot": "menus_report_issue_alert.png", + "assertion": "A native macOS alert sheet in front of the Wealthfolio window showing the app icon, the bold title 'Contact Support', the message 'If you encounter any issues, please email us at wealthfolio@teymz.com' and a single default OK button", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "menus_report_issue_alert.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "menus_about_panel.png", + "screenshot": "menus_about_panel.png", + "assertion": "A small native macOS About window in front of the Wealthfolio app showing the Wealthfolio app icon, the app name 'Wealthfolio' and a 'Version …' line", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "menus_about_panel.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "menus_report_issue_over_accounts.png", + "screenshot": "menus_report_issue_over_accounts.png", + "assertion": "The Wealthfolio Settings ▸ Accounts page ('Accounts' heading, an 'Add account' button and the dashed empty-state card 'No account added!') with a native macOS 'Contact Support' alert about emailing wealthfolio@teymz.com on top of it", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "menus_report_issue_over_accounts.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "states_test_modal_switch_defaults.png", + "screenshot": "states_test_modal_switch_defaults.png", + "assertion": "The Add Account modal is open, centred over the Accounts page, titled 'Add Account'. Its two toggle switches are in their DEFAULT positions: 'Default Account' is OFF (grey/unfilled track, knob on the left) and 'Is Active' is ON (filled/dark track, knob on the right) — one off switch and one on switch side by side. Above them the Account Type reads 'Securities' and Currency reads 'United States dollar (USD)'; Cancel and '+ Add Account' buttons sit at the bottom with a ✕ at the top-right.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "states_test_modal_switch_defaults.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "states_test_help_menu_open.png", + "screenshot": "states_test_help_menu_open.png", + "assertion": "The 'Help' menu in the macOS menu bar is OPEN: its title is highlighted (selected) and a small dropdown is shown below it containing the system search row and a 'Report Issue' item. The Wealthfolio window with the 'Welcome to Wealthfolio' onboarding page is still visible behind the menu.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "states_test_help_menu_open.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "states_test_sidebar_expanded.png", + "screenshot": "states_test_sidebar_expanded.png", + "assertion": "The left sidebar is EXPANDED: it has widened from icon-only to show the text labels Dashboard / Holdings / Activities / Settings beside their icons, plus the 'Wealthfolio' brand name next to the logo at the top; the toggle button now reads 'Collapse Sidebar'. The 'Welcome to Wealthfolio' onboarding page with its coin illustration and three numbered steps is still shown to the right.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "states_test_sidebar_expanded.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "states_test_default_account_on.png", + "screenshot": "states_test_default_account_on.png", + "assertion": "The Add Account modal is open over the Accounts page. Its 'Default Account' toggle switch is now ON (filled/dark track with the knob moved to the right) after one press, while the 'Is Active' switch below it is also ON. Fields above read Account Type 'Securities' and Currency 'United States dollar (USD)'.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "states_test_default_account_on.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "structure_test_window_identity.png", + "screenshot": "structure_test_window_identity.png", + "assertion": "A single standard macOS window titled 'Wealthfolio' (~1366x960) with the three traffic-light buttons (close/minimize/full-screen) at its top-left: a narrow dark icon-only sidebar down the left edge, and the onboarding page filling the rest with a circular coin/pie illustration and the heading 'Welcome to Wealthfolio'.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "structure_test_window_identity.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "structure_test_home_surface.png", + "screenshot": "structure_test_home_surface.png", + "assertion": "Onboarding/home surface: narrow dark icon-only sidebar on the left; a circular coin/pie illustration; the bold heading 'Welcome to Wealthfolio' with the subtitle about a personal financial portfolio tracker; three numbered steps 1/2/3 (set your main currency, add your accounts, add or import activities) each with an arrow; and a dark \"Let's get started\" button at the bottom.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "structure_test_home_surface.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "structure_test_currency_popover.png", + "screenshot": "structure_test_currency_popover.png", + "assertion": "The Settings▸General page is covered by a dropdown panel: a 'Search currency...' input at the top above a long scrollable list of currency rows (United States dollar (USD), Canadian dollar (CAD), European Euro (EUR), Australian dollar (AUD), …). The Save button is no longer reachable behind the panel.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "structure_test_currency_popover.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "structure_test_add_account_modal.png", + "screenshot": "structure_test_add_account_modal.png", + "assertion": "A centred modal card titled 'Add Account' with the fields Account Name, Account Group, Account Type (Securities) and Currency (United States dollar (USD)), two toggle switches (Default Account off, Is Active on), Cancel and '+ Add Account' buttons and a small x at the top-right. The sidebar and the accounts page behind it are dimmed.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "structure_test_add_account_modal.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "structure_test_sidebar_expanded.png", + "screenshot": "structure_test_sidebar_expanded.png", + "assertion": "The left sidebar is widened: the text labels Dashboard, Holdings, Activities and Settings are now visible next to their icons, plus the 'Wealthfolio' brand name next to the logo at the top. The onboarding content is pushed to the right.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "structure_test_sidebar_expanded.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "structure_test_settings_general_surface.png", + "screenshot": "structure_test_settings_general_surface.png", + "assertion": "Settings▸General: a 'Settings' page title, a left column of sub-nav entries General / Accounts / Goals / Appearance with General highlighted, and a 'General' section reading 'Manage the general application settings and preferences.' with a Currency combobox showing 'United States dollar (USD)' and a dark Save button.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "structure_test_settings_general_surface.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "structure_test_report_issue_alert.png", + "screenshot": "structure_test_report_issue_alert.png", + "assertion": "A native macOS alert window floats above the Wealthfolio window: the app icon, the bold line 'Contact Support', a message about emailing wealthfolio@teymz.com, and a single OK button.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "structure_test_report_issue_alert.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "structure_test_accounts_surface.png", + "screenshot": "structure_test_accounts_surface.png", + "assertion": "Settings▸Accounts: an 'Accounts' heading with the subtitle 'Manage your investment and saving accounts.', an 'Add account' button at the top-right, and a dashed-border empty card with a wallet icon reading 'No account added!' / \"You don't have any account yet…\" plus an 'Add an account' button.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "structure_test_accounts_surface.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "text_test_home_onboarding_labels.png", + "screenshot": "text_test_home_onboarding_labels.png", + "assertion": "Wealthfolio onboarding/home screen: a narrow dark-icon sidebar on the left, a circular coin/pie illustration, the bold heading 'Welcome to Wealthfolio', the sub-text \"Your personal financial portfolio tracker, right on your computer. Here's how to get started:\", three numbered steps 1 'Set your main currency', 2 'Add your accounts', 3 'Add or import activities' with arrows, and a dark \"Let's get started\" button. The window title bar reads 'Wealthfolio'.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "text_test_home_onboarding_labels.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "text_test_settings_general.png", + "screenshot": "text_test_settings_general.png", + "assertion": "Wealthfolio Settings page: 'Settings' title with a left column listing General / Accounts / Goals / Appearance, and the 'General' section reading 'Manage the general application settings and preferences.' above a 'Currency' field whose combobox shows 'United States dollar (USD)', the hint 'Select your base currency.' and a dark Save button.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "text_test_settings_general.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "text_test_accounts_empty.png", + "screenshot": "text_test_accounts_empty.png", + "assertion": "Wealthfolio Settings ▸ Accounts (empty): an 'Accounts' heading with the sub-text 'Manage your investment and saving accounts.' and an 'Add account' button top-right, over a dashed-border empty card with a wallet icon reading 'No account added!' and \"You don't have any account yet. Start adding your investment accounts.\" plus an 'Add an account' button.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "text_test_accounts_empty.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "text_test_add_account_modal.png", + "screenshot": "text_test_add_account_modal.png", + "assertion": "Wealthfolio 'Add Account' modal: a centred card titled 'Add Account' with the sub-text 'Add an investment account to track.', fields Account Name (placeholder 'Account display name'), Account Group (placeholder 'Retirement, 401K, RRSP, TFSA,...'), Account Type showing 'Securities' and Currency showing 'United States dollar (USD)', two toggle switches labelled 'Default Account' (off) and 'Is Active' (on), Cancel / '+ Add Account' buttons and a ✕ at the top-right.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "text_test_add_account_modal.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "text_test_currency_popover.png", + "screenshot": "text_test_currency_popover.png", + "assertion": "Wealthfolio currency picker popover open over the Settings ▸ General page: a dropdown panel whose top input reads the placeholder 'Search currency...' above a long scrollable list of currency rows (United States dollar (USD), Canadian dollar (CAD), European Euro (EUR), Australian dollar (AUD), ...).", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "text_test_currency_popover.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "text_test_sidebar_expanded.png", + "screenshot": "text_test_sidebar_expanded.png", + "assertion": "Wealthfolio home screen with the sidebar EXPANDED: the sidebar has widened and now shows the text labels Dashboard / Holdings / Activities / Settings next to their icons plus the 'Wealthfolio' brand next to the logo; the toggle button is now 'Collapse Sidebar'. The main area still shows 'Welcome to Wealthfolio'.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "text_test_sidebar_expanded.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "workflow_appearance_gate.png", + "screenshot": "workflow_appearance_gate.png", + "assertion": "The onboarding/Welcome screen is shown again after clicking Settings > Appearance: circular coin illustration, the heading 'Welcome to Wealthfolio' and the three numbered setup steps; no Appearance settings form is visible.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "workflow_appearance_gate.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "workflow_popover_escape_restores_general.png", + "screenshot": "workflow_popover_escape_restores_general.png", + "assertion": "Settings > General is shown again after dismissing the currency dropdown: the 'Currency' combobox reads a currency name, the description 'Select your base currency.' is visible and the dark Save button is back; no search dropdown.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "workflow_popover_escape_restores_general.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "workflow_modal_state_after_currency_pick.png", + "screenshot": "workflow_modal_state_after_currency_pick.png", + "assertion": "The Add Account modal after picking a currency: Account Name still reads 'Cross Surface', Account Type still reads 'Securities' and the Currency field now reads 'Swiss franc (CHF)'; the two toggle switches are unchanged.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "workflow_modal_state_after_currency_pick.png", + "rigor": null, + "verdict": null, + "calibration": null + } + ], + "merged_from_files": 7, + "source_shapes": { + "dict_str": 36 + } +} \ No newline at end of file diff --git a/macos/ygsgdbd-typeswitch/LICENSE b/macos/ygsgdbd-typeswitch/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..04ff5cf4facb26846d385483a6fc4ef05bf4b3d2 --- /dev/null +++ b/macos/ygsgdbd-typeswitch/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 TypeSwitch Contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, 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 THE +SOFTWARE. diff --git a/macos/ygsgdbd-typeswitch/instance.json b/macos/ygsgdbd-typeswitch/instance.json new file mode 100644 index 0000000000000000000000000000000000000000..314ad9e4d065a453f35b95e20e9f39763e4542b1 --- /dev/null +++ b/macos/ygsgdbd-typeswitch/instance.json @@ -0,0 +1,10 @@ +{ + "schema_version": 1, + "instance_id": "macos/ygsgdbd-typeswitch", + "platform": "macos", + "repo": "https://github.com/ygsgdbd/TypeSwitch", + "commit": "b81c1673ebe47a0caf934506143d06d1b4285498", + "patches": [], + "package": null, + "license": null +} \ No newline at end of file diff --git a/macos/ygsgdbd-typeswitch/reference/build.sh b/macos/ygsgdbd-typeswitch/reference/build.sh new file mode 100644 index 0000000000000000000000000000000000000000..889b1627e28dd01c14d9ce1672f18daf4aa88a83 --- /dev/null +++ b/macos/ygsgdbd-typeswitch/reference/build.sh @@ -0,0 +1,153 @@ +#!/usr/bin/env bash +# +# build.sh — Reproducible build for TypeSwitch (macOS menu-bar app) +# +# TypeSwitch is a Tuist-managed SwiftUI app. Tuist generates the Xcode +# workspace/project from Project.swift, then xcodebuild builds the .app. +# +# This machine runs Xcode 15.4 / Swift 5.10. The upstream pins several SPM +# dependencies at versions whose Package.swift declares Swift tools 5.11/6.0, +# which Swift 5.10 refuses to resolve. We pin those deps down to the newest +# releases that declare tools <= 5.10 (API-compatible with the source): +# Defaults 9.0.0 -> 8.2.0 (tools 5.9, no macros/swift-syntax) +# SwifterSwift 7.0.0 -> 6.2.0 (tools 5.8, not even imported) +# KeyboardShortcuts 2.2.2 -> 2.0.2 (tools 5.10) +# SwiftUIX / swift-log are pinned to their already-resolved versions. +# +# Everything needed lives in this script: dependency installs are idempotent, +# the only source change (Project.swift) is applied as an inline git patch. +# +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd "$SCRIPT_DIR" + +TUIST_VERSION="4.36.0" # pinned by .mise.toml +SCHEME="TypeSwitch" +CONFIGURATION="Release" +DERIVED_DATA="$SCRIPT_DIR/DerivedData" +WORKSPACE="$SCRIPT_DIR/TypeSwitch.xcworkspace" +OUTPUT_DIR="${APP_OUTPUT_DIR:-$SCRIPT_DIR}" + +echo "==> TypeSwitch build starting in: $SCRIPT_DIR" + +# --------------------------------------------------------------------------- +# 1. Locate Homebrew and load its environment +# --------------------------------------------------------------------------- +if command -v brew >/dev/null 2>&1; then + BREW="$(command -v brew)" +elif [ -x /opt/homebrew/bin/brew ]; then + BREW="/opt/homebrew/bin/brew" +elif [ -x /usr/local/bin/brew ]; then + BREW="/usr/local/bin/brew" +else + echo "ERROR: Homebrew is required but was not found." >&2 + exit 1 +fi +eval "$("$BREW" shellenv)" + +# --------------------------------------------------------------------------- +# 2. Install mise (runtime manager) + the pinned Tuist version (idempotent) +# --------------------------------------------------------------------------- +if ! "$BREW" list mise >/dev/null 2>&1; then + echo "==> Installing mise via Homebrew" + "$BREW" install mise +else + echo "==> mise already installed" +fi + +export MISE_YES=1 +# Trust the project's .mise.toml so mise runs non-interactively. +mise trust "$SCRIPT_DIR/.mise.toml" >/dev/null 2>&1 || true +mise trust "$SCRIPT_DIR" >/dev/null 2>&1 || true + +echo "==> Installing Tuist $TUIST_VERSION via mise (per .mise.toml)" +mise install +echo "==> Tuist version: $(mise exec -- tuist version 2>/dev/null || echo unknown)" + +# --------------------------------------------------------------------------- +# 3. Clean previous generation / build artifacts (idempotent, all local) +# --------------------------------------------------------------------------- +echo "==> Cleaning previous artifacts" +rm -rf "$WORKSPACE" "$SCRIPT_DIR/TypeSwitch.xcodeproj" "$DERIVED_DATA" +# The committed root .package.resolved pins the old (incompatible) versions; +# remove it so nothing can seed a stale resolution. +rm -f "$SCRIPT_DIR/.package.resolved" + +# --------------------------------------------------------------------------- +# 4. Apply the only source change: pin SPM deps + fill the build-number +# placeholder in Project.swift. Expressed as an inline git patch so it +# survives a fresh clone. Reset first to stay idempotent across re-runs. +# --------------------------------------------------------------------------- +echo "==> Patching Project.swift (dependency version pins + build number)" +git checkout -- Project.swift 2>/dev/null || true +git apply <<'PATCH' +diff --git a/Project.swift b/Project.swift +index b375fe1..70e7890 100644 +--- a/Project.swift ++++ b/Project.swift +@@ -2,7 +2,7 @@ import ProjectDescription + + // MARK: - Version + let appVersion = "0.3.5" // 应用版本号 +-let buildVersion = "@BUILD_NUMBER@" // 构建版本号占位符,会被 GitHub Actions 替换 ++let buildVersion = "1" // 构建版本号占位符,会被 GitHub Actions 替换 + + let project = Project( + name: "TypeSwitch", +@@ -11,11 +11,11 @@ let project = Project( + developmentRegion: "zh-Hans" + ), + packages: [ +- .remote(url: "https://github.com/sindresorhus/Defaults", requirement: .upToNextMajor(from: "9.0.0")), +- .remote(url: "https://github.com/SwiftUIX/SwiftUIX", requirement: .upToNextMajor(from: "0.1.9")), +- .remote(url: "https://github.com/SwifterSwift/SwifterSwift", requirement: .upToNextMajor(from: "7.0.0")), +- .remote(url: "https://github.com/sindresorhus/KeyboardShortcuts", requirement: .upToNextMajor(from: "2.2.2")), +- .remote(url: "https://github.com/apple/swift-log.git", requirement: .upToNextMajor(from: "1.5.3")) ++ .remote(url: "https://github.com/sindresorhus/Defaults", requirement: .exact("8.2.0")), ++ .remote(url: "https://github.com/SwiftUIX/SwiftUIX", requirement: .exact("0.2.3")), ++ .remote(url: "https://github.com/SwifterSwift/SwifterSwift", requirement: .exact("6.2.0")), ++ .remote(url: "https://github.com/sindresorhus/KeyboardShortcuts", requirement: .exact("2.0.2")), ++ .remote(url: "https://github.com/apple/swift-log.git", requirement: .exact("1.6.2")) + ], + settings: .settings( + base: [ +PATCH + +# --------------------------------------------------------------------------- +# 5. Generate the Xcode workspace/project with Tuist +# --------------------------------------------------------------------------- +echo "==> Generating Xcode project with Tuist" +mise exec -- tuist generate --no-open + +# --------------------------------------------------------------------------- +# 6. Build the app (code signing disabled). A local -derivedDataPath and +# -clonedSourcePackagesDirPath keep SPM resolution isolated & reproducible. +# --------------------------------------------------------------------------- +echo "==> Building $SCHEME ($CONFIGURATION)" +xcodebuild \ + -workspace "$WORKSPACE" \ + -scheme "$SCHEME" \ + -configuration "$CONFIGURATION" \ + -derivedDataPath "$DERIVED_DATA" \ + -clonedSourcePackagesDirPath "$DERIVED_DATA/SourcePackages" \ + -quiet \ + clean build \ + CODE_SIGN_IDENTITY="" CODE_SIGNING_ALLOWED=NO CODE_SIGNING_REQUIRED=NO + +# --------------------------------------------------------------------------- +# 7. Copy the built .app to the output directory +# --------------------------------------------------------------------------- +APP_SRC="$DERIVED_DATA/Build/Products/$CONFIGURATION/TypeSwitch.app" +if [ ! -d "$APP_SRC" ]; then + echo "ERROR: expected app not found at $APP_SRC" >&2 + exit 1 +fi + +mkdir -p "$OUTPUT_DIR" +rm -rf "$OUTPUT_DIR/TypeSwitch.app" +cp -R "$APP_SRC" "$OUTPUT_DIR/" + +echo "" +echo "==> BUILD SUCCEEDED" +echo "==> App bundle: $OUTPUT_DIR/TypeSwitch.app" diff --git a/macos/ygsgdbd-typeswitch/reference/launch.sh b/macos/ygsgdbd-typeswitch/reference/launch.sh new file mode 100644 index 0000000000000000000000000000000000000000..27213223030fe364c8dd1043e1a6e1c13fb266c8 --- /dev/null +++ b/macos/ygsgdbd-typeswitch/reference/launch.sh @@ -0,0 +1,40 @@ +#!/usr/bin/env bash +# +# launch.sh — Start the TypeSwitch app. +# +# TypeSwitch is a macOS menu-bar utility (LSUIElement = true): it has no +# main window and no Dock icon — once launched it lives in the menu bar. +# It is a self-contained .app bundle (Swift stdlib + all SPM dependencies +# are bundled/statically linked), so no DYLD_* / plugin env vars are needed. +# +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" + +# Locate the built .app, checking the output dir, the script dir, and the +# in-tree build products location. +CANDIDATES=( + "${APP_OUTPUT_DIR:-}/TypeSwitch.app" + "$SCRIPT_DIR/TypeSwitch.app" + "$SCRIPT_DIR/DerivedData/Build/Products/Release/TypeSwitch.app" +) + +APP_PATH="" +for c in "${CANDIDATES[@]}"; do + [ -n "$c" ] || continue + if [ -d "$c" ]; then + APP_PATH="$c" + break + fi +done + +if [ -z "$APP_PATH" ]; then + echo "ERROR: TypeSwitch.app not found. Run build.sh first." >&2 + exit 1 +fi + +echo "==> Launching: $APP_PATH" + +# Launch the bundle and wait until it exits (it will keep running in the menu +# bar until quit or terminated). Any extra args are forwarded to the app. +open -W "$APP_PATH" --args "$@" diff --git a/macos/ygsgdbd-typeswitch/tests/ax_helpers.py b/macos/ygsgdbd-typeswitch/tests/ax_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..2418d7b8c75891c2d08906848d6a36517cb98135 --- /dev/null +++ b/macos/ygsgdbd-typeswitch/tests/ax_helpers.py @@ -0,0 +1,849 @@ +import os +import re +import time +import warnings +import subprocess +from dataclasses import dataclass, field +from typing import Optional +from 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", +} + + +@dataclass +class 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 None diff --git a/macos/ygsgdbd-typeswitch/tests/conftest.py b/macos/ygsgdbd-typeswitch/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..21a9b7debd04c0633d77a60d8269102790a13e84 --- /dev/null +++ b/macos/ygsgdbd-typeswitch/tests/conftest.py @@ -0,0 +1,584 @@ +""" +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 json +import os +import signal +import subprocess +import tempfile +import 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 _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 ` whose ARGUMENT merely contains the bundle path. + + A running .app's argv0 is /Contents/MacOS/, so we require that inner + executable path. The old bare-substring test (`app_path in args`) also matched the + lingering `open -W ` 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 == /Contents/MacOS/. + 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 ` 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//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//... — 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.fixture +def app_process(app_path): + pid = _launch_app(app_path) + yield pid + _kill_pid(pid) + + +@pytest.fixture +def 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.fixture +def 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")) diff --git a/macos/ygsgdbd-typeswitch/tests/rb_testgen_kit.py b/macos/ygsgdbd-typeswitch/tests/rb_testgen_kit.py new file mode 100644 index 0000000000000000000000000000000000000000..ccbbdd3c6136513161c133fbb4cefcfb0386d55c --- /dev/null +++ b/macos/ygsgdbd-typeswitch/tests/rb_testgen_kit.py @@ -0,0 +1,575 @@ +#!/usr/bin/env python3 +"""RB TestGen Kit (macOS/AX port of the Linux v7.5 kit) — a test's NAVIGATION +DEPTH and JUMP RIGOR are DECLARED (not inferred), uniformly recorded, and +self-auditable. + +DIFFERENCE FROM LINUX: macOS tests are **pytest** (methods on Test* classes taking +the `ax` fixture, plain asserts) — NOT standalone scripts calling R.record(). So the +DECLARATION is a pytest marker on the test method: + + import rb_testgen_kit as kit + + @pytest.mark.rb(depth=1, jump_kind="reach", expect="Preferences window visible") + def test_prefs_opens(self, ax_with_reset): + before = kit.rb_showing(ax_with_reset) + helpers.rb_reach_prefs(ax_with_reset) # a nav helper you name rb_reach_* / rb_enter_* + after = kit.rb_showing(ax_with_reset) + assert kit.rb_reach(before, after, target="Preferences", source="menu bar") + +conftest.py's pytest_runtest_makereport hook reads the marker + the test outcome and +writes {name, passed, depth, jump_kind, tier, expect} so the runner can fold it into +_results.json. The audits below then read those records (+ the test SOURCE). + +jump_kind (verbatim strings — the audit/stats key off them): + "none" no trigger; existence/structure only -> tier 0 + "liveness" only "did not crash / still alive" -> tier 1 (weak; avoid) + "reach" a real surface jump: the TARGET surface's element + APPEARED and the SOURCE surface's element DISAPPEARED -> tier 2 + "transition" a state flip (CHECKED/ENABLED/mode) before->after -> tier 2 + "value" a specific expected value/content was asserted -> tier 3 + +DEPTH is the number of surfaces crossed before the assertion (0 = home/first screen, +1 = one dialog/panel/submenu, 2+ = deeper). A flat-tree read of a deep element is +depth 0 — depth counts surfaces the test actually navigated through. + +REACH PROOF (so "reach" cannot be faked by reading a flat tree): + before = rb_showing(ax) + + 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('')" + python3 -c "import rb_testgen_kit as k; k.rb_lint('')" + python3 -c "import rb_testgen_kit as k; k.rb_lint_sources('')" + python3 -c "import rb_testgen_kit as k; k.rb_audit_depth('','')" +""" +from __future__ import annotations + +import ast +import glob +import json +import os +import re + +JUMP_KINDS = {"none": 0, "liveness": 1, "reach": 2, "transition": 2, "value": 3} + +# Double-axis quota TARGETS (fractions) — goals rb_audit REPORTS, NOT a hard gate. +QUOTAS = { + "existence_max": 0.30, # jump_kind=="none" share of ALL tests + "interactive_min": 0.60, # reach|transition|value share of ALL tests + "depth_ge1_min": 0.40, # depth>=1 share of INTERACTIVE tests + "depth_ge2_min": 0.10, # depth>=2 share of INTERACTIVE tests + "value_min": 0.25, # jump_kind=="value" share of INTERACTIVE tests +} + +# Depth family: a test "crosses a surface" iff it calls a member of the depth family. +# macOS accepts BOTH the naming convention rb_enter_*/rb_reach_* (write your own nav +# helper and NAME it so) AND the existing verifier_helpers/ax_helpers navigation +# functions (whitelist below) — so tests can reuse the mature reveal/navigate helpers. +DEPTH_FWD_RE = re.compile(r"^rb_(enter|reach)[a-z0-9_]*$") +DEPTH_BACK_RE = re.compile(r"^rb_back[a-z0-9_]*$") +# verifier_helpers / ax_helpers navigation functions that OPEN or move to a new surface. +FWD_WHITELIST = { + "ensure_ui_visible", "ensure_panel_open", "open_actions_menu", "open_menu", + "open_settings", "open_preferences", "open_dialog", "open_panel", "open_window", + "navigate_month", "navigate", "switch_tab", "switch_mode", "switch_page", + "select_tab", "reveal_window", "show_panel", "show_menu", +} +BACK_WHITELIST = { + "dismiss_menus", "dismiss_panel", "dismiss_any_dialog", "close_panel", + "close_window", "go_back", +} +# pytest fixtures that themselves navigate into a surface during setup (so a test taking +# one legitimately has depth>=1 without a nav call in its own body). `ax` does NOT navigate. +_NAV_FIXTURES = {"ax_with_reset", "open_panel"} +# MEASURED-TIER verdict families (ported from keliang): a tier2/3 jump_kind must be BACKED +# by its verdict function — transition->rb_flip*, value->rb_value*, reach->rb_reach* — whose +# bool result is the test's assertion. Self-named wrappers count by prefix. +TIER_FLIP_RE = re.compile(r"^rb_flip[a-z0-9_]*$") +TIER_VALUE_RE = re.compile(r"^rb_value[a-z0-9_]*$") +_JK_FAMILY = {"transition": "flip", "value": "value", "reach": "reach"} +# normalize plural (v73prep) / singular module names so a JSON module ("button") and a +# file stem ("buttons") join. +_MODULE_ALIAS = {"menus": "menu", "buttons": "button", "states": "state", + "structures": "structure", "texts": "text", + "computations": "computation", "workflows": "workflow"} + +_DEPTH = 0 # module-global surface counter for rb_enter/rb_back + + +def tier_of(jump_kind: str) -> int: + return JUMP_KINDS.get(jump_kind, 2) + + +def rb_reset_depth() -> None: + global _DEPTH + _DEPTH = 0 + + +def rb_enter(_surface: str = "") -> int: + """Call right after your test navigates into a new surface (dialog/panel/submenu).""" + global _DEPTH + _DEPTH += 1 + return _DEPTH + + +def rb_back() -> int: + global _DEPTH + _DEPTH = max(0, _DEPTH - 1) + return _DEPTH + + +def _walk_tree_nodes(node, out, seen): + """Yield 'role|name' for a macOS AXHelper.tree() dict node (+children).""" + if not isinstance(node, dict) or seen[0] >= 8000: + return + seen[0] += 1 + role = str(node.get("role") or "") + name = str(node.get("name") or node.get("value") or "") + if role or name: + out.add(f"{role}|{name}") + for c in (node.get("children") or []): + _walk_tree_nodes(c, out, seen) + + +def rb_showing(ax, max_depth: int = 12) -> set: + """Snapshot the currently-reachable AX subtree under the app as {"role|name"}. + macOS AX has no AT-SPI SHOWING/VISIBLE state, so we approximate "showing" by the + live AX tree (AXChildren) the app currently exposes — a new window/sheet/popover + adds its elements; a dismissed one removes them. Feed before+after a trigger to + rb_reach() so a 'reach' test proves a REAL surface change, not a flat-tree read. + Safe no-op (empty set) if `ax` cannot produce a tree.""" + out: set = set() + try: + tree = ax.tree(max_depth=max_depth) # AXHelper.tree() -> nested dict + except Exception: + return out + _walk_tree_nodes(tree, out, [0]) + return out + + +def rb_reach(before, after, target: str, source: str | None = None) -> bool: + """True-jump verdict: the TARGET surface's discriminating element newly APPEARED + AND (if given) the SOURCE surface's discriminating element DISAPPEARED. This is + what separates a real surface jump from reading an element that was always there.""" + before = set(before or []) + after = set(after or []) + t = target.lower() + appeared = any(t in k.lower() for k in (after - before)) + if source is None: + return appeared + s = source.lower() + src_before = any(s in k.lower() for k in before) + src_after = any(s in k.lower() for k in after) + return appeared and src_before and not src_after + + +def rb_flip(before, after, expect: str = "") -> bool: + """In-page STATE-FLIP verdict (tier2 `transition`): the observed state actually CHANGED + before->after (a CHECKED/ENABLED/mode/selection value read the two times). Pass its bool + as the test's assertion. Does NOT touch depth — an in-page flip is depth 0 unless you + navigated a surface to reach the control. You MAY write your own `rb_flip_()` 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_()` 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 | " + "{audit_depth|audit_tier} [results_dir]}") diff --git a/macos/ygsgdbd-typeswitch/tests/requirements.txt b/macos/ygsgdbd-typeswitch/tests/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..feef67ce2aadbaa26d12e6b01cff7b8ce89ecb5c --- /dev/null +++ b/macos/ygsgdbd-typeswitch/tests/requirements.txt @@ -0,0 +1,3 @@ +pytest +pytest-check +pyobjc diff --git a/macos/ygsgdbd-typeswitch/tests/test_ax_buttons.py b/macos/ygsgdbd-typeswitch/tests/test_ax_buttons.py new file mode 100644 index 0000000000000000000000000000000000000000..2d3e5d92aa80e982ce0f43dc947f54b380bc86a4 --- /dev/null +++ b/macos/ygsgdbd-typeswitch/tests/test_ax_buttons.py @@ -0,0 +1,737 @@ +"""AX button-interaction tests for TypeSwitch (macos-ygsgdbd-typeswitch). + +Scope of this module: the app's *press-to-act* controls, exercised behaviourally. + +TypeSwitch is an `LSUIElement` menu-bar-extra app; it exposes exactly three kinds of +pressable control (all observed in recon.md, none of them a toolbar — the app has no +tool bar at all): + + * ONE real push button: `button "Refresh (⌘R)"` → rescans the application folders + * ONE forbidden push button: `button "Quit (⌘Q)"` → identity/geometry only, NEVER pressed + * TWO toggle buttons: `checkbox` with `AXSubrole == "AXToggle"`, + `AXRoleDescription == "toggle button"` + ("Global Quick Switch", "Launch at Login") + * 26 press-to-select `radio` buttons (2 per app row: `Default` / the input method) + +Every test asserts the CONSEQUENCE of a press, never mere existence — the single +exception is the footer-identity test (B9), which must not press its buttons. + +SAFETY: `Quit (⌘Q)` is never pressed, `⌘Q` is never sent, `Quit TypeSwitch` is never +picked, no process is ever killed, and the `Record Shortcut` field is never pressed +(pressing it arms a global key grab). +""" + +# ---- paste verbatim into every test module ------------------------------------- +import os, json, re, subprocess, time +import pytest +import rb_testgen_kit as kit +import verifier_helpers as helpers + +CTRL_LABELS = { + "Global Quick Switch", + "Use shortcut to quickly switch between input methods", + "Launch at Login", + "Automatically start TypeSwitch when you log in", +} + + +def screenshot_assert(test_name, description, results_dir=None): + results_dir = results_dir or os.environ.get("RESULTS_DIR", "results") + 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 + af = os.path.join(ss_dir, "assertions.json") + data = {} + if os.path.exists(af): + try: + data = json.load(open(af)) + except Exception: + data = {} + data[f"{test_name}.png"] = description + with open(af, "w") as f: + json.dump(data, f, indent=2) + + +def _main_window(ax): + """The app's content window: a top-level window that owns a group subtree.""" + for w in ax.find(role="window", max_results=6, max_depth=2): + if ax.find(role="group", root_id=w.id, max_results=1, max_depth=3): + return w + return None + + +def _wait_window(ax, timeout=1.2): + end = time.time() + timeout + while time.time() < end: + w = _main_window(ax) + if w is not None: + return w + time.sleep(0.15) + return None + + +def rb_enter_main_window(ax, attempts=4): + """Reveal the app's main UI (surface crossing: menu bar -> window). + + Portable: an already-open window wins; otherwise press status-item / menu-bar + items (the extras bar FIRST), then CG-click, then ax.ensure_ui_visible().""" + w = _main_window(ax) + if w is not None: + return w + bars = ax.find(role="menu_bar", max_results=4, max_depth=1) + ordered = [] + for bar in reversed(bars): # extras (status-item) menu bar first + ordered += [i for i in ax.find(role="menu_bar_item", root_id=bar.id, + max_results=12) + if (i.name or "") != "Apple"] + for item in ordered: + for _ in range(attempts): + ax.action(item.id, "AXPress") + w = _wait_window(ax) + if w is not None: + return w + helpers.dismiss_menus(ax) + for item in ordered: + ax.click_element_cg(item.id) + w = _wait_window(ax) + if w is not None: + return w + helpers.dismiss_menus(ax) + ax.ensure_ui_visible() + return _main_window(ax) + + +def status_item(ax): + """The menu-bar-extra item that owns the app UI (last menu bar, first item).""" + bars = ax.find(role="menu_bar", max_results=4, max_depth=1) + for bar in reversed(bars): + items = [i for i in ax.find(role="menu_bar_item", root_id=bar.id, max_results=12) + if (i.name or "") != "Apple"] + if len(items) == 1: # a status/extras bar holds exactly one item + return items[0] + return None + + +def frame(ax, el_id): + """(x, y, w, h) floats parsed out of AXPosition / AXSize.""" + d = ax.get(el_id, ["AXPosition", "AXSize"]) + + def num(s, key): + m = re.search(key + r":(-?[\d.]+)", str(s)) + return float(m.group(1)) if m else None + + return (num(d.get("AXPosition"), "x"), num(d.get("AXPosition"), "y"), + num(d.get("AXSize"), "w"), num(d.get("AXSize"), "h")) + + +def search_field(ax, w): + """The app-list search field: the text field whose placeholder mentions search.""" + tfs = ax.find(role="text_field", root_id=w.id, max_results=8, max_depth=12) + for t in tfs: + ph = (ax.get(t.id, ["AXPlaceholderValue"]).get("AXPlaceholderValue") or "") + if "Search" in ph or "搜索" in ph: + return t + return tfs[0] if tfs else None + + +def app_names(ax, w): + """Visible app-row names = every label that is not one of the 4 control labels.""" + return [e.value for e in ax.find(role="label", root_id=w.id, + max_results=300, max_depth=12) + if e.value and e.value not in CTRL_LABELS] + + +def set_search(ax, w, query, settle=0.8): + tf = search_field(ax, w) + ax.set_value(tf.id, query) + time.sleep(settle) + return tf + + +def toggle_for(ax, w, label_text): + """The checkbox/toggle belonging to the settings row labelled `label_text` + (pairs by nearest vertical centre — robust to child ordering).""" + lab = None + for e in ax.find(role="label", root_id=w.id, max_results=300, max_depth=12): + if e.value == label_text: + lab = e + break + boxes = ax.find(role="checkbox", root_id=w.id, max_results=10, max_depth=12) + if not boxes: + return None + if lab is None: + return boxes[0] + ly = (frame(ax, lab.id)[1] or 0) + (frame(ax, lab.id)[3] or 0) / 2.0 + best, bestd = None, 1e9 + for b in boxes: + by = (frame(ax, b.id)[1] or 0) + (frame(ax, b.id)[3] or 0) / 2.0 + if abs(by - ly) < bestd: + best, bestd = b, abs(by - ly) + return best + + +def toggle_value(ax, el_id): + return ax.get(el_id, ["AXValue"]).get("AXValue") + + +def named_button(ax, w, keyword): + for b in ax.find(role="button", root_id=w.id, max_results=30, max_depth=12): + if b.name and keyword.lower() in b.name.lower(): + return b + return None +# -------------------------------------------------------------------------------- + +import shutil + +# Keycodes for the key *equivalents* recon verified as reaching this app. +KC_R = 15 # ⌘R == the Refresh button's shortcut + +REFRESH_SETTLE = 2.5 # recon: rescan is visible after 2.5 s +PROBE_DIR = os.path.expanduser("~/Applications") + +PROBE_PLIST = """ + + +CFBundleName{name} +CFBundleIdentifiercom.recreationbench.{name} +CFBundleExecutable{name} +CFBundlePackageTypeAPPL + +""" + + +def probe_path(name): + return os.path.join(PROBE_DIR, f"{name}.app") + + +def make_probe_app(name): + """Create ~/Applications/.app — one of the three folders TypeSwitch scans. + + The app must NOT know about it yet: that is what makes the Refresh press + observable (stale list -> [] , after refresh -> [name]).""" + root = probe_path(name) + macos = os.path.join(root, "Contents", "MacOS") + os.makedirs(macos, exist_ok=True) + exe = os.path.join(macos, name) + with open(exe, "w") as f: + f.write("#!/bin/sh\nexit 0\n") + os.chmod(exe, 0o755) + with open(os.path.join(root, "Contents", "Info.plist"), "w") as f: + f.write(PROBE_PLIST.format(name=name)) + return root + + +def refresh_button(ax, w): + """The footer push button whose name is `Refresh (⌘R)` (matched on 'Refresh').""" + return named_button(ax, w, "Refresh") + + +def press_refresh(ax, w, settle=REFRESH_SETTLE): + btn = refresh_button(ax, w) + assert btn is not None, ( + "expected a footer push button named 'Refresh (⌘R)' inside the panel window") + ax.action(btn.id, "AXPress") + time.sleep(settle) + return btn + + +def cleanup_probe(ax, w, name): + """Delete the probe bundle, refresh the app back to a clean list, clear search.""" + shutil.rmtree(probe_path(name), ignore_errors=True) + try: + btn = refresh_button(ax, w) + if btn is not None: + ax.action(btn.id, "AXPress") + time.sleep(1.5) + set_search(ax, w, "", settle=0.4) + except Exception: + pass # panel gone: the fixture relaunches anyway + + +def as_int(v): + """A toggle/radio `AXValue` as 0/1 (AX hands back int, bool or numeric string).""" + if v is None: + return None + if isinstance(v, bool): + return int(v) + try: + return int(float(str(v))) + except (TypeError, ValueError): + return None + + +def actions_of(ax, el): + """Advertised AX action names for an element, via whichever API the kit exposes.""" + direct = getattr(el, "actions", None) + if direct: + return [str(a) for a in direct] + for attempt in (lambda: ax.actions(el.id), + lambda: ax.get_actions(el.id), + lambda: ax.get(el.id, ["AXActions"]).get("AXActions")): + try: + vals = attempt() + except Exception: + continue + if vals: + return [str(v) for v in vals] + return [] + + +def is_enabled(ax, el_id): + return bool(ax.get(el_id, ["AXEnabled"]).get("AXEnabled")) + + +def text_field_count(ax, w): + return len(ax.find(role="text_field", root_id=w.id, max_results=8, max_depth=12)) + + +def enter_panel(ax): + w = rb_enter_main_window(ax) + assert w is not None, ( + "expected the TypeSwitch panel window (600x500, AXSubrole 'AXSystemDialog') " + "after revealing the 'Keyboard' status item — got no window at all") + return w + + +# ============================================================================= +# B1-B4 — the app's one real push button: Refresh (⌘R) +# ============================================================================= +class TestRefreshButton: + """`button "Refresh (⌘R)"` recomputes the scanned application list.""" + + @pytest.mark.rb( + depth=1, jump_kind="value", + expect="pressing 'Refresh (⌘R)' rescans ~/Applications, so the search for " + "'RBBtnProbe' turns from [] into exactly ['RBBtnProbe']") + def test_refresh_button_rescans_new_app_bundle(self, ax): + w = enter_panel(ax) + name = "RBBtnProbe" + shutil.rmtree(probe_path(name), ignore_errors=True) + try: + make_probe_app(name) + + # The running app has not rescanned yet -> its list is stale. + set_search(ax, w, name) + stale = app_names(ax, w) + assert stale == [], ( + f"expected [] app rows for query {name!r} BEFORE pressing Refresh " + f"(the freshly created bundle is not in the app's cached list yet), " + f"got {stale!r}") + + press_refresh(ax, w) + observed = app_names(ax, w) + verdict = kit.rb_value(observed, [name]) + screenshot_assert( + "buttons_refresh_button_rescan", + "The dark 600x500 TypeSwitch panel is anchored at the top-right of the " + "screen just under the menu bar. Its rounded search field at the top " + "contains 'RBBtnProbe' and, after the small bottom-right text button " + "'Refresh (⌘R)' was pressed, exactly ONE app row is visible: an app " + "icon, the name 'RBBtnProbe', and a small two-segment picker " + "(Default | U.S.) on the right. The 'Global Quick Switch' row with the " + "sub-line 'Use shortcut to quickly switch between input methods' and its " + "switch, the 'Launch at Login' row with 'Automatically start TypeSwitch " + "when you log in' and its switch, and the footer buttons " + "'Refresh (⌘R)' and 'Quit (⌘Q)' are all still visible.") + assert verdict, ( + f"expected app_names == ['{name}'] 2.5 s after pressing " + f"'Refresh (⌘R)' (the button must rescan the application folders " + f"and pick up ~/Applications/{name}.app), got {observed!r}") + finally: + cleanup_probe(ax, w, name) + + @pytest.mark.rb( + depth=1, jump_kind="value", + expect="the ⌘R key equivalent drives the same rescan as the Refresh " + "button: the search for 'RBBtnProbeKey' turns from [] into " + "exactly ['RBBtnProbeKey']") + def test_refresh_keyboard_equivalent_rescans_new_app_bundle(self, ax): + w = enter_panel(ax) + name = "RBBtnProbeKey" + shutil.rmtree(probe_path(name), ignore_errors=True) + try: + make_probe_app(name) + + set_search(ax, w, name) + stale = app_names(ax, w) + assert stale == [], ( + f"expected [] app rows for query {name!r} BEFORE sending ⌘R " + f"(the app's cached list is stale), got {stale!r}") + + helpers.send_key(KC_R, ["cmd"]) # the Refresh button's shortcut + time.sleep(REFRESH_SETTLE) + + observed = app_names(ax, w) + assert kit.rb_value(observed, [name]), ( + f"expected app_names == ['{name}'] 2.5 s after the ⌘R key " + f"equivalent (it must trigger the same rescan as the " + f"'Refresh (⌘R)' button), got {observed!r}") + finally: + cleanup_probe(ax, w, name) + + @pytest.mark.rb( + depth=1, jump_kind="transition", + expect="Refresh is idempotent for an unchanged Applications folder: the " + "same >=10 app-row names come back in the same order and the button " + "is AXEnabled again afterwards") + def test_refresh_button_is_idempotent_for_unchanged_list(self, ax): + w = enter_panel(ax) + before = app_names(ax, w) + assert len(before) >= 10, ( + f"expected at least 10 realized app-row names in the panel before " + f"refreshing (recon observed 13, e.g. 'Activity Monitor' ... 'Clock'), " + f"got {len(before)}: {before!r}") + + press_refresh(ax, w) + after = app_names(ax, w) + + assert before == after, ( + f"expected the app-row list to be UNCHANGED by a Refresh press when no " + f"bundle was added or removed: expected {before!r}, got {after!r}") + assert not kit.rb_flip(before, after), ( + f"expected NO state flip across an idempotent Refresh press " + f"(kit.rb_flip must be False for identical lists), before={before!r} " + f"after={after!r}") + + btn = refresh_button(ax, w) + assert btn is not None, ( + "expected the 'Refresh (⌘R)' button to still exist after refreshing") + assert is_enabled(ax, btn.id), ( + "expected button 'Refresh (⌘R)' AXEnabled == True again after the " + "rescan completed (the transient disabled/progress state is not " + "observable), got AXEnabled == False") + + @pytest.mark.rb( + depth=1, jump_kind="value", + expect="Refresh preserves the active search filter: with 'Calc' typed the " + "list is still exactly ['Calculator'] after the press") + def test_refresh_button_preserves_active_filter(self, ax): + w = enter_panel(ax) + try: + set_search(ax, w, "Calc") + filtered = app_names(ax, w) + assert filtered == ["Calculator"], ( + f"expected app_names == ['Calculator'] for the query 'Calc' before " + f"refreshing, got {filtered!r}") + + press_refresh(ax, w) + + observed = app_names(ax, w) + assert kit.rb_value(observed, ["Calculator"]), ( + f"expected app_names == ['Calculator'] after pressing " + f"'Refresh (⌘R)' — the rescan must NOT clear or widen the active " + f"'Calc' filter, got {observed!r}") + + query = (ax.get(search_field(ax, w).id, ["AXValue"]).get("AXValue") or "") + assert query == "Calc", ( + f"expected the search field to still hold exactly 'Calc' after the " + f"Refresh press, got {query!r}") + finally: + try: + set_search(ax, w, "", settle=0.4) + except Exception: + pass + + +# ============================================================================= +# B5-B7 — the two toggle buttons (role checkbox, AXSubrole "AXToggle", +# AXRoleDescription "toggle button" == press-to-flip buttons) +# ============================================================================= +class TestToggleButtons: + """Press-to-flip buttons: 'Global Quick Switch' and 'Launch at Login'. + + Both persist across the per-test relaunch (app-group defaults / SMAppService), + so every test reads `before`, flips, asserts the flip, then restores.""" + + @pytest.mark.rb( + depth=1, jump_kind="transition", + expect="pressing the 'Global Quick Switch' toggle button flips its AXValue " + "to the opposite of the value read before (0<->1), and pressing it " + "again restores the original value") + def test_global_quick_switch_toggle_flips_and_restores(self, ax): + w = enter_panel(ax) + tog = toggle_for(ax, w, "Global Quick Switch") + assert tog is not None, ( + "expected a toggle button (role 'checkbox', AXSubrole 'AXToggle') on the " + "settings row labelled 'Global Quick Switch'") + assert is_enabled(ax, tog.id), ( + "expected the 'Global Quick Switch' toggle button AXEnabled == True") + + before = as_int(toggle_value(ax, tog.id)) + assert before in (0, 1), ( + f"expected the 'Global Quick Switch' toggle AXValue to be 0 or 1 before " + f"pressing, got {toggle_value(ax, tog.id)!r}") + + ax.action(tog.id, "AXPress") + time.sleep(1.2) + after = as_int(toggle_value(ax, toggle_for(ax, w, "Global Quick Switch").id)) + + assert kit.rb_flip(before, after), ( + f"expected the 'Global Quick Switch' toggle AXValue to CHANGE on AXPress: " + f"before={before} after={after}") + assert after == 1 - before, ( + f"expected the 'Global Quick Switch' toggle AXValue == {1 - before} after " + f"one AXPress (it must flip 0<->1), got {after}") + + # restore the persisted setting + tog2 = toggle_for(ax, w, "Global Quick Switch") + ax.action(tog2.id, "AXPress") + time.sleep(1.2) + restored = as_int(toggle_value(ax, toggle_for(ax, w, "Global Quick Switch").id)) + assert restored == before, ( + f"expected the 'Global Quick Switch' toggle AXValue back to its original " + f"{before} after a second AXPress, got {restored}") + + @pytest.mark.rb( + depth=1, jump_kind="reach", + expect="pressing the 'Global Quick Switch' toggle button ON materialises a " + "new shortcut-recorder text field showing '⌃⇧Space', taking " + "the window's text_field count from 1 to 2") + def test_global_quick_switch_toggle_on_reveals_shortcut_recorder(self, ax): + w = enter_panel(ax) + tog = toggle_for(ax, w, "Global Quick Switch") + assert tog is not None, ( + "expected a toggle button (role 'checkbox', AXSubrole 'AXToggle') on the " + "settings row labelled 'Global Quick Switch'") + + original = as_int(toggle_value(ax, tog.id)) + assert original in (0, 1), ( + f"expected the 'Global Quick Switch' toggle AXValue to be 0 or 1, " + f"got {toggle_value(ax, tog.id)!r}") + + try: + # normalise to OFF so the press below is genuinely 0 -> 1 + if original == 1: + ax.action(tog.id, "AXPress") + time.sleep(1.2) + tog = toggle_for(ax, w, "Global Quick Switch") + off_value = as_int(toggle_value(ax, tog.id)) + assert off_value == 0, ( + f"expected the 'Global Quick Switch' toggle AXValue == 0 after " + f"normalising it OFF, got {off_value}") + + fields_before = text_field_count(ax, w) + assert fields_before == 1, ( + f"expected exactly 1 text_field (the 'Search Apps... (⌘F)' field) " + f"in the panel while Global Quick Switch is OFF, got {fields_before}") + + showing_before = kit.rb_showing(ax) + ax.action(tog.id, "AXPress") + time.sleep(1.2) + showing_after = kit.rb_showing(ax) + + verdict = kit.rb_reach(showing_before, showing_after, target="⌃⇧Space") + fields_after = text_field_count(ax, w) + + screenshot_assert( + "buttons_quick_switch_toggle_on", + "The dark 600x500 TypeSwitch panel at the top-right of the screen with " + "'Global Quick Switch' switched ON: the switch at the right of the " + "'Global Quick Switch' row is in its filled/ON position and a NEW " + "shortcut recorder field displaying '⌃⇧Space' has appeared to " + "the LEFT of that switch. The sub-line 'Use shortcut to quickly switch " + "between input methods' sits below it, the 'Launch at Login' row and its " + "switch are unchanged, and the footer text buttons 'Refresh (⌘R)' " + "and 'Quit (⌘Q)' are still at the bottom-right.") + + assert verdict, ( + "expected a NEW widget showing the shortcut '⌃⇧Space' " + "(placeholder 'Record Shortcut') to appear after pressing the " + "'Global Quick Switch' toggle button ON — it was absent before the " + "press and must be present after it") + assert fields_after == 2, ( + f"expected the panel's text_field count to go 1 -> 2 when Global Quick " + f"Switch is toggled ON (search field + shortcut recorder), got " + f"{fields_before} -> {fields_after}") + finally: + try: + cur = toggle_for(ax, w, "Global Quick Switch") + if cur is not None and as_int(toggle_value(ax, cur.id)) != original: + ax.action(cur.id, "AXPress") + time.sleep(1.2) + except Exception: + pass + + @pytest.mark.rb( + depth=1, jump_kind="transition", + expect="pressing the 'Launch at Login' toggle button flips its AXValue to " + "the opposite of the value read before, with no error sheet appearing, " + "and a second press restores the original value") + def test_launch_at_login_toggle_flips_without_error_sheet(self, ax): + w = enter_panel(ax) + tog = toggle_for(ax, w, "Launch at Login") + assert tog is not None, ( + "expected a toggle button (role 'checkbox', AXSubrole 'AXToggle') on the " + "settings row labelled 'Launch at Login'") + assert is_enabled(ax, tog.id), ( + "expected the 'Launch at Login' toggle button AXEnabled == True") + + before = as_int(toggle_value(ax, tog.id)) + assert before in (0, 1), ( + f"expected the 'Launch at Login' toggle AXValue to be 0 or 1 before " + f"pressing, got {toggle_value(ax, tog.id)!r}") + + ax.action(tog.id, "AXPress") + time.sleep(2.0) + after = as_int(toggle_value(ax, toggle_for(ax, w, "Launch at Login").id)) + + sheets = ax.find(role="sheet", max_results=3, max_depth=12) + assert sheets == [], ( + f"expected 0 sheets after pressing 'Launch at Login' (SMAppService " + f"registration must succeed with no error alert), got {len(sheets)} sheet(s)") + assert kit.rb_flip(before, after), ( + f"expected the 'Launch at Login' toggle AXValue to CHANGE on AXPress: " + f"before={before} after={after}") + assert after == 1 - before, ( + f"expected the 'Launch at Login' toggle AXValue == {1 - before} after one " + f"AXPress, got {after}") + + # restore the persisted SMAppService state + tog2 = toggle_for(ax, w, "Launch at Login") + ax.action(tog2.id, "AXPress") + time.sleep(2.0) + restored = as_int(toggle_value(ax, toggle_for(ax, w, "Launch at Login").id)) + assert restored == before, ( + f"expected the 'Launch at Login' toggle AXValue back to its original " + f"{before} after a second AXPress, got {restored}") + + +# ============================================================================= +# B8 — press-to-select radio buttons inside an app row +# ============================================================================= +class TestRowRadioButtons: + """Each app row holds a 2-segment picker: `radio "Default"` + an input-method radio.""" + + @pytest.mark.rb( + depth=1, jump_kind="transition", + expect="pressing the non-'Default' radio in the Calculator row selects it " + "(AXValue 1) and deselects 'Default' (AXValue 0) — mutual exclusion") + def test_row_picker_radio_press_selects_and_deselects_default(self, ax): + w = enter_panel(ax) + default = other = None + try: + set_search(ax, w, "Calculator") + + groups = ax.find(role="radiogroup", root_id=w.id, max_results=20, + max_depth=12) + assert len(groups) == 1, ( + f"expected exactly 1 radiogroup (the Calculator row's picker) while " + f"the search field holds 'Calculator', got {len(groups)}") + + radios = ax.find(role="radio", root_id=groups[0].id, max_results=6, + max_depth=4) + assert len(radios) == 2, ( + f"expected exactly 2 radio buttons inside the Calculator row's picker " + f"('Default' plus one input-method entry), got {len(radios)}: " + f"{[r.name for r in radios]!r}") + + default = next((r for r in radios + if (r.name or "").strip() in ("Default", "默认")), None) + assert default is not None, ( + f"expected one radio button named 'Default' in the row picker, got " + f"{[r.name for r in radios]!r}") + other = next(r for r in radios if r.id != default.id) + assert other.name, ( + "expected the second radio button in the row picker to have a " + "non-empty name (the input-method name, e.g. 'U.S.')") + + # normalise the persisted per-app selection to 'Default' + ax.action(default.id, "AXPress") + time.sleep(0.8) + before = [as_int(toggle_value(ax, default.id)), + as_int(toggle_value(ax, other.id))] + assert before == [1, 0], ( + f"expected ['Default'=1, {other.name!r}=0] after normalising the " + f"Calculator picker to 'Default', got {before}") + + ax.action(other.id, "AXPress") + time.sleep(1.0) + after = [as_int(toggle_value(ax, default.id)), + as_int(toggle_value(ax, other.id))] + + screenshot_assert( + "buttons_row_picker_radio_selected", + "The dark TypeSwitch panel with 'Calculator' typed in the top search " + "field shows exactly ONE app row: the Calculator icon, the name " + "'Calculator', and a two-segment picker at the right whose SECOND " + "segment (the input method, e.g. 'U.S.') is now highlighted/selected " + "instead of the 'Default' segment. Below the empty rest of the list are " + "the 'Global Quick Switch' and 'Launch at Login' rows with their " + "switches, and the footer buttons 'Refresh (⌘R)' and " + "'Quit (⌘Q)'.") + + assert kit.rb_flip(before, after), ( + f"expected the Calculator picker's radio values to CHANGE when the " + f"{other.name!r} radio is pressed: before={before} after={after}") + assert after == [0, 1], ( + f"expected ['Default'=0, {other.name!r}=1] after pressing the " + f"{other.name!r} radio (radio buttons are mutually exclusive), " + f"got {after}") + finally: + try: + if default is not None: + ax.action(default.id, "AXPress") + time.sleep(0.6) + set_search(ax, w, "", settle=0.4) + except Exception: + pass + + +# ============================================================================= +# B9 — footer button identity / geometry (the ONLY non-pressing test here: +# `Quit (⌘Q)` must never be activated) +# ============================================================================= +class TestFooterButtonIdentity: + + @pytest.mark.rb( + depth=0, jump_kind="none", + expect="the panel footer holds exactly the buttons 'Refresh (⌘R)' and " + "'Quit (⌘Q)', both enabled and pressable, with Refresh left of " + "Quit on the same baseline") + def test_footer_buttons_refresh_left_of_quit(self, ax): + w = enter_panel(ax) + buttons = ax.find(role="button", root_id=w.id, max_results=30, max_depth=12) + names = [(b.name or "").strip() for b in buttons if (b.name or "").strip()] + + refresh = next((b for b in buttons + if (b.name or "").strip() == "Refresh (⌘R)"), None) + quit_btn = next((b for b in buttons + if (b.name or "").strip() == "Quit (⌘Q)"), None) + + assert refresh is not None, ( + f"expected a button whose name is exactly 'Refresh (⌘R)' in the panel, " + f"named buttons found: {names!r}") + assert quit_btn is not None, ( + f"expected a button whose name is exactly 'Quit (⌘Q)' in the panel, " + f"named buttons found: {names!r}") + + assert is_enabled(ax, refresh.id), ( + "expected button 'Refresh (⌘R)' AXEnabled == True, got False") + assert is_enabled(ax, quit_btn.id), ( + "expected button 'Quit (⌘Q)' AXEnabled == True, got False") + + # Action interface: assert only when the harness can enumerate actions. + for btn in (refresh, quit_btn): + acts = actions_of(ax, btn) + if acts: + assert "AXPress" in acts, ( + f"expected button {btn.name!r} to advertise the action 'AXPress', " + f"got {acts!r}") + + rx, ry, rw, rh = frame(ax, refresh.id) + qx, qy, qw, qh = frame(ax, quit_btn.id) + assert None not in (rx, ry, qx, qy), ( + f"expected AXPosition/AXSize to be readable for both footer buttons, got " + f"Refresh=({rx}, {ry}, {rw}, {rh}) Quit=({qx}, {qy}, {qw}, {qh})") + assert rx < qx, ( + f"expected 'Refresh (⌘R)' to sit LEFT of 'Quit (⌘Q)' " + f"(Refresh.x < Quit.x), got Refresh.x={rx} Quit.x={qx}") + assert abs(ry - qy) <= 4.0, ( + f"expected both footer buttons on the same baseline (|Refresh.y - Quit.y| " + f"<= 4 px), got Refresh.y={ry} Quit.y={qy} (delta {abs(ry - qy)})") + # NOTE: neither footer button is pressed here — pressing 'Quit (⌘Q)' would + # terminate the shared app process. diff --git a/macos/ygsgdbd-typeswitch/tests/test_ax_computation.py b/macos/ygsgdbd-typeswitch/tests/test_ax_computation.py new file mode 100644 index 0000000000000000000000000000000000000000..e849da60e784ba3d17dd78a9f7060e14e59cce68 --- /dev/null +++ b/macos/ygsgdbd-typeswitch/tests/test_ax_computation.py @@ -0,0 +1,690 @@ +"""test_ax_computation.py — TypeSwitch "computation" module. + +TypeSwitch is a menu-bar-extra app, so its computation is NOT arithmetic: the app's +compute surfaces (all OBSERVED in recon.md ## COMPUTATION) are + + 1. the fuzzy app-search engine input = the search `text_field` + output = the filtered app-row `label` list + 2. the app-list refresh input = a new .app in a scanned directory + Refresh + output = the new app appears as a searchable row + 3. the global-hotkey switch cycle input = ⌃⇧Space while Global Quick Switch is ON + output = a 152x32 toast `label` "Switched to: …" + +Every expected value below is the value recon OBSERVED on the reference app. + +Reveal path: the plain `ax` fixture + `rb_enter_main_window()` (recon REVEAL_STEPS). +`ax_with_reset` / `helpers.ensure_panel_open()` are NEVER used here — measured 39.5 s on +this app, which blows the runner's 30 s per-test timeout. + +SAFETY: this module never presses `Quit (⌘Q)` / `Quit TypeSwitch`, never sends ⌘Q and +never touches the `Record Shortcut` recorder field. +""" + +# ---- paste verbatim into every test module ------------------------------------- +import os, json, re, subprocess, time +import pytest +import rb_testgen_kit as kit +import verifier_helpers as helpers + +CTRL_LABELS = { + "Global Quick Switch", + "Use shortcut to quickly switch between input methods", + "Launch at Login", + "Automatically start TypeSwitch when you log in", +} + + +def screenshot_assert(test_name, description, results_dir=None): + results_dir = results_dir or os.environ.get("RESULTS_DIR", "results") + 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 + af = os.path.join(ss_dir, "assertions.json") + data = {} + if os.path.exists(af): + try: + data = json.load(open(af)) + except Exception: + data = {} + data[f"{test_name}.png"] = description + with open(af, "w") as f: + json.dump(data, f, indent=2) + + +def _main_window(ax): + """The app's content window: a top-level window that owns a group subtree.""" + for w in ax.find(role="window", max_results=6, max_depth=2): + if ax.find(role="group", root_id=w.id, max_results=1, max_depth=3): + return w + return None + + +def _wait_window(ax, timeout=1.2): + end = time.time() + timeout + while time.time() < end: + w = _main_window(ax) + if w is not None: + return w + time.sleep(0.15) + return None + + +def rb_enter_main_window(ax, attempts=4): + """Reveal the app's main UI (surface crossing: menu bar -> window). + + Portable: an already-open window wins; otherwise press status-item / menu-bar + items (the extras bar FIRST), then CG-click, then ax.ensure_ui_visible().""" + w = _main_window(ax) + if w is not None: + return w + bars = ax.find(role="menu_bar", max_results=4, max_depth=1) + ordered = [] + for bar in reversed(bars): # extras (status-item) menu bar first + ordered += [i for i in ax.find(role="menu_bar_item", root_id=bar.id, + max_results=12) + if (i.name or "") != "Apple"] + for item in ordered: + for _ in range(attempts): + ax.action(item.id, "AXPress") + w = _wait_window(ax) + if w is not None: + return w + helpers.dismiss_menus(ax) + for item in ordered: + ax.click_element_cg(item.id) + w = _wait_window(ax) + if w is not None: + return w + helpers.dismiss_menus(ax) + ax.ensure_ui_visible() + return _main_window(ax) + + +def status_item(ax): + """The menu-bar-extra item that owns the app UI (last menu bar, first item).""" + bars = ax.find(role="menu_bar", max_results=4, max_depth=1) + for bar in reversed(bars): + items = [i for i in ax.find(role="menu_bar_item", root_id=bar.id, max_results=12) + if (i.name or "") != "Apple"] + if len(items) == 1: # a status/extras bar holds exactly one item + return items[0] + return None + + +def frame(ax, el_id): + """(x, y, w, h) floats parsed out of AXPosition / AXSize.""" + d = ax.get(el_id, ["AXPosition", "AXSize"]) + + def num(s, key): + m = re.search(key + r":(-?[\d.]+)", str(s)) + return float(m.group(1)) if m else None + + return (num(d.get("AXPosition"), "x"), num(d.get("AXPosition"), "y"), + num(d.get("AXSize"), "w"), num(d.get("AXSize"), "h")) + + +def search_field(ax, w): + """The app-list search field: the text field whose placeholder mentions search.""" + tfs = ax.find(role="text_field", root_id=w.id, max_results=8, max_depth=12) + for t in tfs: + ph = (ax.get(t.id, ["AXPlaceholderValue"]).get("AXPlaceholderValue") or "") + if "Search" in ph or "搜索" in ph: + return t + return tfs[0] if tfs else None + + +def app_names(ax, w): + """Visible app-row names = every label that is not one of the 4 control labels.""" + return [e.value for e in ax.find(role="label", root_id=w.id, + max_results=300, max_depth=12) + if e.value and e.value not in CTRL_LABELS] + + +def set_search(ax, w, query, settle=0.8): + tf = search_field(ax, w) + ax.set_value(tf.id, query) + time.sleep(settle) + return tf + + +def toggle_for(ax, w, label_text): + """The checkbox/toggle belonging to the settings row labelled `label_text` + (pairs by nearest vertical centre — robust to child ordering).""" + lab = None + for e in ax.find(role="label", root_id=w.id, max_results=300, max_depth=12): + if e.value == label_text: + lab = e + break + boxes = ax.find(role="checkbox", root_id=w.id, max_results=10, max_depth=12) + if not boxes: + return None + if lab is None: + return boxes[0] + ly = (frame(ax, lab.id)[1] or 0) + (frame(ax, lab.id)[3] or 0) / 2.0 + best, bestd = None, 1e9 + for b in boxes: + by = (frame(ax, b.id)[1] or 0) + (frame(ax, b.id)[3] or 0) / 2.0 + if abs(by - ly) < bestd: + best, bestd = b, abs(by - ly) + return best + + +def toggle_value(ax, el_id): + return ax.get(el_id, ["AXValue"]).get("AXValue") + + +def named_button(ax, w, keyword): + for b in ax.find(role="button", root_id=w.id, max_results=30, max_depth=12): + if b.name and keyword.lower() in b.name.lower(): + return b + return None +# -------------------------------------------------------------------------------- + +import shutil # noqa: E402 (probe-bundle cleanup for the Refresh recomputation test) + +RESULTS_DIR = os.environ.get("RESULTS_DIR", "results") + +# Names OBSERVED in the unfiltered (empty-query) row list — recon ## COMPUTATION. +BASELINE_SOME = ["Activity Monitor", "App Store", "Calculator", + "Calendar", "Chess", "Clock"] + +# Info.plist body recon verified the scanner accepts (NAME is substituted). +PROBE_PLIST = """ + + +CFBundleNameNAME +CFBundleIdentifiercom.recreationbench.NAME +CFBundleExecutableNAME +CFBundlePackageTypeAPPL + +""" + + +# ── local read/act helpers (thin, on top of the verbatim recon block) ──────────── + +def rows(ax, w): + """The computation OUTPUT as plain python strings: the filtered app-row names.""" + return [str(v) for v in app_names(ax, w)] + + +def query_rows(ax, w, text): + """Feed the search field (the computation INPUT) and read the output rows.""" + set_search(ax, w, text) + return rows(ax, w) + + +def role_count(ax, w, role): + return len(ax.find(role=role, root_id=w.id, max_results=60, max_depth=12)) + + +def window_labels(ax, w): + return {str(e.value) for e in ax.find(role="label", root_id=w.id, + max_results=300, max_depth=12) if e.value} + + +def normalise_toggle(ax, w, label_text, want, settle=1.0): + """Force the settings toggle `label_text` to `want` (0/1). + + Returns (element, value_before). Never asserts an absolute initial state — the + setting lives in the app-group defaults suite and survives the per-test relaunch. + """ + el = toggle_for(ax, w, label_text) + assert el is not None, f"no checkbox found for the settings row '{label_text}'" + before = int(toggle_value(ax, el.id) or 0) + if before != want: + ax.action(el.id, "AXPress") + time.sleep(settle) + el = toggle_for(ax, w, label_text) # re-locate: layout changes when ON + assert el is not None, f"checkbox for '{label_text}' vanished after AXPress" + now = int(toggle_value(ax, el.id) or 0) + assert now == want, ( + f"could not set '{label_text}' to {want}: AXValue is {now} " + f"(was {before} before the AXPress)") + return el, before + + +def restore_toggle(ax, w, label_text, want, settle=1.0): + """Best-effort restore of a settings toggle to its pre-test value.""" + try: + el = toggle_for(ax, w, label_text) + if el is None: + return + if int(toggle_value(ax, el.id) or 0) != int(want): + ax.action(el.id, "AXPress") + time.sleep(settle) + except Exception: + pass + + +def rb_reach_toast(ax, panel, timeout=3.0): + """Poll for the transient toast window and return its text values.""" + end = time.time() + timeout + while time.time() < end: + for x in ax.find(role="window", max_results=8, max_depth=2): + if x.id == panel.id: + continue + vals = [e.value or e.name for e in + ax.find_text_elements(root_id=x.id, max_results=10)] + if any(v and "Switched to" in str(v) for v in vals): + return x, vals + time.sleep(0.15) + return None, [] + + +# ── C1 – C11: the fuzzy app-search engine ─────────────────────────────────────── + +class TestSearchComputation: + """input = search `text_field` (ax.set_value) → output = app-row `label` list.""" + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="query 'Calc' filters the app list to exactly ['Calculator'] " + "(1 radiogroup, 1 app image)") + def test_search_calc_exact_row(self, ax): + w = rb_enter_main_window(ax) + assert w is not None, "main panel window never appeared (rb_enter_main_window)" + + observed = query_rows(ax, w, "Calc") + assert kit.rb_value(observed, ["Calculator"]), ( + f"query 'Calc' must compute exactly ['Calculator'], got {observed}") + assert observed == ["Calculator"], ( + f"query 'Calc' must compute exactly ['Calculator'], got {observed}") + + # Structural consequence of the filter (recon: 1 radiogroup / 1 image / 1 label). + n_groups = role_count(ax, w, "radiogroup") + n_images = role_count(ax, w, "image") + assert n_groups == 1, ( + f"with 'Calc' the window must hold exactly 1 radiogroup picker, got {n_groups}") + assert n_images == 1, ( + f"with 'Calc' the window must hold exactly 1 app image, got {n_images}") + + screenshot_assert( + "computation_test_search_calc_exact_row", + "TypeSwitch's dark 600x500 panel is anchored at the top-right of the screen " + "under the menu bar. The search field at the top contains the text 'Calc' and " + "the list below shows exactly ONE app row: the Calculator icon, the name " + "'Calculator', and a two-segment Default | U.S. picker on the right. The " + "'Global Quick Switch' and 'Launch at Login' rows and the 'Refresh (⌘R)' / " + "'Quit (⌘Q)' buttons are still visible at the bottom.", + RESULTS_DIR) + + set_search(ax, w, "") + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="lowercase query 'cal' computes ['Calculator', 'Calendar'] " + "in that order (case-insensitive, 2 hits)") + def test_search_lowercase_two_hits(self, ax): + w = rb_enter_main_window(ax) + assert w is not None, "main panel window never appeared (rb_enter_main_window)" + + observed = query_rows(ax, w, "cal") + assert kit.rb_value(observed, ["Calculator", "Calendar"]), ( + f"lowercase query 'cal' must compute ['Calculator', 'Calendar'], got {observed}") + assert observed == ["Calculator", "Calendar"], ( + f"lowercase query 'cal' must compute ['Calculator', 'Calendar'] in that " + f"ranking order, got {observed}") + assert role_count(ax, w, "radiogroup") == 2, ( + "with 'cal' the window must hold exactly 2 radiogroup pickers (one per hit)") + + set_search(ax, w, "") + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="query 'photo' computes ['Photo Booth', 'Photos']") + def test_search_photo_two_hits(self, ax): + w = rb_enter_main_window(ax) + assert w is not None, "main panel window never appeared (rb_enter_main_window)" + + observed = query_rows(ax, w, "photo") + assert kit.rb_value(observed, ["Photo Booth", "Photos"]), ( + f"query 'photo' must compute ['Photo Booth', 'Photos'], got {observed}") + assert observed == ["Photo Booth", "Photos"], ( + f"query 'photo' must compute ['Photo Booth', 'Photos'] in that order, " + f"got {observed}") + + set_search(ax, w, "") + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="substring (non-prefix) query 'Chrome' computes " + "['Google Chrome']") + def test_search_substring_match(self, ax): + w = rb_enter_main_window(ax) + assert w is not None, "main panel window never appeared (rb_enter_main_window)" + + # 'Chrome' is NOT a prefix of 'Google Chrome' — a prefix-only engine returns []. + observed = query_rows(ax, w, "Chrome") + assert kit.rb_value(observed, ["Google Chrome"]), ( + f"substring query 'Chrome' must compute ['Google Chrome'], got {observed}") + assert observed == ["Google Chrome"], ( + f"substring query 'Chrome' must compute ['Google Chrome'], got {observed}") + + set_search(ax, w, "") + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="initials/fuzzy query 'clcltr' computes ['Calculator']") + def test_search_fuzzy_initials_match(self, ax): + w = rb_enter_main_window(ax) + assert w is not None, "main panel window never appeared (rb_enter_main_window)" + + # c…l…c…l…t…r appears in order inside "Calculator" but is neither a prefix + # nor a contiguous substring — only a fuzzy scorer returns a hit here. + observed = query_rows(ax, w, "clcltr") + assert kit.rb_value(observed, ["Calculator"]), ( + f"fuzzy query 'clcltr' must compute ['Calculator'], got {observed}") + assert observed == ["Calculator"], ( + f"fuzzy query 'clcltr' must compute ['Calculator'], got {observed}") + + set_search(ax, w, "") + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="'xco' and 'Xcode' both compute ['Xcode']") + def test_search_abbreviation_and_full_name(self, ax): + w = rb_enter_main_window(ax) + assert w is not None, "main panel window never appeared (rb_enter_main_window)" + + abbrev = query_rows(ax, w, "xco") + assert kit.rb_value(abbrev, ["Xcode"]), ( + f"query 'xco' must compute ['Xcode'], got {abbrev}") + assert abbrev == ["Xcode"], f"query 'xco' must compute ['Xcode'], got {abbrev}" + + full = query_rows(ax, w, "Xcode") + assert kit.rb_value(full, ["Xcode"]), ( + f"query 'Xcode' must compute ['Xcode'], got {full}") + assert full == ["Xcode"], f"query 'Xcode' must compute ['Xcode'], got {full}" + + set_search(ax, w, "") + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="'TextEdit'/'Weather'/'Notes' each compute their own single " + "row although none is a realized on-screen row") + def test_search_beyond_realized_rows(self, ax): + w = rb_enter_main_window(ax) + assert w is not None, "main panel window never appeared (rb_enter_main_window)" + + # Only ~13 rows are ever realized (alphabetically 'Activity Monitor'…'Clock'), + # so a hit on any of these proves the WHOLE scanned list is searched. + for query, expected in (("TextEdit", ["TextEdit"]), + ("Weather", ["Weather"]), + ("Notes", ["Notes"])): + observed = query_rows(ax, w, query) + assert kit.rb_value(observed, expected), ( + f"query {query!r} must compute {expected}, got {observed}") + assert observed == expected, ( + f"query {query!r} must compute {expected} (the full app list, not just " + f"the realized rows, must be searched), got {observed}") + + set_search(ax, w, "") + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="'System Settings'/'Time Machine'/'Terminal' each compute " + "their own single row") + def test_search_multiword_and_utilities(self, ax): + w = rb_enter_main_window(ax) + assert w is not None, "main panel window never appeared (rb_enter_main_window)" + + # Multi-word queries (space kept) + an app that lives in /Applications/Utilities. + for query, expected in (("System Settings", ["System Settings"]), + ("Time Machine", ["Time Machine"]), + ("Terminal", ["Terminal"])): + observed = query_rows(ax, w, query) + assert kit.rb_value(observed, expected), ( + f"query {query!r} must compute {expected}, got {observed}") + assert observed == expected, ( + f"query {query!r} must compute {expected}, got {observed}") + + set_search(ax, w, "") + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="query 'zzzznotanapp' computes [] (0 radiogroup) while the 4 " + "control labels survive") + def test_search_no_match_empty_result(self, ax): + w = rb_enter_main_window(ax) + assert w is not None, "main panel window never appeared (rb_enter_main_window)" + + observed = query_rows(ax, w, "zzzznotanapp") + assert kit.rb_value(observed, []), ( + f"query 'zzzznotanapp' must compute [] (no app rows), got {observed}") + assert observed == [], ( + f"query 'zzzznotanapp' must compute [] (no app rows), got {observed}") + + labels = window_labels(ax, w) + missing = sorted(CTRL_LABELS - labels) + assert not missing, ( + "an empty search result must keep the 4 control labels 'Global Quick Switch', " + "'Use shortcut to quickly switch between input methods', 'Launch at Login', " + f"'Automatically start TypeSwitch when you log in' — missing {missing}") + + n_groups = role_count(ax, w, "radiogroup") + assert n_groups == 0, ( + f"an empty search result must leave 0 radiogroup pickers, got {n_groups}") + + screenshot_assert( + "computation_test_search_no_match_empty_result", + "TypeSwitch's dark 600x500 panel with 'zzzznotanapp' typed in the top search " + "field and NO app rows at all — the list area is completely blank. The " + "'Global Quick Switch' row (with its sub-line 'Use shortcut to quickly switch " + "between input methods'), the 'Launch at Login' row and the 'Refresh (⌘R)' / " + "'Quit (⌘Q)' text buttons all remain visible.", + RESULTS_DIR) + + set_search(ax, w, "") + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="unfiltered list is alphabetically sorted, >=10 rows, and " + "contains Activity Monitor / App Store / Calculator / " + "Calendar / Chess / Clock") + def test_unfiltered_baseline_list(self, ax): + w = rb_enter_main_window(ax) + assert w is not None, "main panel window never appeared (rb_enter_main_window)" + + set_search(ax, w, "") # explicit empty query = no filtering + names = rows(ax, w) + + assert len(names) >= 10, ( + f"the unfiltered app list must expose at least 10 rows, got {len(names)}: " + f"{names}") + assert names == sorted(names, key=str.lower), ( + f"the unfiltered app list must be alphabetically (case-insensitively) " + f"sorted, got {names}") + + present = all(kit.rb_value(names, n) for n in BASELINE_SOME) + assert present, ( + f"the unfiltered app list must contain {BASELINE_SOME}, got {names}") + assert set(BASELINE_SOME) <= set(names), ( + f"the unfiltered app list must contain {BASELINE_SOME}, got {names}") + + screenshot_assert( + "computation_test_unfiltered_baseline_list", + "TypeSwitch's dark 600x500 panel anchored top-right under the menu bar with " + "an EMPTY search field at the top, showing the full alphabetical app list: " + "rows such as 'Activity Monitor', 'AirPort Utility', 'App Store', " + "'Calculator', 'Calendar', 'Chess', 'Clock', each with its app icon on the " + "left and a two-segment Default | U.S. picker on the right. Bottom: the " + "'Global Quick Switch' and 'Launch at Login' rows with switches, and the " + "'Refresh (⌘R)' / 'Quit (⌘Q)' buttons.", + RESULTS_DIR) + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="filter narrows the list to ['Calculator'] and clearing the " + "query restores the identical baseline list") + def test_filter_then_restore_round_trip(self, ax): + w = rb_enter_main_window(ax) + assert w is not None, "main panel window never appeared (rb_enter_main_window)" + + set_search(ax, w, "") + baseline = rows(ax, w) + assert len(baseline) >= 10, ( + f"baseline list must hold at least 10 app rows before filtering, " + f"got {len(baseline)}: {baseline}") + + filtered = query_rows(ax, w, "Calc") + assert filtered == ["Calculator"], ( + f"filtering with 'Calc' must narrow the list to ['Calculator'], got {filtered}") + assert kit.rb_flip(baseline, filtered), ( + f"the app list must CHANGE when the query 'Calc' is applied: baseline " + f"{baseline} vs filtered {filtered}") + + restored = query_rows(ax, w, "") + assert baseline == restored, ( + f"clearing the query must restore the identical baseline list {baseline}, " + f"got {restored}") + + +# ── C12: refresh recomputation ────────────────────────────────────────────────── + +class TestRefreshRecomputation: + """A new .app in a scanned directory is only found AFTER `Refresh (⌘R)`.""" + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="a freshly created ~/Applications/RBCompProbe.app is [] before " + "Refresh and ['RBCompProbe'] after Refresh") + def test_refresh_picks_up_new_app(self, ax): + w = rb_enter_main_window(ax) + assert w is not None, "main panel window never appeared (rb_enter_main_window)" + + probe = "RBCompProbe" + bundle = os.path.join(os.path.expanduser("~/Applications"), probe + ".app") + macos_dir = os.path.join(bundle, "Contents", "MacOS") + post_delete = {} + + try: + os.makedirs(macos_dir, exist_ok=True) + exe = os.path.join(macos_dir, probe) + with open(exe, "w") as f: + f.write("#!/bin/sh\nexit 0\n") + os.chmod(exe, 0o755) + with open(os.path.join(bundle, "Contents", "Info.plist"), "w") as f: + f.write(PROBE_PLIST.replace("NAME", probe)) + + stale = query_rows(ax, w, probe) + assert stale == [], ( + f"before Refresh the list is stale and {probe!r} must compute [], " + f"got {stale}") + + btn = named_button(ax, w, "Refresh") + assert btn is not None, "no footer button whose name contains 'Refresh'" + ax.action(btn.id, "AXPress") + time.sleep(2.5) + + rescanned = rows(ax, w) + assert kit.rb_value(rescanned, [probe]), ( + f"after pressing Refresh the query {probe!r} must compute ['{probe}'], " + f"got {rescanned}") + assert rescanned == [probe], ( + f"after pressing Refresh the query {probe!r} must compute ['{probe}'], " + f"got {rescanned}") + finally: + # Cleanup + re-scan. The verdict on it is asserted AFTER the finally block so + # a failure here can never mask the primary assertion above. + shutil.rmtree(bundle, ignore_errors=True) + try: + btn = named_button(ax, w, "Refresh") + if btn is not None: + ax.action(btn.id, "AXPress") + time.sleep(2.0) + post_delete["rows"] = rows(ax, w) + set_search(ax, w, "") + except Exception as exc: # pragma: no cover - cleanup only + post_delete["error"] = repr(exc) + + assert post_delete.get("rows") == [], ( + f"after deleting ~/Applications/{probe}.app and pressing Refresh the query " + f"{probe!r} must compute [] again, got {post_delete}") + assert kit.rb_value(post_delete.get("rows"), []), ( + f"after deleting the probe bundle and refreshing, {probe!r} must compute [], " + f"got {post_delete}") + + +# ── C13 – C14: the global-hotkey input-method switch cycle ────────────────────── + +class TestSwitchCycleComputation: + """⌃⇧Space runs the switch cycle and reports the result in a 152x32 toast.""" + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="with Global Quick Switch ON, ⌃⇧Space shows a toast whose " + "label starts with 'Switched to: ' next to image 'Keyboard'") + def test_hotkey_shows_switched_to_toast(self, ax): + w = rb_enter_main_window(ax) + assert w is not None, "main panel window never appeared (rb_enter_main_window)" + + el, before = normalise_toggle(ax, w, "Global Quick Switch", 1) + try: + assert int(toggle_value(ax, el.id) or 0) == 1, ( + "'Global Quick Switch' must read AXValue == 1 before the hotkey test") + time.sleep(1.0) + + helpers.send_key(49, ["ctrl", "shift"]) # ⌃⇧Space + toast, texts = rb_reach_toast(ax, w, timeout=3.0) + assert toast is not None, ( + "⌃⇧Space with Global Quick Switch ON must show a toast window holding a " + "label that starts with 'Switched to: '") + + glyphs = [str(i.name or "") for i in + ax.find(role="image", root_id=toast.id, max_results=6, max_depth=4)] + if "Keyboard" not in glyphs: + # The toast auto-dismisses ~1.65 s after it appears; if it vanished + # mid-read, run the cycle once more and re-read the fresh toast. + helpers.send_key(49, ["ctrl", "shift"]) + toast2, texts2 = rb_reach_toast(ax, w, timeout=3.0) + if toast2 is not None: + texts = texts2 or texts + glyphs = [str(i.name or "") for i in + ax.find(role="image", root_id=toast2.id, + max_results=6, max_depth=4)] + + hits = [str(v) for v in texts if v and "Switched to" in str(v)] + assert hits, ( + f"the toast must expose a label containing 'Switched to', got {texts}") + # Only the PREFIX is asserted: which input-method name follows depends on the + # stored setting of whatever app is frontmost (recon: 'U.S.' or '默认'). + assert kit.rb_value(hits[0], "Switched to: "), ( + f"the toast label must start with 'Switched to: ', got {hits[0]!r}") + assert hits[0].startswith("Switched to: "), ( + f"the toast label must start with 'Switched to: ', got {hits[0]!r}") + assert "Keyboard" in glyphs, ( + f"the toast must also contain the image named 'Keyboard', got {glyphs}") + finally: + restore_toggle(ax, w, "Global Quick Switch", before) + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="⌃⇧Space produces NO 'Switched to' toast while Global Quick " + "Switch is OFF, and DOES produce one once it is ON") + def test_hotkey_inert_until_enabled(self, ax): + w = rb_enter_main_window(ax) + assert w is not None, "main panel window never appeared (rb_enter_main_window)" + + el, before = normalise_toggle(ax, w, "Global Quick Switch", 0) + try: + assert int(toggle_value(ax, el.id) or 0) == 0, ( + "'Global Quick Switch' must read AXValue == 0 for the inert-hotkey phase") + time.sleep(1.0) + + n_windows_off = len(ax.find(role="window", max_results=8, max_depth=2)) + helpers.send_key(49, ["ctrl", "shift"]) # ⌃⇧Space, feature OFF + toast_off, texts_off = rb_reach_toast(ax, w, timeout=2.0) + toast_seen_when_off = toast_off is not None + assert not toast_seen_when_off, ( + f"with Global Quick Switch OFF, ⌃⇧Space must NOT show any 'Switched to' " + f"toast, but one appeared with texts {texts_off}") + assert n_windows_off >= 1, ( + "the main panel window must still be present while the hotkey is inert") + + normalise_toggle(ax, w, "Global Quick Switch", 1) + time.sleep(1.0) + helpers.send_key(49, ["ctrl", "shift"]) # ⌃⇧Space, feature ON + toast_on, texts_on = rb_reach_toast(ax, w, timeout=3.0) + toast_seen_when_on = toast_on is not None + assert toast_seen_when_on, ( + "with Global Quick Switch ON, ⌃⇧Space must show a toast window whose " + "label starts with 'Switched to: '") + + assert kit.rb_flip(toast_seen_when_off, toast_seen_when_on), ( + f"the same ⌃⇧Space press must flip from NO toast while OFF to a toast " + f"while ON, observed off={toast_seen_when_off} on={toast_seen_when_on}") + assert (toast_seen_when_off, toast_seen_when_on) == (False, True), ( + f"expected (toast while OFF, toast while ON) == (False, True), got " + f"({toast_seen_when_off}, {toast_seen_when_on}); ON texts {texts_on}") + finally: + restore_toggle(ax, w, "Global Quick Switch", before) diff --git a/macos/ygsgdbd-typeswitch/tests/test_ax_menus.py b/macos/ygsgdbd-typeswitch/tests/test_ax_menus.py new file mode 100644 index 0000000000000000000000000000000000000000..434d6dc839f1252bc54a49f7a1b68ce14889f503 --- /dev/null +++ b/macos/ygsgdbd-typeswitch/tests/test_ax_menus.py @@ -0,0 +1,482 @@ +"""test_ax_menus.py — AX menu-structure suite for TypeSwitch (macos-ygsgdbd-typeswitch). + +Every expectation below comes from recon.md `## MENUS` / `## AX_TREE` (observed on the +running official app). Golden-model facts exercised here: + + * the app is `LSUIElement` — its status item (`menu_bar_item "Keyboard"` on the extras + menu bar) has ONLY `AXPress` and NO menu children: its press opens the 600x500 panel + WINDOW, not a dropdown; + * the app menu bar holds `Apple / TypeSwitch / File / Edit / View / Window / Help`; + * `TypeSwitch`, `File`, `Edit`, `Window`, `Help` dropdowns + the two observed submenus + (`TypeSwitch ▸ Services`, `Edit ▸ AutoFill`); + * `TypeSwitch ▸ About TypeSwitch` opens a `window` `AXSubrole="AXDialog"`. + +The `View` menu is deliberately NOT asserted on: recon records it as EMPTY. + +Mechanics (recon `## APP → REVEAL_STEPS`): the plain `ax` fixture only — `ax_with_reset` / +`helpers.ensure_panel_open()` measured 39.5 s and blows the 30 s per-test timeout. The UI is +revealed with `rb_enter_main_window(ax)` (0.32 - 0.55 s). Menu items are ALWAYS looked up +scoped to their menu bar item (`open_menu`), otherwise the Apple menu's items come back +first and the wrong element is picked. + +SAFETY: `Quit TypeSwitch`, `Hide TypeSwitch`, `Hide Others`, `Show All`, the `Quit (⌘Q)` +button and ⌘Q are NEVER pressed (see `NEVER_PRESS` / `press_safe`). Nothing is killed. +""" + +# ---- paste verbatim into every test module ------------------------------------- +import os, json, re, subprocess, time +import pytest +import rb_testgen_kit as kit +import verifier_helpers as helpers + +CTRL_LABELS = { + "Global Quick Switch", + "Use shortcut to quickly switch between input methods", + "Launch at Login", + "Automatically start TypeSwitch when you log in", +} + + +def screenshot_assert(test_name, description, results_dir=None): + results_dir = results_dir or os.environ.get("RESULTS_DIR", "results") + 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 + af = os.path.join(ss_dir, "assertions.json") + data = {} + if os.path.exists(af): + try: + data = json.load(open(af)) + except Exception: + data = {} + data[f"{test_name}.png"] = description + with open(af, "w") as f: + json.dump(data, f, indent=2) + + +def _main_window(ax): + """The app's content window: a top-level window that owns a group subtree.""" + for w in ax.find(role="window", max_results=6, max_depth=2): + if ax.find(role="group", root_id=w.id, max_results=1, max_depth=3): + return w + return None + + +def _wait_window(ax, timeout=1.2): + end = time.time() + timeout + while time.time() < end: + w = _main_window(ax) + if w is not None: + return w + time.sleep(0.15) + return None + + +def rb_enter_main_window(ax, attempts=4): + """Reveal the app's main UI (surface crossing: menu bar -> window). + + Portable: an already-open window wins; otherwise press status-item / menu-bar + items (the extras bar FIRST), then CG-click, then ax.ensure_ui_visible().""" + w = _main_window(ax) + if w is not None: + return w + bars = ax.find(role="menu_bar", max_results=4, max_depth=1) + ordered = [] + for bar in reversed(bars): # extras (status-item) menu bar first + ordered += [i for i in ax.find(role="menu_bar_item", root_id=bar.id, + max_results=12) + if (i.name or "") != "Apple"] + for item in ordered: + for _ in range(attempts): + ax.action(item.id, "AXPress") + w = _wait_window(ax) + if w is not None: + return w + helpers.dismiss_menus(ax) + for item in ordered: + ax.click_element_cg(item.id) + w = _wait_window(ax) + if w is not None: + return w + helpers.dismiss_menus(ax) + ax.ensure_ui_visible() + return _main_window(ax) + + +def status_item(ax): + """The menu-bar-extra item that owns the app UI (last menu bar, first item).""" + bars = ax.find(role="menu_bar", max_results=4, max_depth=1) + for bar in reversed(bars): + items = [i for i in ax.find(role="menu_bar_item", root_id=bar.id, max_results=12) + if (i.name or "") != "Apple"] + if len(items) == 1: # a status/extras bar holds exactly one item + return items[0] + return None + + +def frame(ax, el_id): + """(x, y, w, h) floats parsed out of AXPosition / AXSize.""" + d = ax.get(el_id, ["AXPosition", "AXSize"]) + + def num(s, key): + m = re.search(key + r":(-?[\d.]+)", str(s)) + return float(m.group(1)) if m else None + + return (num(d.get("AXPosition"), "x"), num(d.get("AXPosition"), "y"), + num(d.get("AXSize"), "w"), num(d.get("AXSize"), "h")) + + +def search_field(ax, w): + """The app-list search field: the text field whose placeholder mentions search.""" + tfs = ax.find(role="text_field", root_id=w.id, max_results=8, max_depth=12) + for t in tfs: + ph = (ax.get(t.id, ["AXPlaceholderValue"]).get("AXPlaceholderValue") or "") + if "Search" in ph or "搜索" in ph: + return t + return tfs[0] if tfs else None + + +def app_names(ax, w): + """Visible app-row names = every label that is not one of the 4 control labels.""" + return [e.value for e in ax.find(role="label", root_id=w.id, + max_results=300, max_depth=12) + if e.value and e.value not in CTRL_LABELS] + + +def set_search(ax, w, query, settle=0.8): + tf = search_field(ax, w) + ax.set_value(tf.id, query) + time.sleep(settle) + return tf + + +def toggle_for(ax, w, label_text): + """The checkbox/toggle belonging to the settings row labelled `label_text` + (pairs by nearest vertical centre — robust to child ordering).""" + lab = None + for e in ax.find(role="label", root_id=w.id, max_results=300, max_depth=12): + if e.value == label_text: + lab = e + break + boxes = ax.find(role="checkbox", root_id=w.id, max_results=10, max_depth=12) + if not boxes: + return None + if lab is None: + return boxes[0] + ly = (frame(ax, lab.id)[1] or 0) + (frame(ax, lab.id)[3] or 0) / 2.0 + best, bestd = None, 1e9 + for b in boxes: + by = (frame(ax, b.id)[1] or 0) + (frame(ax, b.id)[3] or 0) / 2.0 + if abs(by - ly) < bestd: + best, bestd = b, abs(by - ly) + return best + + +def toggle_value(ax, el_id): + return ax.get(el_id, ["AXValue"]).get("AXValue") + + +def named_button(ax, w, keyword): + for b in ax.find(role="button", root_id=w.id, max_results=30, max_depth=12): + if b.name and keyword.lower() in b.name.lower(): + return b + return None +# -------------------------------------------------------------------------------- + + +RESULTS_DIR = os.environ.get("RESULTS_DIR", "results") + +# ── Observed menu inventory (recon ## MENUS) ───────────────────────────────────── +APP_MENU_BAR_ITEMS = ["Apple", "TypeSwitch", "File", "Edit", "View", "Window", "Help"] +STATUS_ITEM_NAME = "Keyboard" + +TYPESWITCH_MENU_ITEMS = ["About TypeSwitch", "Services", "Hide TypeSwitch", + "Hide Others", "Show All", "Quit TypeSwitch"] +FILE_MENU_ITEMS = ["Close", "Close All"] +EDIT_MENU_ITEMS = ["Undo", "Redo", "Cut", "Copy", "Paste", "Delete", "Select All", + "Start Dictation…", "Emoji & Symbols"] +WINDOW_MENU_ITEMS = ["Minimize", "Minimize All", "Zoom", "Zoom All", + "Bring All to Front", "Arrange in Front"] +HELP_MENU_ITEMS = ["TypeSwitch Help"] +AUTOFILL_SUBMENU_ITEMS = ["Contact…", "Passwords…"] +SERVICES_SETTINGS_ITEM = "Services Settings…" + +# About dialog text (recon ## TEXT) +ABOUT_NAME = "TypeSwitch" +ABOUT_VERSION_PREFIX = "Version " +ABOUT_COPYRIGHT = "Copyright © 2024 ygsgdbd. All rights reserved." +ABOUT_IMAGE = "TypeSwitch icon" + +# SAFETY belt — these menu items / buttons are never activated by this module. +NEVER_PRESS = { + "Quit TypeSwitch", "Hide TypeSwitch", "Hide Others", "Show All", "Quit (⌘Q)", + "Close", "Close All", "Cut", "Copy", "Paste", "Delete", "Select All", + "Undo", "Redo", "Start Dictation…", "Minimize", "Minimize All", "Zoom", + "Zoom All", "Bring All to Front", "Arrange in Front", +} + + +# ── Menu navigation (whitelisted nav helper — backs the declared depth) ────────── +def open_menu(ax, title): + """Open the menu bar item named `title` and return (item, its menu_items). + + Item lookups MUST be scoped to the menu bar item: an unscoped + `ax.find(role="menu_item")` returns the APPLE menu's items first (recon ## MENUS). + """ + mbi = None + for m in ax.find(role="menu_bar_item", max_results=12, max_depth=6): + if m.name == title: + mbi = m + break + assert mbi is not None, f"no menu bar item named {title!r}" + ax.action(mbi.id, "AXPress") + time.sleep(0.9) + return mbi, ax.find(role="menu_item", root_id=mbi.id, max_results=60, max_depth=6) + + +def rb_reach_about_dialog(ax): + """panel window (surface 1) -> TypeSwitch menu (surface 2) -> About dialog. + + Returns the About dialog `window` element (AXSubrole == "AXDialog") or None.""" + rb_enter_main_window(ax) + _mbi, items = open_menu(ax, "TypeSwitch") + about = item_named(items, "About TypeSwitch") + assert about is not None, ( + "TypeSwitch menu must expose a menu item named 'About TypeSwitch'; got " + f"{names_of(items)}") + press_safe(ax, about) + time.sleep(2.5) + return dialog_window(ax) + + +def press_safe(ax, item): + """AXPress a menu item, refusing anything on the destructive NEVER_PRESS list.""" + name = item.name or "" + assert name not in NEVER_PRESS, f"refusing to press destructive menu item {name!r}" + return ax.action(item.id, "AXPress") + + +def names_of(items): + return [(i.name or "") for i in items] + + +def item_named(items, name): + for i in items: + if (i.name or "") == name: + return i + return None + + +def submenu_items(ax, parent_item, max_results=40, max_depth=4): + """The menu_item children exposed under an already-pressed submenu parent.""" + return ax.find(role="menu_item", root_id=parent_item.id, + max_results=max_results, max_depth=max_depth) + + +def dialog_window(ax): + """The first top-level window whose AXSubrole is AXDialog (the About window).""" + for w in ax.find(role="window", max_results=8, max_depth=2): + if (ax.get(w.id, ["AXSubrole"]).get("AXSubrole") or "") == "AXDialog": + return w + return None + + +def top_windows(ax): + return ax.find(role="window", max_results=8, max_depth=2) + + +def missing(expected, observed): + return [e for e in expected if e not in observed] + + +# ── M10 ───────────────────────────────────────────────────────────────────────── +class TestMenuBarInventory: + """The app's two menu bars — the only existence-only test in this module.""" + + @pytest.mark.rb(depth=0, jump_kind="none") + def test_menu_bar_inventory(self, ax): + bars = ax.find(role="menu_bar", max_results=4, max_depth=1) + assert len(bars) >= 2, ( + "app must expose 2 menu bars: the app menu bar " + f"{APP_MENU_BAR_ITEMS} and the extras bar holding " + f"['{STATUS_ITEM_NAME}']; found {len(bars)}") + + first = names_of(ax.find(role="menu_bar_item", root_id=bars[0].id, + max_results=12, max_depth=2)) + assert first == APP_MENU_BAR_ITEMS, ( + f"first menu_bar items must be exactly {APP_MENU_BAR_ITEMS} in that order; " + f"got {first}") + + last = names_of(ax.find(role="menu_bar_item", root_id=bars[-1].id, + max_results=12, max_depth=2)) + assert last == [STATUS_ITEM_NAME], ( + f"last menu_bar (AXExtrasMenuBar) must hold exactly one item named " + f"['{STATUS_ITEM_NAME}']; got {last}") + helpers.dismiss_menus(ax) + + +# ── M1 ────────────────────────────────────────────────────────────────────────── +class TestStatusItem: + """The status item is NOT a menu: its AXPress reveals the panel window.""" + + @pytest.mark.rb(depth=1, jump_kind="reach", + expect="status item 'Keyboard' exposes only AXPress and no menu_item " + "children; pressing it reveals the 600x500 panel window whose " + "button 'Refresh (⌘R)' appears in the AX tree") + def test_status_item_press_opens_window_not_menu(self, ax): + si = status_item(ax) + assert si is not None, ( + "expected an extras menu bar holding exactly one menu_bar_item " + f"named '{STATUS_ITEM_NAME}'") + assert si.name == STATUS_ITEM_NAME, ( + f"status item must be named '{STATUS_ITEM_NAME}'; got {si.name!r}") + assert sorted(si.actions) == ["AXPress"], ( + f"status item '{STATUS_ITEM_NAME}' actions must be exactly ['AXPress']; " + f"got {sorted(si.actions)}") + assert len(ax.find(role="menu_item", root_id=si.id, + max_results=20, max_depth=6)) == 0, ( + f"status item '{STATUS_ITEM_NAME}' must expose no menu_item children " + "before its press") + + before = kit.rb_showing(ax) + w = rb_enter_main_window(ax) # nav — menu bar -> panel window + after = kit.rb_showing(ax) + + menu_kids = ax.find(role="menu_item", root_id=si.id, + max_results=20, max_depth=6) + assert w is not None, ( + f"pressing the status item '{STATUS_ITEM_NAME}' must reveal the panel window") + assert len(menu_kids) == 0, ( + f"'{STATUS_ITEM_NAME}' must open a WINDOW, not a menu — expected 0 menu_item " + f"children after the press, got {names_of(menu_kids)}") + assert kit.rb_reach(before, after, target="Refresh (⌘R)"), ( + "pressing the status item must make the panel's button 'Refresh (⌘R)' appear " + "in the AX tree (it must be absent before the press)") + + +# ── M3 / M2 / M2b ─────────────────────────────────────────────────────────────── +class TestAppMenu: + """The `TypeSwitch` application menu and its About dialog.""" + + + @pytest.mark.rb(depth=2, jump_kind="reach", + expect="panel -> TypeSwitch menu -> 'About TypeSwitch' opens a NEW " + "window with AXSubrole='AXDialog' showing 'Version 0.3.5 (1)'") + def test_about_typeswitch_opens_dialog(self, ax): + w = rb_enter_main_window(ax) # surface 1 — the panel window + assert w is not None, "could not reveal the TypeSwitch panel window" + before = kit.rb_showing(ax) + + _mbi, items = open_menu(ax, "TypeSwitch") # surface 2 — the dropdown + about = item_named(items, "About TypeSwitch") + assert about is not None, ( + "TypeSwitch menu must expose a menu item named 'About TypeSwitch'; got " + f"{names_of(items)}") + wins_before = len(top_windows(ax)) + press_safe(ax, about) + time.sleep(2.5) + after = kit.rb_showing(ax) + + screenshot_assert( + "menus_about_dialog", + "The small standard macOS About window (284x187) is visible, showing the " + "TypeSwitch app icon, the app name 'TypeSwitch', the line " + "'Version 0.3.5 (1)' and 'Copyright © 2024 ygsgdbd. All rights reserved.'", + RESULTS_DIR) + + wins_after = top_windows(ax) + dlg = dialog_window(ax) + helpers.dismiss_menus(ax) + + assert len(wins_after) > wins_before, ( + "pressing 'About TypeSwitch' must add a NEW top-level window; window count " + f"stayed at {wins_before}") + assert dlg is not None, ( + "the About window must be a `window` with AXSubrole == 'AXDialog'; observed " + f"subroles: " + f"{[ax.get(x.id, ['AXSubrole']).get('AXSubrole') for x in wins_after]}") + assert kit.rb_reach(before, after, target="Version 0.3.5", source=None), ( + "the About dialog's label 'Version 0.3.5 (1)' must APPEAR after pressing " + "'About TypeSwitch' (no 'Version' text exists anywhere before it)") + + @pytest.mark.rb(depth=2, jump_kind="value", + expect="About dialog texts are 'TypeSwitch', 'Version 0.3.5 (1)' and " + "'Copyright © 2024 ygsgdbd. All rights reserved.', plus an " + "image named 'TypeSwitch icon'") + def test_about_dialog_text_values(self, ax): + dlg = rb_reach_about_dialog(ax) # panel -> menu -> About dialog + assert dlg is not None, ( + "'About TypeSwitch' must open a window with AXSubrole == 'AXDialog'") + + labels = [e.value for e in ax.find(role="label", root_id=dlg.id, + max_results=40, max_depth=8) if e.value] + images = names_of(ax.find(role="image", root_id=dlg.id, + max_results=20, max_depth=8)) + version = next((v for v in labels if str(v).startswith(ABOUT_VERSION_PREFIX)), + None) + helpers.dismiss_menus(ax) + + assert kit.rb_value(labels, ABOUT_NAME), ( + f"About dialog must show the app name '{ABOUT_NAME}'; labels={labels}") + assert version is not None and kit.rb_value(version, ABOUT_VERSION_PREFIX), ( + f"About dialog must show a label starting with '{ABOUT_VERSION_PREFIX}' " + f"(observed 'Version 0.3.5 (1)'); labels={labels}") + assert kit.rb_value(labels, ABOUT_COPYRIGHT), ( + f"About dialog must show '{ABOUT_COPYRIGHT}'; labels={labels}") + assert kit.rb_value(images, ABOUT_IMAGE), ( + f"About dialog must contain an image named '{ABOUT_IMAGE}'; images={images}") + + +# ── M5 ────────────────────────────────────────────────────────────────────────── + + + +# ── M4 / M6 ───────────────────────────────────────────────────────────────────── + + + + +# ── M7 ────────────────────────────────────────────────────────────────────────── +class TestHelpMenu: + """The `Help` menu holds exactly one item.""" + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="Help menu contains exactly one item named 'TypeSwitch Help'") + def test_help_menu_single_item(self, ax): + _mbi, items = open_menu(ax, "Help") # nav — menu bar -> dropdown + names = names_of(items) + helpers.dismiss_menus(ax) + + assert len(items) == 1, ( + f"Help menu must hold exactly 1 menu_item ({HELP_MENU_ITEMS}); got " + f"{len(items)}: {names}") + assert kit.rb_value(names, HELP_MENU_ITEMS), ( + f"Help menu items must be exactly {HELP_MENU_ITEMS}; got {names}") + + +# ── M8 ────────────────────────────────────────────────────────────────────────── + + + +# ── M9 ────────────────────────────────────────────────────────────────────────── +class TestFileMenu: + """The `File` menu holds exactly `Close` and `Close All` (never pressed — recon: + `File ▸ Close` does NOT close the panel).""" + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="File menu contains exactly the two items 'Close' and " + "'Close All'") + def test_file_menu_items(self, ax): + _mbi, items = open_menu(ax, "File") # nav — menu bar -> dropdown + names = names_of(items) + helpers.dismiss_menus(ax) + + assert len(items) == 2, ( + f"File menu must hold exactly 2 menu_items {FILE_MENU_ITEMS}; got " + f"{len(items)}: {names}") + assert kit.rb_value(sorted(names), sorted(FILE_MENU_ITEMS)), ( + f"File menu items must be exactly {FILE_MENU_ITEMS}; got {names}") diff --git a/macos/ygsgdbd-typeswitch/tests/test_ax_states.py b/macos/ygsgdbd-typeswitch/tests/test_ax_states.py new file mode 100644 index 0000000000000000000000000000000000000000..b290f1df1ca6b2c5331a9f27caac62176f0338b9 --- /dev/null +++ b/macos/ygsgdbd-typeswitch/tests/test_ax_states.py @@ -0,0 +1,884 @@ +"""test_ax_states.py — AX STATE verification for TypeSwitch (macos-ygsgdbd-typeswitch). + +Golden model: recon.md `## STATE` (+ `## AX_TREE`, `## VISUAL`). + +Three stateful controls live OUTSIDE the reset-on-relaunch defaults and therefore +SURVIVE the per-test app relaunch (app-group defaults suite + `SMAppService`): + * the "Global Quick Switch" flag, + * the per-app input-method picker selection, + * the "Launch at Login" flag. +So NO test here asserts an absolute initial value for those. Every one of them +reads `before` -> acts -> asserts the FLIP -> acts again to RESTORE `before`. + +Reveal is always `rb_enter_main_window(ax)` on the plain `ax` fixture: +`ax_with_reset` / `helpers.ensure_panel_open()` measure 39.5 s on this app and blow +the runner's 30 s per-test timeout. + +SAFETY: never presses `Quit (⌘Q)` / `Quit TypeSwitch` / `Hide TypeSwitch`, never +sends ⌘Q, never presses the `Record Shortcut` recorder field, never kills a process. +""" + +# ---- paste verbatim into every test module ------------------------------------- +import os, json, re, subprocess, time +import pytest +import rb_testgen_kit as kit +import verifier_helpers as helpers + +CTRL_LABELS = { + "Global Quick Switch", + "Use shortcut to quickly switch between input methods", + "Launch at Login", + "Automatically start TypeSwitch when you log in", +} + + +def screenshot_assert(test_name, description, results_dir=None): + results_dir = results_dir or os.environ.get("RESULTS_DIR", "results") + 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 + af = os.path.join(ss_dir, "assertions.json") + data = {} + if os.path.exists(af): + try: + data = json.load(open(af)) + except Exception: + data = {} + data[f"{test_name}.png"] = description + with open(af, "w") as f: + json.dump(data, f, indent=2) + + +def _main_window(ax): + """The app's content window: a top-level window that owns a group subtree.""" + for w in ax.find(role="window", max_results=6, max_depth=2): + if ax.find(role="group", root_id=w.id, max_results=1, max_depth=3): + return w + return None + + +def _wait_window(ax, timeout=1.2): + end = time.time() + timeout + while time.time() < end: + w = _main_window(ax) + if w is not None: + return w + time.sleep(0.15) + return None + + +def rb_enter_main_window(ax, attempts=4): + """Reveal the app's main UI (surface crossing: menu bar -> window). + + Portable: an already-open window wins; otherwise press status-item / menu-bar + items (the extras bar FIRST), then CG-click, then ax.ensure_ui_visible().""" + w = _main_window(ax) + if w is not None: + return w + bars = ax.find(role="menu_bar", max_results=4, max_depth=1) + ordered = [] + for bar in reversed(bars): # extras (status-item) menu bar first + ordered += [i for i in ax.find(role="menu_bar_item", root_id=bar.id, + max_results=12) + if (i.name or "") != "Apple"] + for item in ordered: + for _ in range(attempts): + ax.action(item.id, "AXPress") + w = _wait_window(ax) + if w is not None: + return w + helpers.dismiss_menus(ax) + for item in ordered: + ax.click_element_cg(item.id) + w = _wait_window(ax) + if w is not None: + return w + helpers.dismiss_menus(ax) + ax.ensure_ui_visible() + return _main_window(ax) + + +def status_item(ax): + """The menu-bar-extra item that owns the app UI (last menu bar, first item).""" + bars = ax.find(role="menu_bar", max_results=4, max_depth=1) + for bar in reversed(bars): + items = [i for i in ax.find(role="menu_bar_item", root_id=bar.id, max_results=12) + if (i.name or "") != "Apple"] + if len(items) == 1: # a status/extras bar holds exactly one item + return items[0] + return None + + +def frame(ax, el_id): + """(x, y, w, h) floats parsed out of AXPosition / AXSize.""" + d = ax.get(el_id, ["AXPosition", "AXSize"]) + + def num(s, key): + m = re.search(key + r":(-?[\d.]+)", str(s)) + return float(m.group(1)) if m else None + + return (num(d.get("AXPosition"), "x"), num(d.get("AXPosition"), "y"), + num(d.get("AXSize"), "w"), num(d.get("AXSize"), "h")) + + +def search_field(ax, w): + """The app-list search field: the text field whose placeholder mentions search.""" + tfs = ax.find(role="text_field", root_id=w.id, max_results=8, max_depth=12) + for t in tfs: + ph = (ax.get(t.id, ["AXPlaceholderValue"]).get("AXPlaceholderValue") or "") + if "Search" in ph or "搜索" in ph: + return t + return tfs[0] if tfs else None + + +def app_names(ax, w): + """Visible app-row names = every label that is not one of the 4 control labels.""" + return [e.value for e in ax.find(role="label", root_id=w.id, + max_results=300, max_depth=12) + if e.value and e.value not in CTRL_LABELS] + + +def set_search(ax, w, query, settle=0.8): + tf = search_field(ax, w) + ax.set_value(tf.id, query) + time.sleep(settle) + return tf + + +def toggle_for(ax, w, label_text): + """The checkbox/toggle belonging to the settings row labelled `label_text` + (pairs by nearest vertical centre — robust to child ordering).""" + lab = None + for e in ax.find(role="label", root_id=w.id, max_results=300, max_depth=12): + if e.value == label_text: + lab = e + break + boxes = ax.find(role="checkbox", root_id=w.id, max_results=10, max_depth=12) + if not boxes: + return None + if lab is None: + return boxes[0] + ly = (frame(ax, lab.id)[1] or 0) + (frame(ax, lab.id)[3] or 0) / 2.0 + best, bestd = None, 1e9 + for b in boxes: + by = (frame(ax, b.id)[1] or 0) + (frame(ax, b.id)[3] or 0) / 2.0 + if abs(by - ly) < bestd: + best, bestd = b, abs(by - ly) + return best + + +def toggle_value(ax, el_id): + return ax.get(el_id, ["AXValue"]).get("AXValue") + + +def named_button(ax, w, keyword): + for b in ax.find(role="button", root_id=w.id, max_results=30, max_depth=12): + if b.name and keyword.lower() in b.name.lower(): + return b + return None +# -------------------------------------------------------------------------------- + + +# ── observed golden constants (recon ## TEXT / ## STATE) ───────────────────────── +QUICK_SWITCH = "Global Quick Switch" +LAUNCH_AT_LOGIN = "Launch at Login" +SHORTCUT_TEXT = "⌃⇧Space" +RECORDER_PLACEHOLDER = "Record Shortcut" +DEFAULT_OPTION_WORDS = ("default", "默认", "預設", "预设") + + +# ── module-local state readers (semantic locators only: label/name + role) ─────── +def window_count(ax): + """Number of top-level windows the app currently exposes.""" + return len(ax.find(role="window", max_results=8, max_depth=2)) + + +def text_fields(ax, w): + """Every text field inside the panel (search field + shortcut recorder).""" + return ax.find(role="text_field", root_id=w.id, max_results=8, max_depth=12) + + +def text_field_values(ax, w): + """AXValue of every text field inside the panel.""" + return [ax.get(t.id, ["AXValue"]).get("AXValue") for t in text_fields(ax, w)] + + +def recorder_field(ax, w): + """The shortcut-recorder text field — the text field that is NOT the search + field (its placeholder is the record prompt, not the search prompt).""" + for t in text_fields(ax, w): + ph = (ax.get(t.id, ["AXPlaceholderValue"]).get("AXPlaceholderValue") or "") + if "Search" in ph or "搜索" in ph: + continue + return t + return None + + +def toggle_state(ax, label_text): + """(window, toggle_element, AXValue) of the settings-row toggle labelled + `label_text`, freshly re-resolved (SwiftUI rebuilds rows after a flip).""" + w = _main_window(ax) + assert w is not None, ( + "expected the TypeSwitch panel window (600x500 system dialog) to be open — " + "rb_enter_main_window() must reveal it via the 'Keyboard' status item") + tg = toggle_for(ax, w, label_text) + assert tg is not None, ( + f"expected a toggle (role=checkbox, AXSubrole=AXToggle) on the " + f"{label_text!r} settings row") + return w, tg, toggle_value(ax, tg.id) + + +def flip_toggle(ax, label_text, settle=1.2): + """AXPress the `label_text` toggle once; return its AXValue after `settle` s.""" + _w, tg, _v = toggle_state(ax, label_text) + ax.action(tg.id, "AXPress") + time.sleep(settle) + _w2, _tg2, after = toggle_state(ax, label_text) + return after + + +def normalise_toggle(ax, label_text, target, settle=1.2): + """Bring the `label_text` toggle to `target` (0 or 1); return the AXValue seen.""" + _w, tg, v = toggle_state(ax, label_text) + if int(v or 0) == int(target): + return v + ax.action(tg.id, "AXPress") + time.sleep(settle) + _w2, _tg2, after = toggle_state(ax, label_text) + return after + + +def restore_toggle_quietly(ax, label_text, target, settle=1.2): + """Best-effort restore of a PERSISTENT toggle to its pre-test value. Never + raises — a restore problem must not mask the test's own verdict.""" + try: + normalise_toggle(ax, label_text, target, settle=settle) + except Exception: + pass + + +def _is_default_option(name): + n = (name or "").strip().lower() + return any(word in n for word in DEFAULT_OPTION_WORDS) + + +def row_pickers(ax, w): + """Every per-app-row picker (role=radiogroup), ordered top-to-bottom by screen y.""" + rgs = ax.find(role="radiogroup", root_id=w.id, max_results=30, max_depth=12) + return sorted(rgs, key=lambda r: (frame(ax, r.id)[1] or 0.0)) + + +def rows(ax, w): + """[(app_name, picker_radiogroup)] for every realized app row, top-to-bottom. + A row's name label and its picker share a vertical centre — pairing by that + centre is framework-neutral (no child index, no tree path).""" + labels = [e for e in ax.find(role="label", root_id=w.id, + max_results=300, max_depth=12) + if e.value and e.value not in CTRL_LABELS] + lab_y = [] + for lab in labels: + f = frame(ax, lab.id) + lab_y.append((lab, (f[1] or 0.0) + (f[3] or 0.0) / 2.0)) + out = [] + for rg in row_pickers(ax, w): + f = frame(ax, rg.id) + y = (f[1] or 0.0) + (f[3] or 0.0) / 2.0 + best, bestd = None, 1e9 + for lab, ly in lab_y: + if abs(ly - y) < bestd: + best, bestd = lab, abs(ly - y) + out.append(((best.value if best is not None else ""), rg)) + return out + + +def picker_for_app(ax, w, app_name): + """The picker (radiogroup) of the app row named `app_name`.""" + for name, rg in rows(ax, w): + if name == app_name: + return rg + return None + + +def picker_options(ax, rg): + """(default_option, other_option) radios of one picker, left-to-right by x.""" + rs = sorted(ax.find(role="radio", root_id=rg.id, max_results=6, max_depth=3), + key=lambda r: (frame(ax, r.id)[0] or 0.0)) + if not rs: + return None, None + d = next((r for r in rs if _is_default_option(r.name)), rs[0]) + o = next((r for r in rs if r.id != d.id), None) + return d, o + + +def radio_value(ax, el_id): + return ax.get(el_id, ["AXValue"]).get("AXValue") + + +def picker_pair(ax, w, app_name): + """((default_value, other_value), default_el, other_el) for the row named + `app_name`, re-resolved from scratch every call (the segmented picker is + rebuilt after each AXPress, which invalidates older element handles).""" + rg = picker_for_app(ax, w, app_name) + assert rg is not None, ( + f"expected an app row labelled {app_name!r} owning a 2-option picker " + f"(role=radiogroup) in the filtered list") + d, o = picker_options(ax, rg) + assert d is not None and o is not None, ( + f"expected the {app_name!r} row picker to expose exactly 2 radio options " + f"('Default' plus one input source such as 'U.S.')") + return (radio_value(ax, d.id), radio_value(ax, o.id)), d, o + + +def select_default_quietly(ax, app_name, settle=0.8): + """Best-effort: put the `app_name` row picker back on its 'Default' option.""" + try: + w = _main_window(ax) + if w is None: + return + (dv, _ov), d, _o = picker_pair(ax, w, app_name) + if int(dv or 0) != 1: + ax.action(d.id, "AXPress") + time.sleep(settle) + except Exception: + pass + + +def clear_search_quietly(ax, settle=0.4): + try: + w = _main_window(ax) + if w is not None: + set_search(ax, w, "", settle=settle) + except Exception: + pass + + +class TestSettingsToggleStates: + """The two settings-row toggles (role=checkbox, AXSubrole=AXToggle). Both flags + PERSIST across the per-test relaunch, so every test is read-flip-restore.""" + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="'Global Quick Switch' toggle button (AXSubrole=AXToggle, " + "AXRoleDescription='toggle button', AXEnabled=True) flips its " + "AXValue between 0 and 1 on AXPress; then restored") + def test_quick_switch_toggle_checked_flips(self, ax): + w = rb_enter_main_window(ax) + assert w is not None, ( + "expected 1 panel window after pressing the 'Keyboard' status item") + tg = toggle_for(ax, w, QUICK_SWITCH) + assert tg is not None, ( + f"expected a toggle (role=checkbox) on the {QUICK_SWITCH!r} settings row") + + attrs = ax.get(tg.id, ["AXSubrole", "AXRoleDescription", "AXEnabled"]) + assert attrs.get("AXSubrole") == "AXToggle", ( + f"{QUICK_SWITCH!r} control AXSubrole must be 'AXToggle', got " + f"{attrs.get('AXSubrole')!r}") + assert attrs.get("AXRoleDescription") == "toggle button", ( + f"{QUICK_SWITCH!r} control AXRoleDescription must be 'toggle button', got " + f"{attrs.get('AXRoleDescription')!r}") + assert attrs.get("AXEnabled") is True, ( + f"{QUICK_SWITCH!r} toggle AXEnabled must be True, got " + f"{attrs.get('AXEnabled')!r}") + assert "AXPress" in (tg.actions or []), ( + f"{QUICK_SWITCH!r} toggle must expose the 'AXPress' action, got " + f"{tg.actions!r}") + + before = toggle_value(ax, tg.id) + assert before is not None, ( + f"{QUICK_SWITCH!r} toggle must report an AXValue of 0 or 1, got None") + try: + after = flip_toggle(ax, QUICK_SWITCH, settle=1.2) + assert kit.rb_flip(before, after), ( + f"AXPress on the {QUICK_SWITCH!r} toggle must CHANGE its AXValue " + f"(observed {before!r} -> {after!r}; expected 0->1 or 1->0)") + assert {int(before), int(after)} == {0, 1}, ( + f"the {QUICK_SWITCH!r} toggle's two states must be exactly 0 and 1, " + f"observed before={before!r} after={after!r}") + finally: + restore_toggle_quietly(ax, QUICK_SWITCH, before) + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="quick switch 0->1 CONSEQUENCE: panel text_field count 1 -> 2; " + "the new field has AXValue='⌃⇧Space' and " + "AXPlaceholderValue='Record Shortcut'; then restored") + def test_quick_switch_on_adds_shortcut_recorder(self, ax): + w = rb_enter_main_window(ax) + assert w is not None, ( + "expected 1 panel window after pressing the 'Keyboard' status item") + _w, _tg, original = toggle_state(ax, QUICK_SWITCH) + try: + normalise_toggle(ax, QUICK_SWITCH, 0, settle=1.2) + w = _main_window(ax) + count_before = len(text_fields(ax, w)) + assert count_before == 1, ( + "with 'Global Quick Switch' OFF the panel must expose exactly 1 " + f"text_field (the search field), found {count_before}") + + after_val = flip_toggle(ax, QUICK_SWITCH, settle=1.2) + assert int(after_val or 0) == 1, ( + f"{QUICK_SWITCH!r} AXValue must be 1 after turning it ON, got " + f"{after_val!r}") + w = _main_window(ax) + assert w is not None, ( + "the panel window must stay open after turning 'Global Quick Switch' ON") + count_after = len(text_fields(ax, w)) + + assert kit.rb_flip(count_before, count_after), ( + "turning 'Global Quick Switch' ON must CHANGE the panel's text_field " + f"count (observed {count_before} -> {count_after}; expected 1 -> 2)") + assert count_after == 2, ( + "with 'Global Quick Switch' ON the panel must expose exactly 2 " + f"text_fields (search + shortcut recorder), found {count_after}") + + rec = recorder_field(ax, w) + assert rec is not None, ( + "expected a second text_field (the shortcut recorder) once " + "'Global Quick Switch' is ON") + rd = ax.get(rec.id, ["AXValue", "AXPlaceholderValue"]) + assert rd.get("AXValue") == SHORTCUT_TEXT, ( + f"the shortcut recorder AXValue must be {SHORTCUT_TEXT!r}, got " + f"{rd.get('AXValue')!r}") + assert rd.get("AXPlaceholderValue") == RECORDER_PLACEHOLDER, ( + f"the shortcut recorder AXPlaceholderValue must be " + f"{RECORDER_PLACEHOLDER!r}, got {rd.get('AXPlaceholderValue')!r}") + + screenshot_assert( + "states_test_quick_switch_on_adds_shortcut_recorder", + "Global Quick Switch is ON in the dark 600x500 TypeSwitch panel " + "anchored top-right under the menu bar. On the 'Global Quick Switch' " + "row (above 'Launch at Login') the switch on the right is in its ON / " + "filled position, and a shortcut recorder field showing the key " + "combination ⌃⇧Space is now displayed immediately to the LEFT " + "of that switch. The 'Launch at Login' row below is unchanged, and the " + "app list with its Default | U.S. pickers plus the 'Refresh (⌘R)' " + "and 'Quit (⌘Q)' buttons are still visible.") + finally: + restore_toggle_quietly(ax, QUICK_SWITCH, original) + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="quick switch 1->0 CONSEQUENCE: panel text_field count 2 -> 1 and " + "no field with AXValue='⌃⇧Space' remains; then restored") + def test_quick_switch_off_removes_shortcut_recorder(self, ax): + w = rb_enter_main_window(ax) + assert w is not None, ( + "expected 1 panel window after pressing the 'Keyboard' status item") + _w, _tg, original = toggle_state(ax, QUICK_SWITCH) + try: + normalise_toggle(ax, QUICK_SWITCH, 1, settle=1.2) + w = _main_window(ax) + count_before = len(text_fields(ax, w)) + assert count_before == 2, ( + "with 'Global Quick Switch' ON the panel must expose exactly 2 " + f"text_fields (search + '{SHORTCUT_TEXT}' recorder), found {count_before}") + assert SHORTCUT_TEXT in text_field_values(ax, w), ( + f"with 'Global Quick Switch' ON a text_field with AXValue " + f"{SHORTCUT_TEXT!r} must be present, values were " + f"{text_field_values(ax, w)!r}") + + after_val = flip_toggle(ax, QUICK_SWITCH, settle=1.2) + assert int(after_val or 0) == 0, ( + f"{QUICK_SWITCH!r} AXValue must be 0 after turning it OFF, got " + f"{after_val!r}") + w = _main_window(ax) + assert w is not None, ( + "the panel window must stay open after turning 'Global Quick Switch' OFF") + count_after = len(text_fields(ax, w)) + values_after = text_field_values(ax, w) + + assert kit.rb_flip(count_before, count_after), ( + "turning 'Global Quick Switch' OFF must CHANGE the panel's text_field " + f"count (observed {count_before} -> {count_after}; expected 2 -> 1)") + assert count_after == 1, ( + "with 'Global Quick Switch' OFF only the search text_field must remain " + f"(expected 1), found {count_after}") + assert SHORTCUT_TEXT not in values_after, ( + f"no text_field may keep AXValue {SHORTCUT_TEXT!r} after 'Global Quick " + f"Switch' is OFF, values were {values_after!r}") + finally: + restore_toggle_quietly(ax, QUICK_SWITCH, original) + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="'Launch at Login' toggle (a DIFFERENT element than the quick-switch " + "toggle) flips AXValue between 0 and 1 with no error sheet; restored") + def test_launch_at_login_toggle_flips(self, ax): + w = rb_enter_main_window(ax) + assert w is not None, ( + "expected 1 panel window after pressing the 'Keyboard' status item") + login_tg = toggle_for(ax, w, LAUNCH_AT_LOGIN) + quick_tg = toggle_for(ax, w, QUICK_SWITCH) + assert login_tg is not None, ( + f"expected a toggle (role=checkbox) on the {LAUNCH_AT_LOGIN!r} settings row") + assert quick_tg is not None, ( + f"expected a toggle (role=checkbox) on the {QUICK_SWITCH!r} settings row") + assert login_tg.id != quick_tg.id, ( + f"{LAUNCH_AT_LOGIN!r} and {QUICK_SWITCH!r} must be TWO DIFFERENT toggle " + "elements (the panel exposes exactly 2 checkboxes, one per settings row)") + assert ax.get(login_tg.id, ["AXEnabled"]).get("AXEnabled") is True, ( + f"{LAUNCH_AT_LOGIN!r} toggle AXEnabled must be True") + + before = toggle_value(ax, login_tg.id) + assert before is not None, ( + f"{LAUNCH_AT_LOGIN!r} toggle must report an AXValue of 0 or 1, got None") + try: + after = flip_toggle(ax, LAUNCH_AT_LOGIN, settle=2.0) + assert kit.rb_flip(before, after), ( + f"AXPress on the {LAUNCH_AT_LOGIN!r} toggle must CHANGE its AXValue " + f"(observed {before!r} -> {after!r}; expected 0->1 or 1->0)") + assert {int(before), int(after)} == {0, 1}, ( + f"the {LAUNCH_AT_LOGIN!r} toggle's two states must be exactly 0 and 1, " + f"observed before={before!r} after={after!r}") + sheets = ax.find(role="sheet", max_results=3, max_depth=4) + assert len(sheets) == 0, ( + "toggling 'Launch at Login' must NOT present an error sheet " + f"(expected 0 sheets, found {len(sheets)})") + finally: + restore_toggle_quietly(ax, LAUNCH_AT_LOGIN, before, settle=2.0) + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="the two toggles are independent: flipping 'Global Quick Switch' " + "changes only its own AXValue; 'Launch at Login' keeps its value") + def test_toggles_are_independent(self, ax): + w = rb_enter_main_window(ax) + assert w is not None, ( + "expected 1 panel window after pressing the 'Keyboard' status item") + _w1, quick_tg, quick_before = toggle_state(ax, QUICK_SWITCH) + _w2, _login_tg, login_before = toggle_state(ax, LAUNCH_AT_LOGIN) + assert quick_before is not None and login_before is not None, ( + "both settings toggles must report an AXValue of 0 or 1, got " + f"quick={quick_before!r} login={login_before!r}") + try: + ax.action(quick_tg.id, "AXPress") + time.sleep(1.2) + _w3, _tg3, quick_after = toggle_state(ax, QUICK_SWITCH) + _w4, _tg4, login_after = toggle_state(ax, LAUNCH_AT_LOGIN) + + expected_quick = 1 - int(quick_before or 0) + assert kit.rb_value(int(quick_after or 0), expected_quick), ( + f"after one AXPress the {QUICK_SWITCH!r} AXValue must be " + f"{expected_quick} (was {quick_before!r}), got {quick_after!r}") + assert kit.rb_value(int(login_after or 0), int(login_before or 0)), ( + f"pressing the {QUICK_SWITCH!r} toggle must leave {LAUNCH_AT_LOGIN!r} " + f"AXValue unchanged at {login_before!r}, got {login_after!r}") + assert quick_after != quick_before, ( + f"{QUICK_SWITCH!r} AXValue must differ from its pre-press value " + f"{quick_before!r}, got {quick_after!r}") + assert login_after == login_before, ( + f"{LAUNCH_AT_LOGIN!r} AXValue must stay exactly {login_before!r}, got " + f"{login_after!r}") + finally: + restore_toggle_quietly(ax, QUICK_SWITCH, quick_before) + + +class TestPerAppPickerRadioStates: + """Per-app input-method pickers: role=radiogroup with 2 role=radio options + ('Default' + one input source). The selection PERSISTS across the relaunch, so + each test normalises to 'Default' first and restores 'Default' afterwards.""" + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="one app row's picker flips (Default=1, other=0) -> (Default=0, " + "other=1): exactly one radio CHECKED at a time; restored to Default") + def test_picker_radio_group_is_mutually_exclusive(self, ax): + w = rb_enter_main_window(ax) + assert w is not None, ( + "expected 1 panel window after pressing the 'Keyboard' status item") + app_name = None + try: + set_search(ax, w, "Calculator") + w = _main_window(ax) + assert w is not None, "the panel must stay open while filtering the app list" + listed = rows(ax, w) + assert len(listed) == 1, ( + "searching 'Calculator' must filter the list down to exactly 1 app row " + f"with 1 radiogroup, found {len(listed)} ({[n for n, _ in listed]!r})") + app_name = listed[0][0] + + # normalise the persistent selection to 'Default' + (dv0, _ov0), d0, _o0 = picker_pair(ax, w, app_name) + if int(dv0 or 0) != 1: + ax.action(d0.id, "AXPress") + time.sleep(0.8) + + before, _d1, other = picker_pair(ax, w, app_name) + assert before == (1, 0), ( + f"after selecting 'Default' the {app_name!r} picker must read " + f"(Default=1, other=0), got {before!r}") + + ax.action(other.id, "AXPress") + time.sleep(1.0) + after, d2, o2 = picker_pair(ax, w, app_name) + + assert kit.rb_flip(before, after), ( + f"pressing the non-Default radio of the {app_name!r} picker must CHANGE " + f"the (Default, other) value pair (observed {before!r} -> {after!r}; " + "expected (1, 0) -> (0, 1))") + assert after == (0, 1), ( + f"the {app_name!r} picker must read (Default=0, other=1) after selecting " + f"the non-Default option, got {after!r}") + assert int(radio_value(ax, o2.id) or 0) == 1, ( + "the pressed radio's AXValue must be exactly 1 (CHECKED), got " + f"{radio_value(ax, o2.id)!r}") + assert int(radio_value(ax, d2.id) or 0) == 0, ( + "the 'Default' radio's AXValue must be exactly 0 (unchecked) once the " + f"other option is selected, got {radio_value(ax, d2.id)!r}") + + screenshot_assert( + "states_test_picker_radio_group_is_mutually_exclusive", + "The dark 600x500 TypeSwitch panel has 'Calculator' typed in the search " + "field at the top and exactly ONE app row visible: the Calculator icon, " + "the name 'Calculator', and a small two-segment picker on the right. In " + "that picker the NON-Default segment ('U.S.') is now highlighted / " + "selected and the 'Default' segment is NOT highlighted — exactly one " + "segment is selected. Below, the 'Global Quick Switch' and 'Launch at " + "Login' rows with their switches and the 'Refresh (⌘R)' / " + "'Quit (⌘Q)' buttons are unchanged.") + finally: + if app_name: + select_default_quietly(ax, app_name) + clear_search_quietly(ax) + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="picker selection is PER ROW: row 1 other radio == 1 while row 2 " + "Default radio stays == 1; both restored to Default") + def test_picker_selection_is_per_row(self, ax): + w = rb_enter_main_window(ax) + assert w is not None, ( + "expected 1 panel window after pressing the 'Keyboard' status item") + names = [] + try: + set_search(ax, w, "cal") + w = _main_window(ax) + assert w is not None, "the panel must stay open while filtering the app list" + listed = rows(ax, w) + names = [n for n, _ in listed] + assert len(listed) == 2, ( + "searching 'cal' must show exactly 2 app rows ('Calculator' and " + f"'Calendar'), found {len(listed)} ({names!r})") + first, second = names[0], names[1] + assert first != second, ( + f"the 2 filtered rows must be distinct apps, got {names!r}") + + # normalise BOTH persistent selections to 'Default' + for name in (first, second): + (dv, _ov), d, _o = picker_pair(ax, w, name) + if int(dv or 0) != 1: + ax.action(d.id, "AXPress") + time.sleep(0.6) + (d1v, o1v), _d1, other1 = picker_pair(ax, w, first) + (d2v, o2v), _d2, _other2 = picker_pair(ax, w, second) + assert (d1v, o1v) == (1, 0) and (d2v, o2v) == (1, 0), ( + "after normalising, BOTH rows must read (Default=1, other=0), got " + f"{first!r}={(d1v, o1v)!r} {second!r}={(d2v, o2v)!r}") + + # select the non-Default option in the FIRST row only + ax.action(other1.id, "AXPress") + time.sleep(1.0) + (d1v2, o1v2), _d1b, _o1b = picker_pair(ax, w, first) + (d2v2, o2v2), _d2b, _o2b = picker_pair(ax, w, second) + + assert kit.rb_value(int(o1v2 or 0), 1), ( + f"row 1 ({first!r}) non-Default radio AXValue must be 1 (CHECKED), got " + f"{o1v2!r}") + assert kit.rb_value(int(d2v2 or 0), 1), ( + f"row 2 ({second!r}) 'Default' radio AXValue must still be 1 — the " + f"selection is per row, got {d2v2!r}") + assert int(d1v2 or 0) == 0, ( + f"row 1 ({first!r}) 'Default' radio AXValue must be 0 after selecting " + f"the other option, got {d1v2!r}") + assert int(o2v2 or 0) == 0, ( + f"row 2 ({second!r}) non-Default radio AXValue must stay 0 — row 1's " + f"press must not touch it, got {o2v2!r}") + + screenshot_assert( + "states_test_picker_selection_is_per_row", + "The TypeSwitch panel has 'cal' typed in the search field and exactly " + "TWO app rows visible ('Calculator' and 'Calendar', each with its icon " + "and a two-segment Default | U.S. picker on the right). In the FIRST / " + "topmost row the non-Default segment ('U.S.') is highlighted, while in " + "the SECOND row the 'Default' segment is still the highlighted one — " + "proving the input-method selection is stored per app row. The two " + "settings switches at the bottom are unchanged.") + finally: + for name in names: + select_default_quietly(ax, name, settle=0.6) + clear_search_quietly(ax) + + +class TestSearchFieldAndEscapeStates: + """Search-field value state + the two-level Escape semantics.""" + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="search field AXValue flips '' -> 'cal' when set, and back to '' " + "when cleared") + def test_search_field_value_state(self, ax): + w = rb_enter_main_window(ax) + assert w is not None, ( + "expected 1 panel window after pressing the 'Keyboard' status item") + tf = search_field(ax, w) + assert tf is not None, ( + "expected the app-list search field (role=text_field, placeholder " + "'Search Apps... (⌘F)') in the panel") + before = ax.get(tf.id, ["AXValue"]).get("AXValue") + assert before == "", ( + f"on a freshly revealed panel the search field AXValue must be '' (empty), " + f"got {before!r}") + + set_search(ax, w, "cal") + w = _main_window(ax) + assert w is not None, "the panel must stay open while the search field holds text" + tf = search_field(ax, w) + after = ax.get(tf.id, ["AXValue"]).get("AXValue") + assert kit.rb_flip(before, after), ( + f"setting the search field must CHANGE its AXValue (observed {before!r} -> " + f"{after!r}; expected '' -> 'cal')") + assert after == "cal", ( + f"the search field AXValue must be exactly 'cal', got {after!r}") + + set_search(ax, w, "") + w = _main_window(ax) + assert w is not None, "the panel must stay open after clearing the search field" + tf = search_field(ax, w) + restored = ax.get(tf.id, ["AXValue"]).get("AXValue") + assert restored == "", ( + f"clearing the search field must return its AXValue to '' (empty), got " + f"{restored!r}") + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="Escape with text in the search box: AXValue 'cal' -> '' , the panel " + "window STAYS open and the full app list (>=10 rows) is back") + def test_escape_clears_search_but_keeps_panel(self, ax): + w = rb_enter_main_window(ax) + assert w is not None, ( + "expected 1 panel window after pressing the 'Keyboard' status item") + set_search(ax, w, "cal") + w = _main_window(ax) + assert w is not None, "the panel must stay open while the search field holds 'cal'" + tf = search_field(ax, w) + before = ax.get(tf.id, ["AXValue"]).get("AXValue") + assert before == "cal", ( + f"the search field AXValue must be exactly 'cal' before Escape, got {before!r}") + filtered = app_names(ax, w) + assert len(filtered) == 2, ( + f"searching 'cal' must show exactly 2 app rows, found {len(filtered)} " + f"({filtered!r})") + + helpers.send_key(helpers.KC_ESCAPE) + time.sleep(0.8) + + w_after = _main_window(ax) + assert w_after is not None, ( + "Escape while the search box holds text must be consumed by the search box " + "— the panel window must STILL be open (expected 1 window, found 0)") + tf_after = search_field(ax, w_after) + assert tf_after is not None, ( + "the search field must still exist in the panel after Escape") + after = ax.get(tf_after.id, ["AXValue"]).get("AXValue") + assert kit.rb_flip(before, after), ( + f"Escape must CHANGE the search field AXValue (observed {before!r} -> " + f"{after!r}; expected 'cal' -> '')") + assert after == "", ( + f"Escape must clear the search field to '' (empty), got {after!r}") + restored_names = app_names(ax, w_after) + assert len(restored_names) >= 10, ( + "clearing the search must bring the full app list back (>=10 app rows), " + f"found {len(restored_names)} ({restored_names!r})") + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="Escape with an EMPTY search box closes the panel: window count " + "1 -> 0 and no content window remains") + def test_escape_with_empty_search_closes_panel(self, ax): + w = rb_enter_main_window(ax) + assert w is not None, ( + "expected 1 panel window after pressing the 'Keyboard' status item") + tf = search_field(ax, w) + assert tf is not None, "expected the app-list search field in the panel" + if (ax.get(tf.id, ["AXValue"]).get("AXValue") or "") != "": + set_search(ax, w, "") + w = _main_window(ax) + assert w is not None, "the panel must stay open after clearing the search field" + tf = search_field(ax, w) + value = ax.get(tf.id, ["AXValue"]).get("AXValue") + assert value == "", ( + f"the search field AXValue must be '' (empty) before this Escape, got " + f"{value!r}") + + n_before = window_count(ax) + assert n_before == 1, ( + f"the app must expose exactly 1 window (the open panel) before Escape, " + f"found {n_before}") + + helpers.send_key(helpers.KC_ESCAPE) + time.sleep(1.0) + + n_after = window_count(ax) + assert kit.rb_flip(n_before, n_after), ( + "Escape with an empty search box must CHANGE the window count (observed " + f"{n_before} -> {n_after}; expected 1 -> 0)") + assert n_after == 0, ( + f"Escape with an empty search box must close the panel (expected 0 windows, " + f"found {n_after})") + assert _main_window(ax) is None, ( + "no content window may remain after Escape closed the panel") + + +class TestFocusAndEnabledCensus: + """Sole owner of the focus / enabled-census assertions for this app.""" + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="on reveal the search field has AXFocused=True and every " + "interactive widget (2 toggles, search field, Refresh, Quit, both " + "radios of the first picker) has AXEnabled=True") + def test_focus_and_enabled_census(self, ax): + w = rb_enter_main_window(ax) + assert w is not None, ( + "expected 1 panel window after pressing the 'Keyboard' status item") + + tf = search_field(ax, w) + assert tf is not None, ( + "expected the app-list search field (role=text_field, placeholder " + "'Search Apps... (⌘F)') in the panel") + focused = ax.get(tf.id, ["AXFocused"]).get("AXFocused") + assert kit.rb_value(focused, True), ( + "immediately after the panel is revealed the search field AXFocused must be " + f"True (the app auto-focuses it), got {focused!r}") + assert ax.get(tf.id, ["AXEnabled"]).get("AXEnabled") is True, ( + "the search field AXEnabled must be True") + + boxes = ax.find(role="checkbox", root_id=w.id, max_results=10, max_depth=12) + assert len(boxes) == 2, ( + "the panel must expose exactly 2 toggles (role=checkbox): 'Global Quick " + f"Switch' and 'Launch at Login', found {len(boxes)}") + for i, b in enumerate(boxes): + en = ax.get(b.id, ["AXEnabled"]).get("AXEnabled") + assert kit.rb_value(en, True), ( + f"settings toggle #{i + 1} of 2 must have AXEnabled=True, got {en!r}") + + refresh = named_button(ax, w, "Refresh") + quit_btn = named_button(ax, w, "Quit") + assert refresh is not None, ( + "expected a footer button whose title contains 'Refresh' (observed " + "'Refresh (⌘R)')") + assert quit_btn is not None, ( + "expected a footer button whose title contains 'Quit' (observed 'Quit (⌘Q)')") + r_en = ax.get(refresh.id, ["AXEnabled"]).get("AXEnabled") + q_en = ax.get(quit_btn.id, ["AXEnabled"]).get("AXEnabled") + assert kit.rb_value(r_en, True), ( + f"the {refresh.name!r} button AXEnabled must be True, got {r_en!r}") + assert kit.rb_value(q_en, True), ( + f"the {quit_btn.name!r} button AXEnabled must be True, got {q_en!r}") + + pickers = row_pickers(ax, w) + assert len(pickers) >= 1, ( + "expected at least 1 per-app picker (role=radiogroup) in the app list, " + f"found {len(pickers)}") + radios = ax.find(role="radio", root_id=pickers[0].id, max_results=6, max_depth=3) + assert len(radios) == 2, ( + "the first app row's picker must hold exactly 2 radio options ('Default' " + f"plus one input source), found {len(radios)}") + for r in radios: + en = ax.get(r.id, ["AXEnabled"]).get("AXEnabled") + assert kit.rb_value(en, True), ( + f"radio option {r.name!r} of the first picker must have AXEnabled=True, " + f"got {en!r}") diff --git a/macos/ygsgdbd-typeswitch/tests/test_ax_structure.py b/macos/ygsgdbd-typeswitch/tests/test_ax_structure.py new file mode 100644 index 0000000000000000000000000000000000000000..ae78d090b1deb7710564bf5d7522257f22544f3c --- /dev/null +++ b/macos/ygsgdbd-typeswitch/tests/test_ax_structure.py @@ -0,0 +1,716 @@ +"""AX STRUCTURE lane for TypeSwitch (macos-ygsgdbd-typeswitch). + +Everything asserted here comes from the observed golden model in recon.md: + * gate (depth=0, jump_kind="none") -> the two menu bars, the 600x500 + AXSystemDialog panel, its role census + and its row/footer layout invariants + * shape (depth=1/2, reach / transition) -> recon STRUCTURE rows S1..S11, i.e. the + widget-tree DELTAS produced by the status + item, Escape, AXConfirm, the Global Quick + Switch toggle, the search filter, the + About dialog and the ctrl-shift-Space toast. + +The app is an LSUIElement menu-bar-extra app: there is NO window until the status item +is pressed, so every window-dependent test reveals the UI with `rb_enter_main_window` +(0.3-2.7 s). `ax_with_reset` / `helpers.ensure_panel_open()` are deliberately NOT used +(measured 39.5 s -> blows the 30 s per-test timeout). + +SAFETY: this module never presses `Quit (⌘Q)`, `Quit TypeSwitch`, `Hide TypeSwitch`, +`Hide Others`, never sends ⌘Q and never kills a process. +""" + +# ---- paste verbatim into every test module ------------------------------------- +import os, json, re, subprocess, time +import pytest +import rb_testgen_kit as kit +import verifier_helpers as helpers + +CTRL_LABELS = { + "Global Quick Switch", + "Use shortcut to quickly switch between input methods", + "Launch at Login", + "Automatically start TypeSwitch when you log in", +} + + +def screenshot_assert(test_name, description, results_dir=None): + results_dir = results_dir or os.environ.get("RESULTS_DIR", "results") + 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 + af = os.path.join(ss_dir, "assertions.json") + data = {} + if os.path.exists(af): + try: + data = json.load(open(af)) + except Exception: + data = {} + data[f"{test_name}.png"] = description + with open(af, "w") as f: + json.dump(data, f, indent=2) + + +def _main_window(ax): + """The app's content window: a top-level window that owns a group subtree.""" + for w in ax.find(role="window", max_results=6, max_depth=2): + if ax.find(role="group", root_id=w.id, max_results=1, max_depth=3): + return w + return None + + +def _wait_window(ax, timeout=1.2): + end = time.time() + timeout + while time.time() < end: + w = _main_window(ax) + if w is not None: + return w + time.sleep(0.15) + return None + + +def rb_enter_main_window(ax, attempts=4): + """Reveal the app's main UI (surface crossing: menu bar -> window). + + Portable: an already-open window wins; otherwise press status-item / menu-bar + items (the extras bar FIRST), then CG-click, then ax.ensure_ui_visible().""" + w = _main_window(ax) + if w is not None: + return w + bars = ax.find(role="menu_bar", max_results=4, max_depth=1) + ordered = [] + for bar in reversed(bars): # extras (status-item) menu bar first + ordered += [i for i in ax.find(role="menu_bar_item", root_id=bar.id, + max_results=12) + if (i.name or "") != "Apple"] + for item in ordered: + for _ in range(attempts): + ax.action(item.id, "AXPress") + w = _wait_window(ax) + if w is not None: + return w + helpers.dismiss_menus(ax) + for item in ordered: + ax.click_element_cg(item.id) + w = _wait_window(ax) + if w is not None: + return w + helpers.dismiss_menus(ax) + ax.ensure_ui_visible() + return _main_window(ax) + + +def status_item(ax): + """The menu-bar-extra item that owns the app UI (last menu bar, first item).""" + bars = ax.find(role="menu_bar", max_results=4, max_depth=1) + for bar in reversed(bars): + items = [i for i in ax.find(role="menu_bar_item", root_id=bar.id, max_results=12) + if (i.name or "") != "Apple"] + if len(items) == 1: # a status/extras bar holds exactly one item + return items[0] + return None + + +def frame(ax, el_id): + """(x, y, w, h) floats parsed out of AXPosition / AXSize.""" + d = ax.get(el_id, ["AXPosition", "AXSize"]) + + def num(s, key): + m = re.search(key + r":(-?[\d.]+)", str(s)) + return float(m.group(1)) if m else None + + return (num(d.get("AXPosition"), "x"), num(d.get("AXPosition"), "y"), + num(d.get("AXSize"), "w"), num(d.get("AXSize"), "h")) + + +def search_field(ax, w): + """The app-list search field: the text field whose placeholder mentions search.""" + tfs = ax.find(role="text_field", root_id=w.id, max_results=8, max_depth=12) + for t in tfs: + ph = (ax.get(t.id, ["AXPlaceholderValue"]).get("AXPlaceholderValue") or "") + if "Search" in ph or "搜索" in ph: + return t + return tfs[0] if tfs else None + + +def app_names(ax, w): + """Visible app-row names = every label that is not one of the 4 control labels.""" + return [e.value for e in ax.find(role="label", root_id=w.id, + max_results=300, max_depth=12) + if e.value and e.value not in CTRL_LABELS] + + +def set_search(ax, w, query, settle=0.8): + tf = search_field(ax, w) + ax.set_value(tf.id, query) + time.sleep(settle) + return tf + + +def toggle_for(ax, w, label_text): + """The checkbox/toggle belonging to the settings row labelled `label_text` + (pairs by nearest vertical centre — robust to child ordering).""" + lab = None + for e in ax.find(role="label", root_id=w.id, max_results=300, max_depth=12): + if e.value == label_text: + lab = e + break + boxes = ax.find(role="checkbox", root_id=w.id, max_results=10, max_depth=12) + if not boxes: + return None + if lab is None: + return boxes[0] + ly = (frame(ax, lab.id)[1] or 0) + (frame(ax, lab.id)[3] or 0) / 2.0 + best, bestd = None, 1e9 + for b in boxes: + by = (frame(ax, b.id)[1] or 0) + (frame(ax, b.id)[3] or 0) / 2.0 + if abs(by - ly) < bestd: + best, bestd = b, abs(by - ly) + return best + + +def toggle_value(ax, el_id): + return ax.get(el_id, ["AXValue"]).get("AXValue") + + +def named_button(ax, w, keyword): + for b in ax.find(role="button", root_id=w.id, max_results=30, max_depth=12): + if b.name and keyword.lower() in b.name.lower(): + return b + return None +# -------------------------------------------------------------------------------- + + +# ---- raw-AX fallbacks (unused by the tests below; the `ax` fixture is the ------- +# ---- mandated access path, these exist only so the module is self-describing) --- +try: # pragma: no cover - pyobjc availability is environment dependent + from ApplicationServices import ( + AXUIElementCreateApplication, AXUIElementCopyAttributeValue, + AXUIElementCopyActionNames, AXUIElementPerformAction, + AXUIElementCopyElementAtPosition, AXUIElementIsAttributeSettable, + AXUIElementSetAttributeValue, AXUIElementGetPid, + ) + + def get_attr(el, attr): + err, val = AXUIElementCopyAttributeValue(el, attr, None) + return val if err == 0 else None + + def set_attr(el, attr, val): + AXUIElementSetAttributeValue(el, attr, val) + + def walk_tree(el, depth=0, max_depth=15): + role = get_attr(el, "AXRole") or "" + title = get_attr(el, "AXTitle") or "" + yield (depth, role, title, el) + if depth < max_depth: + for child in (get_attr(el, "AXChildren") or []): + yield from walk_tree(child, depth + 1, max_depth) + + def get_actions(element): + err, actions = AXUIElementCopyActionNames(element, None) + return list(actions) if err == 0 and actions else [] +except Exception: # pragma: no cover + pass +# -------------------------------------------------------------------------------- + + +# ---- structure-lane local helpers ---------------------------------------------- + +#: roles observed inside the main panel (recon AX_TREE census) - used for diversity +PANEL_ROLES = ("group", "text_field", "scroll_area", "label", "image", + "radiogroup", "radio", "checkbox", "button") + +#: standard AppKit menu-bar item titles; anything else is the app's own menu +STD_MENU_TITLES = {"Apple", "File", "Edit", "View", "Window", "Help", "Keyboard"} + + +def window_count(ax): + """Number of top-level windows the application currently exposes.""" + return len(ax.find(role="window", max_results=8, max_depth=2)) + + +def count_role(ax, w, role, max_results=400, max_depth=12): + """How many `role` nodes live inside window/container `w`.""" + return len(ax.find(role=role, root_id=w.id, + max_results=max_results, max_depth=max_depth)) + + +def role_census(ax, w, roles=PANEL_ROLES): + return {r: count_role(ax, w, r) for r in roles} + + +def actions_of(ax, el_id): + """Best-effort action-name list (the helper exposes it under varying names).""" + for meth in ("actions", "get_actions", "action_names", "list_actions"): + fn = getattr(ax, meth, None) + if callable(fn): + try: + res = fn(el_id) + if res: + return [str(a) for a in res] + except Exception: + pass + try: + raw = (ax.get(el_id, ["AXActions"]) or {}).get("AXActions") + if raw: + if isinstance(raw, (list, tuple)): + return [str(a) for a in raw] + return re.findall(r"AX[A-Za-z]+", str(raw)) + except Exception: + pass + return [] + + +def _truthy(v): + """AXValue of a toggle may come back as 1/0, True/False or "1"/"0".""" + if v is None: + return False + if isinstance(v, bool): + return v + if isinstance(v, (int, float)): + return v != 0 + return str(v).strip().lower() in ("1", "true", "yes", "on") + + +def clear_search(ax, w, settle=0.6): + """Leave the search box empty (needed by the Escape / AXConfirm close paths).""" + tf = search_field(ax, w) + if tf is None: + return None + if (ax.get(tf.id, ["AXValue"]).get("AXValue") or "") != "": + ax.set_value(tf.id, "") + time.sleep(settle) + return tf + + +def ensure_no_window(ax, tries=3): + """Normalise to the fresh-launch shape: zero windows exposed.""" + for _ in range(tries): + if window_count(ax) == 0: + return True + si = status_item(ax) + if si is not None: + ax.action(si.id, "AXPress") # the status item TOGGLES the panel + time.sleep(1.0) + if window_count(ax) == 0: + return True + helpers.send_key(helpers.KC_ESCAPE) + time.sleep(0.9) + return window_count(ax) == 0 + + +def quick_switch_toggle(ax, w): + """Freshly resolve the "Global Quick Switch" toggle (SwiftUI re-creates nodes).""" + return toggle_for(ax, w, "Global Quick Switch") + + +def windows_with_subrole(ax, subrole): + out = [] + for win in ax.find(role="window", max_results=8, max_depth=2): + if (ax.get(win.id, ["AXSubrole"]).get("AXSubrole") or "") == subrole: + out.append(win) + return out + + +def window_sized(ax, width, height, tol=10.0): + """First top-level window whose AXSize is (width x height) within `tol` px.""" + for win in ax.find(role="window", max_results=8, max_depth=2): + _, _, ww, hh = frame(ax, win.id) + if ww is None or hh is None: + continue + if abs(ww - width) <= tol and abs(hh - height) <= tol: + return win + return None + + +def app_menu_bar_item(ax): + """The application menu (named after the app) in the first/app menu bar.""" + items = ax.find(role="menu_bar_item", max_results=20, max_depth=6) + named = [(i, (i.name or "")) for i in items] + for el, name in named: + if name == "TypeSwitch": + return el + for el, name in named: + if name and name not in STD_MENU_TITLES: + return el + return None + + +# ================================================================================= +# GATE - existence only, depth=0 / jump_kind="none" (<=30 % of the suite: 4/12) +# ================================================================================= + +class TestAXStructureGate: + + @pytest.mark.rb(depth=0, jump_kind="none") + def test_gate_menu_bar_structure(self, ax): + """Two AX menu bars: the app menu bar + the extras bar holding "Keyboard".""" + bars = ax.find(role="menu_bar", max_results=6, max_depth=1) + assert len(bars) == 2, ( + "expected exactly 2 menu_bar children (app menu bar + AXExtrasMenuBar " + f"status bar), found {len(bars)}") + + extras_items = ax.find(role="menu_bar_item", root_id=bars[-1].id, + max_results=12) + assert len(extras_items) == 1, ( + "the extras (status-item) menu bar must hold exactly ONE menu_bar_item, " + f"found {len(extras_items)}: {[i.name for i in extras_items]}") + assert (extras_items[0].name or "") == "Keyboard", ( + "the status item must be named 'Keyboard' (SF Symbol keyboard), got " + f"{extras_items[0].name!r}") + acts = actions_of(ax, extras_items[0].id) + if acts: + assert "AXPress" in acts, ( + "the 'Keyboard' status item must expose actions ['AXPress'], got " + f"{acts}") + + app_items = [(i.name or "") for i in + ax.find(role="menu_bar_item", root_id=bars[0].id, + max_results=20)] + for expected in ("Apple", "TypeSwitch", "File", "Edit", "View", + "Window", "Help"): + assert expected in app_items, ( + f"app menu bar is missing the {expected!r} menu_bar_item; observed " + f"{app_items}") + + @pytest.mark.rb(depth=0, jump_kind="none") + def test_gate_main_panel_window(self, ax): + """The revealed panel is a 600x500 AXSystemDialog owning exactly one group.""" + w = rb_enter_main_window(ax) + assert w is not None, ( + "no main window after rb_enter_main_window: pressing the 'Keyboard' " + "status item must reveal the TypeSwitch panel") + + attrs = ax.get(w.id, ["AXSubrole", "AXRoleDescription"]) + assert (attrs.get("AXSubrole") or "") == "AXSystemDialog", ( + "main panel AXSubrole must be 'AXSystemDialog', got " + f"{attrs.get('AXSubrole')!r}") + assert (attrs.get("AXRoleDescription") or "").lower() == "system dialog", ( + "main panel AXRoleDescription must be 'system dialog', got " + f"{attrs.get('AXRoleDescription')!r}") + + _, _, ww, hh = frame(ax, w.id) + assert ww is not None and hh is not None, "main panel exposes no AXSize" + assert abs(ww - 600) <= 2, f"main panel width must be 600 px, got {ww}" + assert abs(hh - 500) <= 2, f"main panel height must be 500 px, got {hh}" + + groups = ax.find(role="group", root_id=w.id, max_results=6, max_depth=3) + assert len(groups) == 1, ( + f"main panel must own exactly one content group, found {len(groups)}") + + screenshot_assert( + "structure_test_main_panel_window", + "A dark 600x500 TypeSwitch panel anchored at the TOP-RIGHT of the screen " + "just under the menu bar. Top: a rounded search field spanning the panel " + "width with placeholder 'Search Apps... (⌘F)'. Middle: a scrolling list of " + "app rows, each with an app icon on the left, the app name beside it and a " + "small two-segment picker (Default | U.S.) on the right. Bottom: a " + "'Global Quick Switch' row with the sub-line 'Use shortcut to quickly " + "switch between input methods' and a switch on the right, then a " + "'Launch at Login' row with 'Automatically start TypeSwitch when you log " + "in' and a second switch; bottom-right two small text buttons " + "'Refresh (⌘R)' and 'Quit (⌘Q)'.") + + @pytest.mark.rb(depth=0, jump_kind="none") + def test_gate_panel_role_census(self, ax): + """The panel exposes the observed per-role minimum counts + role diversity.""" + w = rb_enter_main_window(ax) + assert w is not None, "no main window to take a role census in" + + census = role_census(ax, w) + minimums = {"text_field": 1, "scroll_area": 1, "label": 14, + "button": 6, "radiogroup": 10, "radio": 20, "image": 10} + for role, low in minimums.items(): + assert census[role] >= low, ( + f"panel must expose at least {low} {role!r} nodes " + f"(recon observed {'17' if role == 'label' else 'more'}), got " + f"{census[role]}; full census {census}") + + checkboxes = ax.find(role="checkbox", root_id=w.id, max_results=10, + max_depth=12) + assert len(checkboxes) == 2, ( + "panel must expose exactly 2 checkboxes ('Global Quick Switch' and " + f"'Launch at Login'), found {len(checkboxes)}") + for cb in checkboxes: + sub = ax.get(cb.id, ["AXSubrole"]).get("AXSubrole") or "" + assert sub == "AXToggle", ( + f"each settings checkbox must have AXSubrole 'AXToggle', got {sub!r}") + + distinct = sorted(r for r, n in census.items() if n > 0) + assert len(distinct) >= 7, ( + "panel role diversity must be at least 7 distinct roles out of " + f"{list(PANEL_ROLES)}, got {len(distinct)}: {distinct}") + + @pytest.mark.rb(depth=0, jump_kind="none") + def test_gate_row_and_footer_layout_invariants(self, ax): + """#image == #app-name labels == #radiogroup, 2 radios each, Refresh left of Quit.""" + w = rb_enter_main_window(ax) + assert w is not None, "no main window to check row invariants in" + + images = ax.find(role="image", root_id=w.id, max_results=300, max_depth=12) + names = app_names(ax, w) + groups = ax.find(role="radiogroup", root_id=w.id, max_results=300, + max_depth=12) + assert len(images) == len(names) == len(groups), ( + "every realized app row must be image + name label + picker, so the three " + f"counts must be equal: images={len(images)} names={len(names)} " + f"radiogroups={len(groups)}") + assert len(groups) >= 10, ( + f"expected at least 10 realized app rows, found {len(groups)}") + + for idx, rg in enumerate(groups): + radios = ax.find(role="radio", root_id=rg.id, max_results=6, max_depth=3) + assert len(radios) == 2, ( + f"app-row radiogroup #{idx} must hold exactly 2 radios " + f"('Default' and 'U.S.'), found {len(radios)}: " + f"{[r.name for r in radios]}") + + refresh = named_button(ax, w, "Refresh") + quit_btn = named_button(ax, w, "Quit") + assert refresh is not None, "footer button 'Refresh (⌘R)' not found" + assert quit_btn is not None, "footer button 'Quit (⌘Q)' not found" + rx, ry, _, _ = frame(ax, refresh.id) + qx, qy, _, _ = frame(ax, quit_btn.id) + assert None not in (rx, ry, qx, qy), "footer buttons expose no AXPosition" + assert rx < qx, ( + "'Refresh (⌘R)' must sit to the LEFT of 'Quit (⌘Q)' " + f"(observed x 1517 < 1599), got refresh.x={rx} quit.x={qx}") + assert abs(ry - qy) <= 4, ( + "'Refresh (⌘R)' and 'Quit (⌘Q)' must share the same footer baseline " + f"(within 4 px), got refresh.y={ry} quit.y={qy}") + + +# ================================================================================= +# SHAPE DELTAS - recon STRUCTURE rows S1..S11 +# ================================================================================= + +class TestAXStructureShapeDeltas: + + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="window count 1 -> 0 when the 'Keyboard' status item is " + "pressed while the panel is open (it toggles it closed); " + "panel re-revealed afterwards") + def test_s2_status_item_toggles_panel_closed(self, ax): + w = rb_enter_main_window(ax) + assert w is not None, "panel must be open before testing the close toggle" + before = kit.rb_showing(ax) + assert window_count(ax) == 1, ( + f"expected 1 window before the toggle-close, got {window_count(ax)}") + + si = status_item(ax) + assert si is not None, "no 'Keyboard' status item to press" + ax.action(si.id, "AXPress") + time.sleep(1.2) + + after = kit.rb_showing(ax) + assert window_count(ax) == 0, ( + "pressing the 'Keyboard' status item again must close the panel " + f"(0 windows), got {window_count(ax)}") + assert kit.rb_flip(before, after), ( + "the widget tree must flip when the status item toggles the panel closed") + + rb_enter_main_window(ax) # leave the desktop in the revealed state + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="window count 1 -> 0 when Escape is sent while the search " + "box is EMPTY (second-level Escape closes the panel)") + def test_s3_escape_with_empty_search_closes_panel(self, ax): + w = rb_enter_main_window(ax) + assert w is not None, "panel must be open before sending Escape" + clear_search(ax, w) + before = kit.rb_showing(ax) + assert window_count(ax) == 1, ( + f"expected 1 window before Escape, got {window_count(ax)}") + + helpers.send_key(helpers.KC_ESCAPE) + time.sleep(1.0) + + after = kit.rb_showing(ax) + assert window_count(ax) == 0, ( + "Escape on an EMPTY search box must close the panel (0 windows), got " + f"{window_count(ax)}") + assert kit.rb_flip(before, after), ( + "the widget tree must flip when Escape dismisses the panel") + + rb_enter_main_window(ax) + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="window count 1 -> 0 when AXConfirm is performed on the " + "EMPTY search field (submitting an empty query closes the " + "panel)") + def test_s4_axconfirm_on_empty_search_closes_panel(self, ax): + w = rb_enter_main_window(ax) + assert w is not None, "panel must be open before AXConfirm on the search field" + tf = clear_search(ax, w) + assert tf is not None, "search text_field not found in the panel" + before = kit.rb_showing(ax) + assert window_count(ax) == 1, ( + f"expected 1 window before AXConfirm, got {window_count(ax)}") + + ax.action(tf.id, "AXConfirm") + time.sleep(1.2) + + after = kit.rb_showing(ax) + assert window_count(ax) == 0, ( + "AXConfirm on the empty search field must close the panel (0 windows), " + f"got {window_count(ax)}") + assert kit.rb_flip(before, after), ( + "the widget tree must flip when AXConfirm dismisses the panel") + + rb_enter_main_window(ax) + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="'Global Quick Switch' OFF->ON adds a second text_field " + "(the shortcut recorder, AXValue '⌃⇧Space'): count 1 -> 2; " + "ON->OFF removes it again: 2 -> 1; original state restored") + def test_s5_s6_quick_switch_toggle_adds_and_removes_recorder_field(self, ax): + w = rb_enter_main_window(ax) + assert w is not None, "panel must be open to toggle Global Quick Switch" + + tg = quick_switch_toggle(ax, w) + assert tg is not None, "'Global Quick Switch' toggle (checkbox) not found" + original_on = _truthy(toggle_value(ax, tg.id)) + + # this setting persists across relaunches -> normalise to OFF first + if original_on: + ax.action(tg.id, "AXPress") + time.sleep(1.2) + tg = quick_switch_toggle(ax, w) + assert not _truthy(toggle_value(ax, tg.id)), ( + "could not normalise 'Global Quick Switch' to OFF before measuring") + + assert count_role(ax, w, "text_field") == 1, ( + "with Global Quick Switch OFF the panel must expose exactly 1 text_field " + f"(the search box), got {count_role(ax, w, 'text_field')}") + + before = kit.rb_showing(ax) + ax.action(tg.id, "AXPress") # S5: OFF -> ON + time.sleep(1.2) + after = kit.rb_showing(ax) + + fields = ax.find(role="text_field", root_id=w.id, max_results=8, max_depth=12) + assert len(fields) == 2, ( + "turning Global Quick Switch ON must add the shortcut recorder, so the " + f"panel must expose 2 text_fields, got {len(fields)}") + values = [(ax.get(f.id, ["AXValue"]).get("AXValue") or "") for f in fields] + assert "⌃⇧Space" in values, ( + "the new recorder text_field must show AXValue '⌃⇧Space', observed " + f"text_field values {values}") + assert kit.rb_flip(before, after), ( + "the widget tree must flip when the shortcut recorder field appears") + + screenshot_assert( + "structure_test_quick_switch_recorder", + "The dark TypeSwitch panel with the 'Global Quick Switch' row at the " + "bottom now ALSO showing a shortcut recorder field displaying '⌃⇧Space' to " + "the LEFT of the switch, and that switch is in its ON (filled/blue) " + "position. The 'Launch at Login' row, the app list above and the " + "'Refresh (⌘R)' / 'Quit (⌘Q)' buttons are unchanged.") + + tg = quick_switch_toggle(ax, w) + ax.action(tg.id, "AXPress") # S6: ON -> OFF + time.sleep(1.2) + assert count_role(ax, w, "text_field") == 1, ( + "turning Global Quick Switch OFF again must remove the recorder field " + f"(back to 1 text_field), got {count_role(ax, w, 'text_field')}") + + if original_on: # restore persisted state + tg = quick_switch_toggle(ax, w) + ax.action(tg.id, "AXPress") + time.sleep(1.2) + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="search 'Calc' shrinks the list from >=10 radiogroups to " + "exactly 1 radiogroup / 1 app image / 1 app row label; " + "clearing the search restores >=10 radiogroups") + def test_s7_search_filter_shrinks_app_list(self, ax): + w = rb_enter_main_window(ax) + assert w is not None, "panel must be open to drive the search filter" + clear_search(ax, w) + + baseline = count_role(ax, w, "radiogroup") + assert baseline >= 10, ( + "with an empty search the panel must expose at least 10 app-row " + f"radiogroups, got {baseline}") + + before = kit.rb_showing(ax) + set_search(ax, w, "Calc") + after = kit.rb_showing(ax) + + assert count_role(ax, w, "radiogroup") == 1, ( + "searching 'Calc' must leave exactly 1 app-row radiogroup, got " + f"{count_role(ax, w, 'radiogroup')}") + assert count_role(ax, w, "image") == 1, ( + "searching 'Calc' must leave exactly 1 app icon image, got " + f"{count_role(ax, w, 'image')}") + assert len(app_names(ax, w)) == 1, ( + "searching 'Calc' must leave exactly 1 app-row label, got " + f"{app_names(ax, w)}") + assert kit.rb_flip(before, after), ( + "the widget tree must flip when the search filter collapses the app list") + + screenshot_assert( + "structure_test_search_filter_shrinks_list", + "The dark TypeSwitch panel with 'Calc' typed into the top search field and " + "only ONE app row visible in the list area: the Calculator icon, the name " + "'Calculator' and its two-segment 'Default | U.S.' picker on the right. " + "The rest of the list area is empty; the 'Global Quick Switch' and " + "'Launch at Login' rows and the 'Refresh (⌘R)' / 'Quit (⌘Q)' buttons " + "remain at the bottom.") + + set_search(ax, w, "") + restored = count_role(ax, w, "radiogroup") + assert restored >= 10, ( + "clearing the search must restore at least 10 app-row radiogroups, got " + f"{restored}") + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="search 'zzzznotanapp' empties the list: 0 radiogroups and " + "0 app-name labels, while the 4 settings control labels " + "remain; clearing restores >=10 radiogroups") + def test_s8_no_match_search_empties_list_but_keeps_controls(self, ax): + w = rb_enter_main_window(ax) + assert w is not None, "panel must be open to drive the search filter" + clear_search(ax, w) + assert count_role(ax, w, "radiogroup") >= 10, ( + "expected a populated app list before the no-match search, got " + f"{count_role(ax, w, 'radiogroup')} radiogroups") + + before = kit.rb_showing(ax) + set_search(ax, w, "zzzznotanapp") + after = kit.rb_showing(ax) + + assert count_role(ax, w, "radiogroup") == 0, ( + "a no-match search must leave 0 app-row radiogroups, got " + f"{count_role(ax, w, 'radiogroup')}") + assert app_names(ax, w) == [], ( + "a no-match search must leave 0 app-name labels, got " + f"{app_names(ax, w)}") + + labels = {e.value for e in ax.find(role="label", root_id=w.id, + max_results=300, max_depth=12) if e.value} + missing = CTRL_LABELS - labels + assert not missing, ( + "the 4 settings control labels must survive a no-match search; missing " + f"{sorted(missing)}") + assert kit.rb_flip(before, after), ( + "the widget tree must flip when the no-match search empties the app list") + + screenshot_assert( + "structure_test_no_match_search", + "The dark TypeSwitch panel with 'zzzznotanapp' in the top search field and " + "NO app rows at all - the whole list area is blank. Only the two settings " + "rows ('Global Quick Switch' with its sub-line and switch, 'Launch at " + "Login' with its sub-line and switch) and the bottom-right 'Refresh (⌘R)' " + "and 'Quit (⌘Q)' buttons remain.") + + set_search(ax, w, "") + assert count_role(ax, w, "radiogroup") >= 10, ( + "clearing the search must restore at least 10 app-row radiogroups, got " + f"{count_role(ax, w, 'radiogroup')}") + + diff --git a/macos/ygsgdbd-typeswitch/tests/test_ax_text.py b/macos/ygsgdbd-typeswitch/tests/test_ax_text.py new file mode 100644 index 0000000000000000000000000000000000000000..f9fb7f46dd438c5e1319de9cbaa44b3a7e7e4cfa --- /dev/null +++ b/macos/ygsgdbd-typeswitch/tests/test_ax_text.py @@ -0,0 +1,763 @@ +"""test_ax_text.py — TEXT CONTENT tests for TypeSwitch (menu-bar-extra app). + +Every expected string below was OBSERVED on the running reference app and is quoted +verbatim from recon.md `## TEXT`. Text for `label` / `text_field` lives in `AXValue` +(their name/`AXTitle` is empty); text for `button` / `radio` / `menu_bar_item` / +`image` lives in the NAME (`AXTitle` or `AXDescription`). + +Contract notes +- The app is `LSUIElement = true`: there is NO window until the status item is pressed. + Every window-dependent test therefore starts with `rb_enter_main_window(ax)` (0.3-0.6 s). + `ax_with_reset` / `helpers.ensure_panel_open()` are NEVER used (measured 39.5 s on this + app -> blows the runner's 30 s per-test timeout). +- The main window's `AXTitle` is `""` (recon `## UNREACHED`) — no test asserts a + non-empty window title. The app-level AX `AXTitle` ("TypeSwitch") is asserted instead. +- SAFETY: nothing here presses `Quit (⌘Q)`, `Quit TypeSwitch`, `Hide TypeSwitch`, + `Hide Others`, sends ⌘Q, or touches the `Record Shortcut` recorder field. +- Global Quick Switch persists across the per-test relaunch, so the two tests that need + it ON read the value first and RESTORE it in a `finally`. +""" + +# ---- paste verbatim into every test module ------------------------------------- +import os, json, re, subprocess, time +import pytest +import rb_testgen_kit as kit +import verifier_helpers as helpers + +CTRL_LABELS = { + "Global Quick Switch", + "Use shortcut to quickly switch between input methods", + "Launch at Login", + "Automatically start TypeSwitch when you log in", +} + + +def screenshot_assert(test_name, description, results_dir=None): + results_dir = results_dir or os.environ.get("RESULTS_DIR", "results") + 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 + af = os.path.join(ss_dir, "assertions.json") + data = {} + if os.path.exists(af): + try: + data = json.load(open(af)) + except Exception: + data = {} + data[f"{test_name}.png"] = description + with open(af, "w") as f: + json.dump(data, f, indent=2) + + +def _main_window(ax): + """The app's content window: a top-level window that owns a group subtree.""" + for w in ax.find(role="window", max_results=6, max_depth=2): + if ax.find(role="group", root_id=w.id, max_results=1, max_depth=3): + return w + return None + + +def _wait_window(ax, timeout=1.2): + end = time.time() + timeout + while time.time() < end: + w = _main_window(ax) + if w is not None: + return w + time.sleep(0.15) + return None + + +def rb_enter_main_window(ax, attempts=4): + """Reveal the app's main UI (surface crossing: menu bar -> window). + + Portable: an already-open window wins; otherwise press status-item / menu-bar + items (the extras bar FIRST), then CG-click, then ax.ensure_ui_visible().""" + w = _main_window(ax) + if w is not None: + return w + bars = ax.find(role="menu_bar", max_results=4, max_depth=1) + ordered = [] + for bar in reversed(bars): # extras (status-item) menu bar first + ordered += [i for i in ax.find(role="menu_bar_item", root_id=bar.id, + max_results=12) + if (i.name or "") != "Apple"] + for item in ordered: + for _ in range(attempts): + ax.action(item.id, "AXPress") + w = _wait_window(ax) + if w is not None: + return w + helpers.dismiss_menus(ax) + for item in ordered: + ax.click_element_cg(item.id) + w = _wait_window(ax) + if w is not None: + return w + helpers.dismiss_menus(ax) + ax.ensure_ui_visible() + return _main_window(ax) + + +def status_item(ax): + """The menu-bar-extra item that owns the app UI (last menu bar, first item).""" + bars = ax.find(role="menu_bar", max_results=4, max_depth=1) + for bar in reversed(bars): + items = [i for i in ax.find(role="menu_bar_item", root_id=bar.id, max_results=12) + if (i.name or "") != "Apple"] + if len(items) == 1: # a status/extras bar holds exactly one item + return items[0] + return None + + +def frame(ax, el_id): + """(x, y, w, h) floats parsed out of AXPosition / AXSize.""" + d = ax.get(el_id, ["AXPosition", "AXSize"]) + + def num(s, key): + m = re.search(key + r":(-?[\d.]+)", str(s)) + return float(m.group(1)) if m else None + + return (num(d.get("AXPosition"), "x"), num(d.get("AXPosition"), "y"), + num(d.get("AXSize"), "w"), num(d.get("AXSize"), "h")) + + +def search_field(ax, w): + """The app-list search field: the text field whose placeholder mentions search.""" + tfs = ax.find(role="text_field", root_id=w.id, max_results=8, max_depth=12) + for t in tfs: + ph = (ax.get(t.id, ["AXPlaceholderValue"]).get("AXPlaceholderValue") or "") + if "Search" in ph or "搜索" in ph: + return t + return tfs[0] if tfs else None + + +def app_names(ax, w): + """Visible app-row names = every label that is not one of the 4 control labels.""" + return [e.value for e in ax.find(role="label", root_id=w.id, + max_results=300, max_depth=12) + if e.value and e.value not in CTRL_LABELS] + + +def set_search(ax, w, query, settle=0.8): + tf = search_field(ax, w) + ax.set_value(tf.id, query) + time.sleep(settle) + return tf + + +def toggle_for(ax, w, label_text): + """The checkbox/toggle belonging to the settings row labelled `label_text` + (pairs by nearest vertical centre — robust to child ordering).""" + lab = None + for e in ax.find(role="label", root_id=w.id, max_results=300, max_depth=12): + if e.value == label_text: + lab = e + break + boxes = ax.find(role="checkbox", root_id=w.id, max_results=10, max_depth=12) + if not boxes: + return None + if lab is None: + return boxes[0] + ly = (frame(ax, lab.id)[1] or 0) + (frame(ax, lab.id)[3] or 0) / 2.0 + best, bestd = None, 1e9 + for b in boxes: + by = (frame(ax, b.id)[1] or 0) + (frame(ax, b.id)[3] or 0) / 2.0 + if abs(by - ly) < bestd: + best, bestd = b, abs(by - ly) + return best + + +def toggle_value(ax, el_id): + return ax.get(el_id, ["AXValue"]).get("AXValue") + + +def named_button(ax, w, keyword): + for b in ax.find(role="button", root_id=w.id, max_results=30, max_depth=12): + if b.name and keyword.lower() in b.name.lower(): + return b + return None +# -------------------------------------------------------------------------------- + + +# ── EXACT observed text (recon `## TEXT`) ─────────────────────────────────────── +SEARCH_PLACEHOLDER = "Search Apps... (⌘F)" +SETTINGS_LABELS = [ + "Global Quick Switch", + "Use shortcut to quickly switch between input methods", + "Launch at Login", + "Automatically start TypeSwitch when you log in", +] +FOOTER_REFRESH = "Refresh (⌘R)" +FOOTER_QUIT = "Quit (⌘Q)" +PICKER_FIRST = "Default" +PICKER_SECOND = "U.S." +STATUS_ITEM_NAME = "Keyboard" +APP_AX_TITLE = "TypeSwitch" +RECORDER_PLACEHOLDER = "Record Shortcut" +RECORDER_VALUE = "⌃⇧Space" +ABOUT_APP_NAME = "TypeSwitch" +ABOUT_VERSION = "Version 0.3.5" +ABOUT_COPYRIGHT = "Copyright © 2024 ygsgdbd. All rights reserved." +ABOUT_ICON_NAME = "TypeSwitch icon" +TOAST_PREFIX = "Switched to: " +TOAST_ICON_NAME = "Keyboard" +PANEL_ROLE_DESCRIPTION = "system dialog" +TOGGLE_ROLE_DESCRIPTION = "toggle button" +QUICK_SWITCH_LABEL = "Global Quick Switch" + +# App-row labels observed in the realized rows (recon `## TEXT`). `Safari` and +# `Visual Studio Code` are deliberately absent — recon observed [] for both. +EXPECTED_APP_NAMES = [ + "Activity Monitor", + "AirPort Utility", + "App Store", + "Audio MIDI Setup", + "Automator", + "Bluetooth File Exchange", + "Books", + "Boot Camp Assistant", + "Calculator", + "Calendar", + "Chess", + "Clock", +] + + +# ── small text/state utilities (no navigation) ────────────────────────────────── +def _txt(v): + """AX string value -> plain python str ('' for None).""" + return "" if v is None else str(v) + + +def _attr(ax, el_id, attr): + return _txt(ax.get(el_id, [attr]).get(attr)) + + +def _label_values(ax, w): + """Every label's AXValue inside `w`, as plain strings.""" + return [_txt(e.value) for e in ax.find(role="label", root_id=w.id, + max_results=300, max_depth=12)] + + +def _names(ax, w): + """app_names() normalised to plain python strings.""" + return [_txt(n) for n in app_names(ax, w)] + + +def _is_on(v): + return _txt(v).strip() in ("1", "True", "true", "YES") + + +def _set_toggle(ax, box_id, want_on, settle=1.2): + """Normalise a persistent toggle to `want_on`; returns its observed state.""" + if _is_on(toggle_value(ax, box_id)) != want_on: + ax.action(box_id, "AXPress") + time.sleep(settle) + return _is_on(toggle_value(ax, box_id)) + + +def _recorder_field(ax, w): + """The shortcut recorder text field: placeholder "Record Shortcut" (falls back to + the text field that is NOT the search box). Read-only — never pressed.""" + others = [] + for t in ax.find(role="text_field", root_id=w.id, max_results=8, max_depth=12): + ph = _attr(ax, t.id, "AXPlaceholderValue") + if "Record" in ph or "录制" in ph: + return t + if "Search" not in ph and "搜索" not in ph: + others.append(t) + return others[0] if others else None + + +def _menu_bar_item(ax, title): + for bar in ax.find(role="menu_bar", max_results=4, max_depth=1): + for it in ax.find(role="menu_bar_item", root_id=bar.id, max_results=12): + if _txt(it.name) == title: + return it + return None + + +def _app_menu_bar_item(ax): + """The app's own menu (named "TypeSwitch" on the reference). Portable fallback: + the first non-Apple item of the menu bar that holds MORE than one item (the + extras/status bar holds exactly one).""" + mbi = _menu_bar_item(ax, APP_AX_TITLE) + if mbi is not None: + return mbi + for bar in ax.find(role="menu_bar", max_results=4, max_depth=1): + cands = [i for i in ax.find(role="menu_bar_item", root_id=bar.id, max_results=12) + if _txt(i.name) not in ("Apple", "")] + if len(cands) > 1: + return cands[0] + return None + + +def _dialog_window(ax, timeout=2.0): + """A top-level window whose AXSubrole is AXDialog (the About panel).""" + end = time.time() + timeout + while time.time() < end: + for win in ax.find(role="window", max_results=8, max_depth=2): + if _attr(ax, win.id, "AXSubrole") == "AXDialog": + return win + time.sleep(0.2) + return None + + +# ── navigation helpers (named for the rb depth audit) ─────────────────────────── +def rb_enter_about_window(ax): + """Surface crossing #2: main panel -> app menu bar item -> the About dialog. + + The "About …" item MUST be looked up SCOPED to the app's menu bar item: an + unscoped role=menu_item search returns the Apple menu's "About This Mac" first + (recon `## MENUS`). Returns the dialog window element, or None.""" + rb_enter_main_window(ax) + mbi = _app_menu_bar_item(ax) + if mbi is None: + return None + ax.action(mbi.id, "AXPress") + time.sleep(0.9) + about = None + for mi in ax.find(role="menu_item", root_id=mbi.id, max_results=40, max_depth=6): + nm = _txt(mi.name) + if nm.lower().startswith("about") or nm.startswith("关于"): + about = mi + break + if about is None: + return None + ax.action(about.id, "AXPress") + time.sleep(2.5) + return _dialog_window(ax, timeout=2.0) + + +def rb_reach_toast(ax, panel, timeout=3.0): + """Surface crossing: the transient toast window the global hotkey raises. + + Polls up to `timeout` for a window that is NOT the panel (compared by element id + AND by frame, so no reliance on AX identity) and that carries a non-empty label. + Returns (window, label_text) or (None, "").""" + pf = frame(ax, panel.id) if panel is not None else None + end = time.time() + timeout + while time.time() < end: + for win in ax.find(role="window", max_results=8, max_depth=2): + if panel is not None and (win.id == panel.id or frame(ax, win.id) == pf): + continue + for lab in ax.find(role="label", root_id=win.id, max_results=20, max_depth=8): + text = _txt(lab.value).strip() + if text: + return win, text + time.sleep(0.15) + return None, "" + + +# ═══════════════════════════════════════════════════════════════════════════════ +class TestPanelChromeText: + """Static text of the panel's own chrome: search placeholder, settings labels, + footer button labels, role-description strings.""" + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="search field placeholder reads 'Search Apps... (⌘F)' and its AXValue is ''") + def test_search_field_placeholder_and_empty_value(self, ax): + w = rb_enter_main_window(ax) + assert w is not None, "the main panel window must be reachable via the 'Keyboard' status item" + + tf = search_field(ax, w) + assert tf is not None, "the panel must expose a search text_field (placeholder 'Search Apps... (⌘F)')" + + placeholder = _attr(ax, tf.id, "AXPlaceholderValue") + assert kit.rb_value(placeholder, SEARCH_PLACEHOLDER), ( + f"search field AXPlaceholderValue must be exactly 'Search Apps... (⌘F)', " + f"observed {placeholder!r}") + assert placeholder == SEARCH_PLACEHOLDER, ( + f"search field AXPlaceholderValue must be exactly 'Search Apps... (⌘F)' " + f"(three ASCII dots, a space, then '(⌘F)'), observed {placeholder!r}") + + value = _attr(ax, tf.id, "AXValue") + assert value == "", ( + f"on reveal the search field AXValue must be the empty string '', observed {value!r}") + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="labels read 'Global Quick Switch' / 'Use shortcut to quickly switch between input methods' / 'Launch at Login' / 'Automatically start TypeSwitch when you log in', top to bottom") + def test_settings_labels_exact_text_and_order(self, ax): + w = rb_enter_main_window(ax) + assert w is not None, "the main panel window must be reachable via the 'Keyboard' status item" + + found = {} + for e in ax.find(role="label", root_id=w.id, max_results=300, max_depth=12): + v = _txt(e.value) + if v in SETTINGS_LABELS and v not in found: + found[v] = e + observed = _label_values(ax, w) + + for expected in SETTINGS_LABELS: + hit = _txt(found[expected].value) if expected in found else None + assert kit.rb_value(hit, expected), ( + f"a settings label whose AXValue is exactly {expected!r} must exist; " + f"observed label values: {observed}") + + assert kit.rb_value(sorted(found.keys()), sorted(SETTINGS_LABELS)), ( + f"the four settings labels must read exactly " + f"{sorted(SETTINGS_LABELS)}, observed {sorted(found.keys())}") + + ys = [] + for expected in SETTINGS_LABELS: + y = frame(ax, found[expected].id)[1] + assert y is not None, f"label {expected!r} must expose an AXPosition" + ys.append(y) + assert ys == sorted(ys), ( + "the settings labels must appear top-to-bottom in the order " + "'Global Quick Switch' > 'Use shortcut to quickly switch between input methods' > " + f"'Launch at Login' > 'Automatically start TypeSwitch when you log in', observed y values {ys}") + + screenshot_assert( + "text_test_settings_labels", + "The dark 600x500 TypeSwitch panel anchored top-right under the menu bar. " + "Bottom half reads the settings text: the row 'Global Quick Switch' with the " + "sub-line 'Use shortcut to quickly switch between input methods' and a switch on " + "the right, then 'Launch at Login' with 'Automatically start TypeSwitch when you " + "log in' and a second switch. Bottom-right shows the two small text buttons " + "'Refresh (⌘R)' and 'Quit (⌘Q)'. Top shows the search field placeholder " + "'Search Apps... (⌘F)'.") + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="footer buttons are named exactly 'Refresh (⌘R)' and 'Quit (⌘Q)'") + def test_footer_button_labels_exact(self, ax): + w = rb_enter_main_window(ax) + assert w is not None, "the main panel window must be reachable via the 'Keyboard' status item" + + all_names = [_txt(b.name) for b in ax.find(role="button", root_id=w.id, + max_results=30, max_depth=12)] + + refresh = named_button(ax, w, "Refresh") + assert refresh is not None, ( + f"a footer button named 'Refresh (⌘R)' must exist; observed button names: {all_names}") + refresh_name = _txt(refresh.name) + assert kit.rb_value(refresh_name, FOOTER_REFRESH), ( + f"the refresh button's name must be exactly 'Refresh (⌘R)', observed {refresh_name!r}") + assert refresh_name == FOOTER_REFRESH, ( + f"the refresh button's name must be exactly 'Refresh (⌘R)' — the '(⌘R)' shortcut " + f"hint is part of the label; observed {refresh_name!r}") + + quit_btn = named_button(ax, w, "Quit") + assert quit_btn is not None, ( + f"a footer button named 'Quit (⌘Q)' must exist; observed button names: {all_names}") + quit_name = _txt(quit_btn.name) # read only — NEVER pressed + assert kit.rb_value(quit_name, FOOTER_QUIT), ( + f"the quit button's name must be exactly 'Quit (⌘Q)', observed {quit_name!r}") + assert quit_name == FOOTER_QUIT, ( + f"the quit button's name must be exactly 'Quit (⌘Q)' — the '(⌘Q)' shortcut hint " + f"is part of the label; observed {quit_name!r}") + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="panel AXRoleDescription reads 'system dialog' and each toggle's reads 'toggle button'") + def test_role_description_strings(self, ax): + w = rb_enter_main_window(ax) + assert w is not None, "the main panel window must be reachable via the 'Keyboard' status item" + + panel_desc = _attr(ax, w.id, "AXRoleDescription") + assert kit.rb_value(panel_desc, PANEL_ROLE_DESCRIPTION), ( + f"the panel's AXRoleDescription must be exactly 'system dialog', observed {panel_desc!r}") + assert panel_desc == PANEL_ROLE_DESCRIPTION, ( + f"the panel's AXRoleDescription must be exactly 'system dialog', observed {panel_desc!r}") + + boxes = ax.find(role="checkbox", root_id=w.id, max_results=10, max_depth=12) + assert len(boxes) >= 2, ( + f"the panel must expose the 2 settings toggles ('Global Quick Switch', " + f"'Launch at Login'), observed {len(boxes)} checkbox element(s)") + for box in boxes: + desc = _attr(ax, box.id, "AXRoleDescription") + assert kit.rb_value(desc, TOGGLE_ROLE_DESCRIPTION), ( + f"every settings checkbox's AXRoleDescription must be exactly 'toggle button', " + f"observed {desc!r}") + assert desc == TOGGLE_ROLE_DESCRIPTION, ( + f"every settings checkbox's AXRoleDescription must be exactly 'toggle button', " + f"observed {desc!r}") + + +# ═══════════════════════════════════════════════════════════════════════════════ +class TestAppListText: + """Text carried by the app-list rows: the row name labels and each row's + input-method picker radios.""" + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="every row picker's first radio is named 'Default' and its second radio is named 'U.S.'") + def test_picker_radio_labels(self, ax): + w = rb_enter_main_window(ax) + assert w is not None, "the main panel window must be reachable via the 'Keyboard' status item" + + groups = ax.find(role="radiogroup", root_id=w.id, max_results=20, max_depth=12) + assert len(groups) >= 5, ( + f"at least 5 app rows must each expose an input-method picker (radiogroup), " + f"observed {len(groups)}") + + seconds = [] + for i, g in enumerate(groups[:8]): + radios = ax.find(role="radio", root_id=g.id, max_results=6, max_depth=4) + names = [_txt(r.name) for r in radios] + assert len(radios) >= 2, ( + f"picker #{i} must hold 2 radios ('Default' and the input-method one), " + f"observed names {names}") + first = _txt(radios[0].name) + assert kit.rb_value(first, PICKER_FIRST), ( + f"picker #{i}'s FIRST radio must be named exactly 'Default', " + f"observed {first!r} (all names: {names})") + assert first == PICKER_FIRST, ( + f"picker #{i}'s FIRST radio must be named exactly 'Default', observed {first!r}") + second = _txt(radios[1].name) + assert second.strip(), ( + f"picker #{i}'s SECOND radio must carry non-empty text (the input-method " + f"name), observed {second!r}") + seconds.append(second) + + assert len(set(seconds)) == 1, ( + f"the second radio's name must be identical in every picker, observed {sorted(set(seconds))}") + assert kit.rb_value(seconds[0], PICKER_SECOND), ( + f"the second radio of every picker must be named exactly 'U.S.', observed {seconds[0]!r}") + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="row labels include 'Activity Monitor', 'App Store', 'Calculator', 'Calendar', 'Chess', 'Clock' ... (12 observed names), each non-empty") + def test_app_row_names_are_the_observed_apps(self, ax): + w = rb_enter_main_window(ax) + assert w is not None, "the main panel window must be reachable via the 'Keyboard' status item" + + names = _names(ax, w) + assert names, "with an empty search box the list must show app-row name labels, observed none" + + for expected in EXPECTED_APP_NAMES: + hit = next((n for n in names if n == expected), None) + assert kit.rb_value(hit, expected), ( + f"an app-row label whose text is exactly {expected!r} must be present; " + f"observed rows: {names}") + + for n in names: + assert n.strip() == n and n.strip(), ( + f"every app-row label must carry a non-empty, un-padded name, observed {n!r} " + f"in {names}") + + +# ═══════════════════════════════════════════════════════════════════════════════ +class TestMenuBarText: + """Text that lives on the menu bar surface (depth 0 — no window needed).""" + + @pytest.mark.rb(depth=0, jump_kind="value", + expect="status item is named 'Keyboard' and the AX application AXTitle is 'TypeSwitch'") + def test_status_item_and_app_title(self, ax): + item = status_item(ax) + assert item is not None, ( + "the app must publish exactly one menu-bar-extra item (named 'Keyboard') " + "in its extras menu bar") + item_name = _txt(item.name) + assert kit.rb_value(item_name, STATUS_ITEM_NAME), ( + f"the status item's name must be exactly 'Keyboard', observed {item_name!r}") + assert item_name == STATUS_ITEM_NAME, ( + f"the status item's name must be exactly 'Keyboard', observed {item_name!r}") + + # NOTE: ax.get(None, ...) returns {} (AXHelper._get_ref(None) misses the cache), + # so the application element is fetched by role and its AXTitle read from it. + app_els = ax.find(role="application", max_results=1, max_depth=0) + assert app_els, "the AX application element must be reachable" + app_title = _attr(ax, app_els[0].id, "AXTitle") + assert kit.rb_value(app_title, APP_AX_TITLE), ( + f"the AX application AXTitle must be exactly 'TypeSwitch', observed {app_title!r}") + assert app_title == APP_AX_TITLE, ( + f"the AX application AXTitle must be exactly 'TypeSwitch', observed {app_title!r}") + + +# ═══════════════════════════════════════════════════════════════════════════════ +class TestTextAfterInteraction: + """Text an interaction PRODUCES: the filtered row list, the shortcut recorder + string, the global-hotkey toast.""" + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="typing 'Calc' changes the row labels from the 13-app list to exactly ['Calculator']") + def test_search_calc_filters_text_to_calculator(self, ax): + w = rb_enter_main_window(ax) + assert w is not None, "the main panel window must be reachable via the 'Keyboard' status item" + assert search_field(ax, w) is not None, ( + "the panel must expose a search text_field (placeholder 'Search Apps... (⌘F)')") + + before = _names(ax, w) + assert len(before) >= 5, ( + f"the unfiltered list must show several app-row labels, observed {before}") + try: + set_search(ax, w, "Calc") + after = _names(ax, w) + + assert kit.rb_flip(before, after), ( + f"searching 'Calc' must CHANGE the row-label text; before={before} after={after}") + assert after == ["Calculator"], ( + f"searching 'Calc' must leave exactly one row label reading 'Calculator', " + f"observed {after}") + + screenshot_assert( + "text_test_search_filters_to_calculator", + "The TypeSwitch panel with 'Calc' typed into the top search field and only ONE " + "app row visible: the text 'Calculator' next to its app icon, with the small " + "two-segment 'Default' | 'U.S.' picker on the right. The settings text " + "'Global Quick Switch' / 'Launch at Login' and the 'Refresh (⌘R)' and " + "'Quit (⌘Q)' buttons remain at the bottom.") + finally: + set_search(ax, w, "") + + restored = _names(ax, w) + assert restored == before, ( + f"clearing the search box must restore the original row-label text {before}, " + f"observed {restored}") + + @pytest.mark.rb(depth=1, jump_kind="transition", + expect="typing 'zzzznotanapp' empties the row labels to [] while the 4 settings labels survive") + def test_search_no_match_empties_rows_keeps_chrome(self, ax): + w = rb_enter_main_window(ax) + assert w is not None, "the main panel window must be reachable via the 'Keyboard' status item" + assert search_field(ax, w) is not None, ( + "the panel must expose a search text_field (placeholder 'Search Apps... (⌘F)')") + + before = _names(ax, w) + assert len(before) >= 5, ( + f"the unfiltered list must show several app-row labels, observed {before}") + try: + set_search(ax, w, "zzzznotanapp") + after = _names(ax, w) + + assert kit.rb_flip(before, after), ( + f"searching 'zzzznotanapp' must CHANGE the row-label text; " + f"before={before} after={after}") + assert after == [], ( + f"searching 'zzzznotanapp' must leave NO app-row labels at all, observed {after}") + + survivors = set(_label_values(ax, w)) + missing = sorted(CTRL_LABELS - survivors) + assert not missing, ( + "the chrome text must survive an empty result — labels 'Global Quick Switch', " + "'Use shortcut to quickly switch between input methods', 'Launch at Login' and " + f"'Automatically start TypeSwitch when you log in' must all remain; missing {missing}") + finally: + set_search(ax, w, "") + + restored = _names(ax, w) + assert restored == before, ( + f"clearing the search box must restore the original row-label text {before}, " + f"observed {restored}") + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="with Global Quick Switch ON the recorder field (placeholder 'Record Shortcut') reads '⌃⇧Space'") + def test_shortcut_recorder_text(self, ax): + w = rb_enter_main_window(ax) + assert w is not None, "the main panel window must be reachable via the 'Keyboard' status item" + + box = toggle_for(ax, w, QUICK_SWITCH_LABEL) + assert box is not None, ( + "the row labelled 'Global Quick Switch' must own a toggle (checkbox)") + was_on = _is_on(toggle_value(ax, box.id)) + try: + assert _set_toggle(ax, box.id, True), ( + "the 'Global Quick Switch' toggle must be switchable ON (AXValue 1)") + time.sleep(1.2) + + recorder = _recorder_field(ax, w) + placeholders = [_attr(ax, t.id, "AXPlaceholderValue") + for t in ax.find(role="text_field", root_id=w.id, + max_results=8, max_depth=12)] + assert recorder is not None, ( + "with Global Quick Switch ON a shortcut recorder text_field with placeholder " + f"'Record Shortcut' must appear; observed placeholders {placeholders}") + + placeholder = _attr(ax, recorder.id, "AXPlaceholderValue") + assert kit.rb_value(placeholder, RECORDER_PLACEHOLDER), ( + f"the recorder field's AXPlaceholderValue must be exactly 'Record Shortcut', " + f"observed {placeholder!r}") + + # READ ONLY — pressing this field arms a global key grab (recon SAFETY). + value = _attr(ax, recorder.id, "AXValue") + assert kit.rb_value(value, RECORDER_VALUE), ( + f"the recorder field's AXValue must be exactly '⌃⇧Space', observed {value!r}") + assert value == RECORDER_VALUE, ( + f"the recorder field's AXValue must be exactly '⌃⇧Space', observed {value!r}") + finally: + _set_toggle(ax, box.id, was_on) + + @pytest.mark.rb(depth=1, jump_kind="value", + expect="⌃⇧Space raises a toast whose label text starts with 'Switched to: ' next to an image named 'Keyboard'") + def test_toast_text_after_global_hotkey(self, ax): + w = rb_enter_main_window(ax) + assert w is not None, "the main panel window must be reachable via the 'Keyboard' status item" + + box = toggle_for(ax, w, QUICK_SWITCH_LABEL) + assert box is not None, ( + "the row labelled 'Global Quick Switch' must own a toggle (checkbox)") + was_on = _is_on(toggle_value(ax, box.id)) + try: + assert _set_toggle(ax, box.id, True), ( + "the 'Global Quick Switch' toggle must be switchable ON (AXValue 1) so the " + "global ⌃⇧Space hotkey is live") + time.sleep(1.0) + + helpers.send_key(49, ["ctrl", "shift"]) + toast, text = rb_reach_toast(ax, w, timeout=3.0) + assert toast is not None, ( + "pressing ⌃⇧Space with Global Quick Switch ON must raise a toast window " + "carrying a label whose text starts with 'Switched to: '") + + # Only the PREFIX is asserted: what follows depends on the frontmost app + # (recon observed 'Switched to: U.S.' and 'Switched to: 默认'). + assert kit.rb_value(text, TOAST_PREFIX), ( + f"the toast label text must contain the exact prefix 'Switched to: ', " + f"observed {text!r}") + assert text.startswith(TOAST_PREFIX), ( + f"the toast label text must START with the exact prefix 'Switched to: ', " + f"observed {text!r}") + + icons = [_txt(i.name) for i in ax.find(role="image", root_id=toast.id, + max_results=10, max_depth=6)] + assert TOAST_ICON_NAME in icons, ( + f"the toast must also hold an image named exactly 'Keyboard', observed {icons}") + finally: + _set_toggle(ax, box.id, was_on) + + +# ═══════════════════════════════════════════════════════════════════════════════ +class TestAboutWindowText: + """Text that only exists two surfaces deep: panel -> app menu -> About dialog.""" + + @pytest.mark.rb(depth=2, jump_kind="value", + expect="About dialog labels read 'TypeSwitch', 'Version 0.3.5 (1)' and 'Copyright © 2024 ygsgdbd. All rights reserved.' beside an image named 'TypeSwitch icon'") + def test_about_window_text(self, ax): + try: + dlg = rb_enter_about_window(ax) + assert dlg is not None, ( + "pressing the app menu's 'About TypeSwitch' item must open a window whose " + "AXSubrole is 'AXDialog'") + + values = [_txt(e.value) for e in ax.find(role="label", root_id=dlg.id, + max_results=40, max_depth=8)] + + assert ABOUT_APP_NAME in values, ( + f"the About dialog must show a label whose text is exactly 'TypeSwitch', " + f"observed label values {values}") + + version = next((v for v in values if ABOUT_VERSION in v), None) + assert kit.rb_value(version, ABOUT_VERSION), ( + f"the About dialog must show a label containing exactly 'Version 0.3.5', " + f"observed label values {values}") + + copyright_line = next((v for v in values if v == ABOUT_COPYRIGHT), None) + assert kit.rb_value(copyright_line, ABOUT_COPYRIGHT), ( + "the About dialog must show a label whose text is exactly " + f"'Copyright © 2024 ygsgdbd. All rights reserved.', observed label values {values}") + + icons = [_txt(i.name) for i in ax.find(role="image", root_id=dlg.id, + max_results=10, max_depth=8)] + assert ABOUT_ICON_NAME in icons, ( + f"the About dialog must hold an image named exactly 'TypeSwitch icon', " + f"observed image names {icons}") + + screenshot_assert( + "text_test_about_window", + "A small (284x187) standard macOS About window showing the TypeSwitch app icon, " + "the app name text 'TypeSwitch', the line 'Version 0.3.5 (1)' and the copyright " + "line 'Copyright © 2024 ygsgdbd. All rights reserved.'.") + finally: + helpers.dismiss_menus(ax) diff --git a/macos/ygsgdbd-typeswitch/tests/testcase_counts.json b/macos/ygsgdbd-typeswitch/tests/testcase_counts.json new file mode 100644 index 0000000000000000000000000000000000000000..9af550071f863df379289b21908d5055bf2a1444 --- /dev/null +++ b/macos/ygsgdbd-typeswitch/tests/testcase_counts.json @@ -0,0 +1,39 @@ +{ + "ax_total": 62, + "vlm_total": 16, + "ax_by_lane": { + "test_ax_buttons.py": 9, + "test_ax_computation.py": 14, + "test_ax_menus.py": 6, + "test_ax_states.py": 11, + "test_ax_structure.py": 10, + "test_ax_text.py": 12 + }, + "vlm_by_dir": { + "buttons": 3, + "computation": 2, + "menus": 1, + "states": 3, + "structure": 4, + "text": 3 + }, + "vlm_names": [ + "buttons_quick_switch_toggle_on.png", + "buttons_refresh_button_rescan.png", + "buttons_row_picker_radio_selected.png", + "computation_test_search_calc_exact_row.png", + "computation_test_search_no_match_empty_result.png", + "menus_about_dialog.png", + "states_test_picker_radio_group_is_mutually_exclusive.png", + "states_test_picker_selection_is_per_row.png", + "states_test_quick_switch_on_adds_shortcut_recorder.png", + "structure_test_main_panel_window.png", + "structure_test_no_match_search.png", + "structure_test_quick_switch_recorder.png", + "structure_test_search_filter_shrinks_list.png", + "text_test_about_window.png", + "text_test_search_filters_to_calculator.png", + "text_test_settings_labels.png" + ], + "frozen_at": "stage2_finalize" +} \ No newline at end of file diff --git a/macos/ygsgdbd-typeswitch/tests/verifier_helpers.py b/macos/ygsgdbd-typeswitch/tests/verifier_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..ce369cdae8db3a7427890d1636f8f5a3201dbef1 --- /dev/null +++ b/macos/ygsgdbd-typeswitch/tests/verifier_helpers.py @@ -0,0 +1,753 @@ +""" +verifier_helpers.py — High-level AX testing patterns for macOS app verification. + +v6 core library. Encodes all robust testing patterns as reusable functions +so verifier agents call high-level APIs instead of building from scratch. + +Depends on: ax_helpers.py (AXHelper class) +""" + +import datetime +import os +import re +import signal +import subprocess +import time +from collections import Counter + +# --------------------------------------------------------------------------- +# Key codes (macOS virtual key codes) +# --------------------------------------------------------------------------- +KC_LEFT_ARROW = 123 +KC_RIGHT_ARROW = 124 +KC_UP_ARROW = 126 +KC_DOWN_ARROW = 125 +KC_SPACE = 49 +KC_RETURN = 36 +KC_TAB = 48 +KC_ESCAPE = 53 +KC_Q = 12 +KC_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": , "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)" + ) diff --git a/macos/ygsgdbd-typeswitch/vlm_assertions.json b/macos/ygsgdbd-typeswitch/vlm_assertions.json new file mode 100644 index 0000000000000000000000000000000000000000..a07a6382390053767717e5afa141ecf5b7ac2781 --- /dev/null +++ b/macos/ygsgdbd-typeswitch/vlm_assertions.json @@ -0,0 +1,231 @@ +{ + "schema_version": 2, + "instance_id": "macos/ygsgdbd-typeswitch", + "grading": { + "mode": "deferred", + "model": null, + "scored_separately": true + }, + "totals": { + "assertions": 16, + "with_verdict": 0, + "calibrated": 0, + "usable": null, + "scored_records": 0, + "unbacked_records": 0 + }, + "assertions": [ + { + "id": "buttons_refresh_button_rescan.png", + "screenshot": "buttons_refresh_button_rescan.png", + "assertion": "The dark 600x500 TypeSwitch panel is anchored at the top-right of the screen just under the menu bar. Its rounded search field at the top contains 'RBBtnProbe' and, after the small bottom-right text button 'Refresh (⌘R)' was pressed, exactly ONE app row is visible: an app icon, the name 'RBBtnProbe', and a small two-segment picker (Default | U.S.) on the right. The 'Global Quick Switch' row with the sub-line 'Use shortcut to quickly switch between input methods' and its switch, the 'Launch at Login' row with 'Automatically start TypeSwitch when you log in' and its switch, and the footer buttons 'Refresh (⌘R)' and 'Quit (⌘Q)' are all still visible.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "buttons_refresh_button_rescan.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "buttons_quick_switch_toggle_on.png", + "screenshot": "buttons_quick_switch_toggle_on.png", + "assertion": "The dark 600x500 TypeSwitch panel at the top-right of the screen with 'Global Quick Switch' switched ON: the switch at the right of the 'Global Quick Switch' row is in its filled/ON position and a NEW shortcut recorder field displaying '⌃⇧Space' has appeared to the LEFT of that switch. The sub-line 'Use shortcut to quickly switch between input methods' sits below it, the 'Launch at Login' row and its switch are unchanged, and the footer text buttons 'Refresh (⌘R)' and 'Quit (⌘Q)' are still at the bottom-right.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "buttons_quick_switch_toggle_on.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "buttons_row_picker_radio_selected.png", + "screenshot": "buttons_row_picker_radio_selected.png", + "assertion": "The dark TypeSwitch panel with 'Calculator' typed in the top search field shows exactly ONE app row: the Calculator icon, the name 'Calculator', and a two-segment picker at the right whose SECOND segment (the input method, e.g. 'U.S.') is now highlighted/selected instead of the 'Default' segment. Below the empty rest of the list are the 'Global Quick Switch' and 'Launch at Login' rows with their switches, and the footer buttons 'Refresh (⌘R)' and 'Quit (⌘Q)'.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "buttons_row_picker_radio_selected.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "computation_test_search_calc_exact_row.png", + "screenshot": "computation_test_search_calc_exact_row.png", + "assertion": "TypeSwitch's dark 600x500 panel is anchored at the top-right of the screen under the menu bar. The search field at the top contains the text 'Calc' and the list below shows exactly ONE app row: the Calculator icon, the name 'Calculator', and a two-segment Default | U.S. picker on the right. The 'Global Quick Switch' and 'Launch at Login' rows and the 'Refresh (⌘R)' / 'Quit (⌘Q)' buttons are still visible at the bottom.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "computation_test_search_calc_exact_row.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "computation_test_search_no_match_empty_result.png", + "screenshot": "computation_test_search_no_match_empty_result.png", + "assertion": "TypeSwitch's dark 600x500 panel with 'zzzznotanapp' typed in the top search field and NO app rows at all — the list area is completely blank. The 'Global Quick Switch' row (with its sub-line 'Use shortcut to quickly switch between input methods'), the 'Launch at Login' row and the 'Refresh (⌘R)' / 'Quit (⌘Q)' text buttons all remain visible.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "computation_test_search_no_match_empty_result.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "menus_about_dialog.png", + "screenshot": "menus_about_dialog.png", + "assertion": "The small standard macOS About window (284x187) is visible, showing the TypeSwitch app icon, the app name 'TypeSwitch', the line 'Version 0.3.5 (1)' and 'Copyright © 2024 ygsgdbd. All rights reserved.'", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "menus_about_dialog.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "states_test_quick_switch_on_adds_shortcut_recorder.png", + "screenshot": "states_test_quick_switch_on_adds_shortcut_recorder.png", + "assertion": "Global Quick Switch is ON in the dark 600x500 TypeSwitch panel anchored top-right under the menu bar. On the 'Global Quick Switch' row (above 'Launch at Login') the switch on the right is in its ON / filled position, and a shortcut recorder field showing the key combination ⌃⇧Space is now displayed immediately to the LEFT of that switch. The 'Launch at Login' row below is unchanged, and the app list with its Default | U.S. pickers plus the 'Refresh (⌘R)' and 'Quit (⌘Q)' buttons are still visible.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "states_test_quick_switch_on_adds_shortcut_recorder.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "states_test_picker_radio_group_is_mutually_exclusive.png", + "screenshot": "states_test_picker_radio_group_is_mutually_exclusive.png", + "assertion": "The dark 600x500 TypeSwitch panel has 'Calculator' typed in the search field at the top and exactly ONE app row visible: the Calculator icon, the name 'Calculator', and a small two-segment picker on the right. In that picker the NON-Default segment ('U.S.') is now highlighted / selected and the 'Default' segment is NOT highlighted — exactly one segment is selected. Below, the 'Global Quick Switch' and 'Launch at Login' rows with their switches and the 'Refresh (⌘R)' / 'Quit (⌘Q)' buttons are unchanged.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "states_test_picker_radio_group_is_mutually_exclusive.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "states_test_picker_selection_is_per_row.png", + "screenshot": "states_test_picker_selection_is_per_row.png", + "assertion": "The TypeSwitch panel has 'cal' typed in the search field and exactly TWO app rows visible ('Calculator' and 'Calendar', each with its icon and a two-segment Default | U.S. picker on the right). In the FIRST / topmost row the non-Default segment ('U.S.') is highlighted, while in the SECOND row the 'Default' segment is still the highlighted one — proving the input-method selection is stored per app row. The two settings switches at the bottom are unchanged.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "states_test_picker_selection_is_per_row.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "structure_test_main_panel_window.png", + "screenshot": "structure_test_main_panel_window.png", + "assertion": "A dark 600x500 TypeSwitch panel anchored at the TOP-RIGHT of the screen just under the menu bar. Top: a rounded search field spanning the panel width with placeholder 'Search Apps... (⌘F)'. Middle: a scrolling list of app rows, each with an app icon on the left, the app name beside it and a small two-segment picker (Default | U.S.) on the right. Bottom: a 'Global Quick Switch' row with the sub-line 'Use shortcut to quickly switch between input methods' and a switch on the right, then a 'Launch at Login' row with 'Automatically start TypeSwitch when you log in' and a second switch; bottom-right two small text buttons 'Refresh (⌘R)' and 'Quit (⌘Q)'.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "structure_test_main_panel_window.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "structure_test_quick_switch_recorder.png", + "screenshot": "structure_test_quick_switch_recorder.png", + "assertion": "The dark TypeSwitch panel with the 'Global Quick Switch' row at the bottom now ALSO showing a shortcut recorder field displaying '⌃⇧Space' to the LEFT of the switch, and that switch is in its ON (filled/blue) position. The 'Launch at Login' row, the app list above and the 'Refresh (⌘R)' / 'Quit (⌘Q)' buttons are unchanged.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "structure_test_quick_switch_recorder.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "structure_test_search_filter_shrinks_list.png", + "screenshot": "structure_test_search_filter_shrinks_list.png", + "assertion": "The dark TypeSwitch panel with 'Calc' typed into the top search field and only ONE app row visible in the list area: the Calculator icon, the name 'Calculator' and its two-segment 'Default | U.S.' picker on the right. The rest of the list area is empty; the 'Global Quick Switch' and 'Launch at Login' rows and the 'Refresh (⌘R)' / 'Quit (⌘Q)' buttons remain at the bottom.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "structure_test_search_filter_shrinks_list.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "structure_test_no_match_search.png", + "screenshot": "structure_test_no_match_search.png", + "assertion": "The dark TypeSwitch panel with 'zzzznotanapp' in the top search field and NO app rows at all - the whole list area is blank. Only the two settings rows ('Global Quick Switch' with its sub-line and switch, 'Launch at Login' with its sub-line and switch) and the bottom-right 'Refresh (⌘R)' and 'Quit (⌘Q)' buttons remain.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "structure_test_no_match_search.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "text_test_settings_labels.png", + "screenshot": "text_test_settings_labels.png", + "assertion": "The dark 600x500 TypeSwitch panel anchored top-right under the menu bar. Bottom half reads the settings text: the row 'Global Quick Switch' with the sub-line 'Use shortcut to quickly switch between input methods' and a switch on the right, then 'Launch at Login' with 'Automatically start TypeSwitch when you log in' and a second switch. Bottom-right shows the two small text buttons 'Refresh (⌘R)' and 'Quit (⌘Q)'. Top shows the search field placeholder 'Search Apps... (⌘F)'.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "text_test_settings_labels.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "text_test_search_filters_to_calculator.png", + "screenshot": "text_test_search_filters_to_calculator.png", + "assertion": "The TypeSwitch panel with 'Calc' typed into the top search field and only ONE app row visible: the text 'Calculator' next to its app icon, with the small two-segment 'Default' | 'U.S.' picker on the right. The settings text 'Global Quick Switch' / 'Launch at Login' and the 'Refresh (⌘R)' and 'Quit (⌘Q)' buttons remain at the bottom.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "text_test_search_filters_to_calculator.png", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "text_test_about_window.png", + "screenshot": "text_test_about_window.png", + "assertion": "A small (284x187) standard macOS About window showing the TypeSwitch app icon, the app name text 'TypeSwitch', the line 'Version 0.3.5 (1)' and the copyright line 'Copyright © 2024 ygsgdbd. All rights reserved.'.", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "text_test_about_window.png", + "rigor": null, + "verdict": null, + "calibration": null + } + ], + "merged_from_files": 6, + "source_shapes": { + "dict_str": 16 + } +} \ No newline at end of file diff --git a/macos/zotero-zotero/COPYING b/macos/zotero-zotero/COPYING new file mode 100644 index 0000000000000000000000000000000000000000..b14d531f57df630c8668473475c602966561c83e --- /dev/null +++ b/macos/zotero-zotero/COPYING @@ -0,0 +1,681 @@ +Zotero is Copyright © 2018 Corporation for Digital Scholarship, +Vienna, Virginia, USA http://digitalscholar.org + +Copyright © 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017 +Roy Rosenzweig Center for History and New Media, George Mason University, +Fairfax, Virginia, USA http://zotero.org + +The Corporation for Digital Scholarship distributes the Zotero source code +under the GNU Affero General Public License, version 3 (AGPLv3). The full text +of this license is given below. + +The Zotero name is a registered trademark of the Corporation for Digital Scholarship. +See http://zotero.org/trademark for more information. + +Third-party copyright in this distribution is noted where applicable. + +All rights not expressly granted are reserved. + +========================================================================= + + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + 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 for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification 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 of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. 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 work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a 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 visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation 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 to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients 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 to +produce it from the Program, in the form of source code under the +terms 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 independent +works, 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 not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-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 excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the 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 install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional 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 you +add to a covered work, you may (if authorized by the copyright holders of +that 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 "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form 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 expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered 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 automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent 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 anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain 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 limiting +any implied license or other defenses to infringement that may +otherwise 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 or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License 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 the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES 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 OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy 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 greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + 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 . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific 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 +. diff --git a/macos/zotero-zotero/instance.json b/macos/zotero-zotero/instance.json new file mode 100644 index 0000000000000000000000000000000000000000..6ba30c7d9409604e82bafa018475dd70a6a23785 --- /dev/null +++ b/macos/zotero-zotero/instance.json @@ -0,0 +1,10 @@ +{ + "schema_version": 1, + "instance_id": "macos/zotero-zotero", + "platform": "macos", + "repo": "https://github.com/zotero/zotero", + "commit": "615ba3c1789e790f6bd84f7735ac4973a688495b", + "patches": [], + "package": null, + "license": null +} \ No newline at end of file diff --git a/macos/zotero-zotero/reference/build.sh b/macos/zotero-zotero/reference/build.sh new file mode 100644 index 0000000000000000000000000000000000000000..3c0db8f4bbf25d1623679835ded108a4dda6b6ad --- /dev/null +++ b/macos/zotero-zotero/reference/build.sh @@ -0,0 +1,298 @@ +#!/bin/bash +# +# Standalone, self-contained build script for Zotero (macOS). +# +# Reproduces the entire build from a fresh `git clone` into which only this +# script (and launch.sh) have been copied: +# 1. Checks out git submodules (reader, note-editor, translators, etc.) +# 2. Fetches the Git-LFS macOS updater payload (app/mac/updater.tar.xz) +# 3. npm install + `npm run build` (transpile JS/JSX, SCSS, browserify) +# 4. Downloads + patches the Gecko/Firefox runtime (fetch_xulrunner) +# 5. Packages everything into Zotero.app via app/build.sh +# +# The final Zotero.app is copied to ${APP_OUTPUT_DIR:-