"""AX structure tests for massCode (Electron/Vue snippet manager).""" 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__))) def screenshot_assert(test_name, description, results_dir=None): results_dir = results_dir or 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 _enable_web_ax(ax, timeout=10.0): """Chromium/Electron builds its web-content AX tree only once an AT announces itself.""" from ApplicationServices import AXUIElementSetAttributeValue try: AXUIElementSetAttributeValue(ax._app_ref, "AXEnhancedUserInterface", True) except Exception: pass deadline = time.time() + timeout while time.time() < deadline: if ax.find(role="label", max_results=1, max_depth=16): return True time.sleep(0.25) return False def app_ready(ax): """MANDATORY bring-up: build the web AX tree and foreground the app (every massCode menu handler needs BrowserWindow.getFocusedWindow()).""" _enable_web_ax(ax) try: from AppKit import NSRunningApplication a = NSRunningApplication.runningApplicationWithProcessIdentifier_(int(ax.get_pid())) if a is not None: a.activateWithOptions_(1 << 1) except Exception: pass time.sleep(0.4) return ax def labels(ax): return [l.value for l in ax.find(role="label", max_results=250, max_depth=26) if l.value] def field(ax, placeholder): for t in ax.find(role="text_field", max_results=15, max_depth=26): if (t.name or "") == placeholder: return t return None def press_labelled_group(ax, text): for g in ax.find(role="group", max_results=600, max_depth=26): if "AXPress" not in (g.actions or []): continue labs = ax.find(role="label", root_id=g.id, max_results=3, max_depth=2) if any((l.value or "").strip() == text for l in labs): return ax.action(g.id, "AXPress") return False def webarea(ax): w = ax.find(role="webarea", max_results=1, max_depth=6) return w[0] if w else None def webarea_buttons(ax): """(x, y, element) for every button inside the web content, DOM order.""" wa = webarea(ax) if wa is None: return [] out = [] for b in ax.find(role="button", root_id=wa.id, max_results=30, max_depth=26): p = ax.get(b.id, ["AXPosition"]).get("AXPosition", "") or "" try: x = float(p.split("x:")[1].split(" ")[0]) y = float(p.split("y:")[1].split(" ")[0]) except Exception: x = y = -1.0 out.append((x, y, b)) return out def menu_el(ax, path): items = ax.find(role="menu_bar_item", name=path[0], max_results=3, max_depth=3) if not items: return None cur = items[0] for lbl in path[1:]: kids = ax.find(role="menu_item", name=lbl, root_id=cur.id, max_results=3, max_depth=3) if not kids: return None cur = kids[0] return cur def rb_enter_menu(ax, path, settle=1.2): """NAVIGATION: fire a menu item, crossing into whatever surface it opens.""" el = menu_el(ax, path) if el is None: return False ok = ax.action(el.id, "AXPress") time.sleep(settle) return ok def rb_enter_close_surface(ax, settle=1.3): """NAVIGATION: leave Preferences / Developer Tools / Presentation via the single close button inside the web content.""" wa = webarea(ax) if wa is None: return False btns = ax.find(role="button", root_id=wa.id, max_results=5, max_depth=24) if not btns: return False ok = ax.action(btns[0].id, "AXPress") time.sleep(settle) return ok def go_home(ax): """Normalise: leave any full-window surface, then put the sidebar in LIBRARY mode.""" for _ in range(3): ls = labels(ax) if "Preferences" in ls or "Developer Tools" in ls or "1 / 0" in ls: if rb_enter_close_surface(ax): continue break if "Inbox" not in labels(ax): press_labelled_group(ax, "LIBRARY") time.sleep(0.8) return ax def wait_label(ax, text, timeout=3.0): """Poll for a label value to (re)appear. Returns True as soon as it is present.""" deadline = time.time() + timeout while True: if text in labels(ax): return True if time.time() >= deadline: return False time.sleep(0.3) # --------------------------------------------------------------------------- # GATE — existence of the top-level surfaces (3 tests, depth=0, jump_kind="none") # --------------------------------------------------------------------------- class TestGateStructure: @pytest.mark.rb(depth=0, jump_kind="none") def test_gate_window_and_webarea(self, ax): app_ready(ax) windows = ax.find(role="window", max_results=6, max_depth=1) assert len(windows) == 1, f"expected exactly one AX window, got {len(windows)}" win = windows[0] assert (win.name or "") == "massCode", f"window title was {win.name!r}" webs = ax.find(role="webarea", root_id=win.id, max_results=3, max_depth=6) assert webs, "no webarea inside the massCode window" assert any((w.name or "") == "massCode" for w in webs), \ f"webarea names were {[w.name for w in webs]!r}" screenshot_assert( "structure_home_layout", "massCode main window shows a three-column layout: a left sidebar with a " "LIBRARY / TAGS header above Inbox, Favorites, All Snippets and Trash rows and a " "FOLDERS section with a + button; a middle snippet-list column with a 'Search...' " "box and a + button; and a wide right-hand editor pane.", RESULTS_DIR, ) @pytest.mark.rb(depth=0, jump_kind="none") def test_gate_menu_bar_has_all_app_menus(self, ax): app_ready(ax) bars = ax.find(role="menu_bar", max_results=3, max_depth=1) assert bars, "no AXMenuBar found for massCode" names = {m.name for m in ax.find(role="menu_bar_item", max_results=15, max_depth=2)} expected = {"massCode", "File", "View", "Edit", "Editor", "Markdown", "History", "Help"} assert expected <= names, f"missing menus {sorted(expected - names)}; saw {sorted(n for n in names if n)}" screenshot_assert( "structure_menu_bar", "massCode is the frontmost app and the macOS menu bar at the top of the screen " "shows its menu titles in order: massCode, File, View, Edit, Editor, Markdown, " "History, Help. No menu is dropped open.", RESULTS_DIR, ) @pytest.mark.rb(depth=0, jump_kind="none") def test_gate_home_shell_widgets(self, ax): app_ready(ax) go_home(ax) ls = labels(ax) for want in ("Inbox", "Favorites", "All Snippets", "Trash", "FOLDERS"): assert want in ls, f"home sidebar label {want!r} missing; saw {ls[:40]!r}" assert field(ax, "Search...") is not None, "snippet-list 'Search...' text field missing" btns = webarea_buttons(ax) assert len(btns) >= 2, f"expected >=2 in-page buttons (add-folder + add-snippet), got {len(btns)}" screenshot_assert( "structure_home_shell_widgets", "The massCode window's left sidebar lists the LIBRARY / TAGS header with the Inbox, " "Favorites, All Snippets and Trash rows and a FOLDERS section header carrying a small " "+ button; the middle snippet-list column shows a 'Search...' input box with a + " "button beside it.", RESULTS_DIR, ) # --------------------------------------------------------------------------- # SHAPE DELTAS — trigger flips the tree shape, then it is restored (4 tests) # --------------------------------------------------------------------------- class TestShapeDeltas: @pytest.mark.rb(depth=1, jump_kind="transition", expect="home shell (All Snippets sidebar row) replaced by the Preferences " "surface with the Storage/Editor/Markdown/Appearance/Language rail, " "then restored on close") def test_settings_replaces_home_shape(self, ax): app_ready(ax) go_home(ax) before = "All Snippets" in labels(ax) assert before is True, "home shell was not showing before opening Settings" assert rb_enter_menu(ax, ["massCode", "Settings…"], settle=1.6), \ "could not press massCode > Settings..." ls = labels(ax) after = "All Snippets" in ls assert kit.rb_flip(before, after, expect="home shell replaced by the Preferences surface") assert "Preferences" in ls, f"no 'Preferences' label after Settings...; saw {ls[:40]!r}" rail = {"Storage", "Editor", "Markdown", "Appearance", "Language"} assert rail <= set(ls), f"Preferences rail incomplete, missing {sorted(rail - set(ls))}" screenshot_assert( "structure_preferences_surface", "The window content is replaced by the Preferences page: a 'Preferences' title, a " "left rail listing Storage, Editor, Markdown, Appearance and Language, and the " "Storage pane on the right with a storage-path field and Move/Open/New/Reload " "Storage buttons.", RESULTS_DIR, ) rb_enter_close_surface(ax) assert wait_label(ax, "All Snippets", timeout=3.0), \ "home shell did not come back after closing Preferences" @pytest.mark.rb(depth=1, jump_kind="transition", expect="home shell (All Snippets sidebar row) replaced by the Developer Tools " "surface listing Case Converter / Hash Generator / Base64 Encoder " "/ Decoder, then restored on close") def test_devtools_replaces_home_shape(self, ax): app_ready(ax) go_home(ax) before = "All Snippets" in labels(ax) assert before is True, "home shell was not showing before opening Developer Tools" assert rb_enter_menu(ax, ["massCode", "Developer Tools…"], settle=1.6), \ "could not press massCode > Developer Tools..." ls = labels(ax) after = "All Snippets" in ls assert kit.rb_flip(before, after, expect="home shell replaced by the Developer Tools surface") for want in ("Developer Tools", "Case Converter", "Hash Generator", "Base64 Encoder / Decoder"): assert want in ls, f"Developer Tools label {want!r} missing; saw {ls[:40]!r}" assert after is False, "home 'All Snippets' row still present on the Developer Tools surface" screenshot_assert( "structure_devtools_surface", "The window content is replaced by the Developer Tools page: a 'Developer Tools' " "title, a left rail grouped into Text Tools, Cryptography / Security and Encoders / " "Decoders listing tools such as Case Converter, Sort Lines, Hash Generator and " "Base64 Encoder / Decoder, and the selected tool's input/output pane on the right. " "The Inbox / All Snippets sidebar is gone.", RESULTS_DIR, ) rb_enter_close_surface(ax) assert wait_label(ax, "All Snippets", timeout=3.0), \ "home shell did not come back after closing Developer Tools" @pytest.mark.rb(depth=0, jump_kind="transition", expect="sidebar TAGS row hides the LIBRARY rows (Inbox/Favorites/All " "Snippets/Trash/FOLDERS); pressing LIBRARY brings FOLDERS back") def test_tags_mode_hides_library_rows(self, ax): app_ready(ax) go_home(ax) before = "FOLDERS" in labels(ax) assert before is True, "FOLDERS section was not showing in LIBRARY mode" assert press_labelled_group(ax, "TAGS"), "could not press the sidebar TAGS row" time.sleep(1.2) ls = labels(ax) after = "FOLDERS" in ls assert kit.rb_flip(before, after, expect="LIBRARY rows (Inbox/Favorites/All Snippets/Trash/FOLDERS) " "hidden in TAGS mode") assert after is False, "FOLDERS still present in TAGS mode" for gone in ("Inbox", "Favorites", "Trash"): assert gone not in ls, f"LIBRARY row {gone!r} still present in TAGS mode" screenshot_assert( "structure_tags_sidebar", "The sidebar is switched to TAGS mode: the Inbox, Favorites, All Snippets and Trash " "rows and the whole FOLDERS section are gone, leaving the LIBRARY / TAGS header with " "TAGS active above a (possibly empty) tag list; the snippet-list and editor columns " "are still on the right.", RESULTS_DIR, ) press_labelled_group(ax, "LIBRARY") time.sleep(1.0) assert "FOLDERS" in labels(ax), "FOLDERS did not come back after pressing LIBRARY" # --------------------------------------------------------------------------- # REACH — cross into a surface and back (2 tests) # --------------------------------------------------------------------------- class TestReachSurfaces: @pytest.mark.rb(depth=1, jump_kind="reach", expect="Preferences surface replaces the home shell") def test_reach_preferences_surface(self, ax): app_ready(ax) go_home(ax) before = kit.rb_showing(ax) assert rb_enter_menu(ax, ["massCode", "Settings…"], settle=1.6), \ "could not press massCode > Settings..." after = kit.rb_showing(ax) assert kit.rb_reach(before, after, target="Preferences", source="All Snippets") screenshot_assert( "structure_reach_preferences", "The Preferences page fills the massCode window: a 'Preferences' title with a left " "rail of Storage, Editor, Markdown, Appearance and Language and the Storage pane on " "the right; the home sidebar with Inbox / All Snippets / Trash is no longer visible.", RESULTS_DIR, ) rb_enter_close_surface(ax)