"""AX text-content 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.""" _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 fields(ax): return ax.find(role="text_field", max_results=12, max_depth=26) def headings(ax): return [h.name for h in ax.find(role="heading", max_results=30, max_depth=26) if h.name] 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 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.""" 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 rb_enter_preferences_pane(ax, pane, settle=1.2): """NAVIGATION: open Preferences (if needed) and select a pane in its left rail.""" if "Preferences" not in labels(ax): rb_enter_menu(ax, ["massCode", "Settings…"], settle=1.6) ok = press_labelled_group(ax, pane) time.sleep(settle) return ok def rb_enter_devtool(ax, tool_name, settle=1.3): """NAVIGATION: open Developer Tools (if needed) and select a tool in its left rail.""" if "Developer Tools" not in labels(ax): rb_enter_menu(ax, ["massCode", "Developer Tools…"], settle=1.6) ok = press_labelled_group(ax, tool_name) time.sleep(settle) return ok def rb_enter_new_snippet(ax): """NAVIGATION: create + select a fresh snippet (the editor surface).""" return rb_enter_menu(ax, ["File", "New Snippet"], settle=1.6) def esc(): subprocess.run(["osascript", "-e", 'tell application "System Events" to key code 53'], capture_output=True, timeout=5) time.sleep(0.4) def go_home(ax): 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 # ── local read-only helpers (no navigation) ────────────────────────────────── def button_names(ax, root_id=None): """Trimmed AXTitle/AXDescription of every reachable button.""" kw = {"role": "button", "max_results": 60, "max_depth": 26} if root_id: kw["root_id"] = root_id return [(b.name or "").strip() for b in ax.find(**kw)] def named_button(ax, name, root_id=None): kw = {"role": "button", "max_results": 60, "max_depth": 26} if root_id: kw["root_id"] = root_id for b in ax.find(**kw): if (b.name or "").strip() == name: return b return None def popup_values(ax): return [(p.value or "") for p in ax.find(role="popup", max_results=15, max_depth=26)] def first_label_matching(ax_labels, pattern): rx = re.compile(pattern) for l in ax_labels: if rx.match((l or "").strip()): return (l or "").strip() return None def first_label_startswith(ax_labels, prefix): for l in ax_labels: if (l or "").strip().startswith(prefix): return (l or "").strip() return None def sheets(ax): return ax.find(role="sheet", max_results=5, max_depth=4) # ── tests ──────────────────────────────────────────────────────────────────── class TestHomeText: """Text-bearing nodes on the home surface (window title + sidebar + search).""" @pytest.mark.rb(depth=0, jump_kind="none", expect="window and webarea titled 'massCode'; sidebar text " "LIBRARY / TAGS / Inbox / Favorites / All Snippets / Trash / FOLDERS") def test_window_and_sidebar_text(self, ax): app_ready(ax) go_home(ax) wins = ax.find(role="window", max_results=3, max_depth=1) assert wins, "no AXWindow exposed by the app" win_title = (wins[0].name or "") assert "massCode" in win_title, f"window AXTitle={win_title!r} (expected 'massCode')" assert win_title.strip() == "massCode", f"window AXTitle={win_title!r}" wa = webarea(ax) assert wa is not None, "no webarea (web content AX tree missing)" assert (wa.name or "").strip() == "massCode", f"webarea AXTitle={wa.name!r}" ls = labels(ax) assert ls, "no AXStaticText nodes at all — web content has no text" for want in ("LIBRARY", "TAGS", "Inbox", "Favorites", "All Snippets", "Trash", "FOLDERS"): assert want in ls, f"sidebar label {want!r} missing; labels={sorted(set(ls))[:40]}" # every sidebar label we matched must be non-empty readable text assert all((l or "").strip() for l in ls if l is not None and l != "") hs = headings(ax) assert "LIBRARY/TAGS" in hs, f"headings={hs}" assert "FOLDERS" in hs, f"headings={hs}" search = field(ax, "Search...") assert search is not None, "no text_field titled 'Search...'" screenshot_assert( "text_home_sidebar", "massCode home window. The left sidebar shows the 'LIBRARY / TAGS' switcher " "header, then the four system rows Inbox, Favorites, All Snippets and Trash, " "then a 'FOLDERS' section header with a '+' button and a 'Default' folder row. " "The middle column shows an empty 'Search...' box with a '+' add-snippet button; " "the window title reads 'massCode'.") @pytest.mark.rb(depth=0, jump_kind="none", expect="search box placeholder 'Search...'; empty editor pane reads " "'No Snippet Selected'") def test_search_placeholder_and_empty_editor_text(self, ax): app_ready(ax) go_home(ax) search = field(ax, "Search...") assert search is not None, "no text_field titled 'Search...'" assert (search.name or "") == "Search...", f"placeholder={search.name!r}" # Trash is empty -> selecting it clears the selection, so the editor column # collapses to a single explanatory label. assert press_labelled_group(ax, "Trash"), "could not press the sidebar 'Trash' row" time.sleep(1.0) ls = labels(ax) assert "No Snippet Selected" in ls, \ f"empty-editor label missing; labels={sorted(set(ls))[:40]}" press_labelled_group(ax, "Inbox") time.sleep(0.8) class TestPreferencesText: """Text living on the Preferences surface (depth 1 — reached via massCode ▸ Settings…).""" @pytest.mark.rb(depth=1, jump_kind="value", expect="Preferences rail: Storage/Editor/Markdown/Appearance/Language") def test_preferences_rail_labels(self, ax): app_ready(ax) assert rb_enter_menu(ax, ["massCode", "Settings…"], settle=1.6), \ "menu massCode ▸ Settings… did not fire" ls = labels(ax) observed = sorted(set(ls) & {"Storage", "Editor", "Markdown", "Appearance", "Language"}) expected = sorted(["Appearance", "Editor", "Language", "Markdown", "Storage"]) assert kit.rb_value(observed, expected), \ f"Preferences rail text = {observed} (expected {expected}); labels={sorted(set(ls))[:40]}" assert "Preferences" in headings(ax), f"headings={headings(ax)}" rb_enter_close_surface(ax) @pytest.mark.rb(depth=1, jump_kind="value", expect="Storage pane: ' snippets.' count, storage path ending " "'/massCode', the massCode-v1.0 migrate sentence and 6 storage buttons") def test_preferences_storage_pane_text(self, ax): app_ready(ax) assert rb_enter_preferences_pane(ax, "Storage"), \ "could not select the 'Storage' pane in the Preferences rail" ls = labels(ax) assert "Migrate" in ls, f"'Migrate' section label missing; labels={sorted(set(ls))[:40]}" assert "Count" in ls, f"'Count' label missing; labels={sorted(set(ls))[:40]}" count_text = first_label_matching(ls, r"^\d+ snippets?\.$") assert kit.rb_value(bool(count_text), True), \ f"no ' snippets.' count label; labels={sorted(set(ls))[:40]}" # long sentence — AX truncates it, so prefix-match only migrate_text = first_label_startswith( ls, "To migrate from massCode v1.0 select the folder") assert migrate_text is not None, \ f"massCode-v1.0 migrate sentence missing; labels={sorted(set(ls))[:40]}" names = button_names(ax) for want in ("Move Storage", "Open Storage", "New Storage", "Reload Storage", "From massCode v1.0", "From SnippetsLab"): assert want in names, f"storage button {want!r} missing; buttons={names}" path = None for t in fields(ax): v = (t.value or "") if v.endswith("/massCode"): path = v break assert path, f"no storage-path text_field; values={[(t.value or '') for t in fields(ax)]}" assert kit.rb_value(path[-9:], "/massCode"), f"storage path = {path!r}" screenshot_assert( "text_preferences_storage", "massCode Preferences page, title 'Preferences'. The left rail lists " "Storage / Editor / Markdown / Appearance / Language with 'Storage' selected. " "The Storage pane shows a path field whose value ends in '/massCode', the four " "buttons Move Storage / Open Storage / New Storage / Reload Storage, a 'Count' " f"row reading '{count_text}', and a 'Migrate' section whose text begins " "'To migrate from massCode v1.0 select the folder containing the database files.' " "above the From massCode v1.0 and From SnippetsLab buttons.") rb_enter_close_surface(ax) @pytest.mark.rb(depth=1, jump_kind="value", expect="all nine Editor preference labels present") def test_preferences_editor_pane_text(self, ax): app_ready(ax) assert rb_enter_preferences_pane(ax, "Editor"), \ "could not select the 'Editor' pane in the Preferences rail" ls = set(labels(ax)) expected = ["Font Size", "Font Family", "Wrap", "Tab Size", "Highlight Line", "Match Brackets", "Trailing Comma", "Semi", "Single Quote"] missing = [e for e in expected if e not in ls] assert kit.rb_value(missing, []), \ f"Editor pane labels missing: {missing}; labels={sorted(ls)[:40]}" hs = headings(ax) assert "Editor" in hs, f"headings={hs}" assert "Prettier" in hs, f"headings={hs}" rb_enter_close_surface(ax) class TestDeveloperToolsText: """Text living on the Developer Tools surface (depth 1).""" @pytest.mark.rb(depth=1, jump_kind="value", expect="3 group headers + 10 tool names") def test_devtools_rail_text(self, ax): app_ready(ax) assert rb_enter_menu(ax, ["massCode", "Developer Tools…"], settle=1.6), \ "menu massCode ▸ Developer Tools… did not fire" assert "Developer Tools" in headings(ax), f"headings={headings(ax)}" ls = set(labels(ax)) expected = ["Text Tools", "Cryptography / Security", "Encoders / Decoders", "Case Converter", "Slug Generator", "Sort Lines", "URL Parser", "Hash Generator", "HMAC Generator", "Password Generator", "UUID Generator", "URL Encoder / Decoder", "Base64 Encoder / Decoder"] missing = [e for e in expected if e not in ls] assert kit.rb_value(missing, []), \ f"Developer Tools rail text missing: {missing}; labels={sorted(ls)[:40]}" screenshot_assert( "text_devtools_rail", "massCode Developer Tools page, title 'Developer Tools'. The left rail is split " "into three labelled groups: 'Text Tools' (Case Converter, Slug Generator, " "Sort Lines, URL Parser), 'Cryptography / Security' (Hash Generator, " "HMAC Generator, Password Generator, UUID Generator) and 'Encoders / Decoders' " "(URL Encoder / Decoder, Base64 Encoder / Decoder).") rb_enter_close_surface(ax) class TestSnippetEditorText: """Default text of a freshly created snippet (depth 1 — File ▸ New Snippet).""" @pytest.mark.rb(depth=1, jump_kind="value", expect="new snippet reads 'Untitled snippet', language 'Plain Text', " "cursor status 'Line 1, Column 1'") def test_new_snippet_default_text(self, ax): app_ready(ax) go_home(ax) assert rb_enter_new_snippet(ax), "menu File ▸ New Snippet did not fire" name = field(ax, "Type snippet name") assert name is not None, "no text_field titled 'Type snippet name'" assert kit.rb_value((name.value or "").strip(), "Untitled snippet"), \ f"snippet name box = {name.value!r} (expected 'Untitled snippet')" tag = field(ax, "Add Tag") assert tag is not None, "no text_field titled 'Add Tag'" assert (tag.name or "") == "Add Tag", f"tag placeholder={tag.name!r}" pv = popup_values(ax) assert "Plain Text" in pv, f"language popup value not 'Plain Text'; popups={pv}" ls = labels(ax) cursor = first_label_matching(ls, r"^Line \d+, Column \d+$") assert kit.rb_value(cursor, "Line 1, Column 1"), \ f"cursor status = {cursor!r}; labels={sorted(set(ls))[:40]}" screenshot_assert( "text_snippet_editor", "massCode snippet editor for a freshly created snippet: the name box at the top " "of the right-hand pane reads 'Untitled snippet', below it an empty tag input " "placeholdered 'Add Tag', then an empty code editor area. The bottom bar shows " "the language dropdown reading 'Plain Text' and the cursor status text " "'Line 1, Column 1'. The middle list shows an 'Untitled snippet' row.") class TestAboutDialogText: """Text inside the modal About sheet (depth 1 — massCode ▸ About massCode).""" @pytest.mark.rb(depth=1, jump_kind="value", expect="About sheet shows the title 'massCode', a detail block containing " "'Version' and an OK button") def test_about_dialog_text(self, ax): app_ready(ax) assert rb_enter_menu(ax, ["massCode", "About massCode"], settle=1.8), \ "menu massCode ▸ About massCode did not fire" sh = sheets(ax) assert len(sh) == 1, f"expected exactly 1 sheet, found {len(sh)}" sheet_id = sh[0].id sheet_labels = [(l.value or "") for l in ax.find(role="label", root_id=sheet_id, max_results=20, max_depth=8) if l.value] assert any(t.strip() == "massCode" for t in sheet_labels), \ f"About sheet has no 'massCode' title label; labels={sheet_labels}" ok = named_button(ax, "OK", root_id=sheet_id) assert ok is not None, \ f"About sheet has no OK button; buttons={button_names(ax, root_id=sheet_id)}" # NEVER assert the version digits — only that a Version line is rendered. has_version = any("Version" in t for t in sheet_labels) assert kit.rb_value(has_version, True), \ f"About detail text has no 'Version' line; labels={sheet_labels}" ax.action(ok.id, "AXPress") time.sleep(1.0) assert len(sheets(ax)) == 0, "About sheet did not close after pressing OK" class TestTextTransitions: """Text that CHANGES as a result of an interaction (depth 1 — snippet editor).""" @pytest.mark.rb(depth=1, jump_kind="transition", expect="snippet-list row text follows the rename to 'RB Text Marker'") def test_snippet_rename_updates_list_row(self, ax): app_ready(ax) go_home(ax) assert rb_enter_new_snippet(ax), "menu File ▸ New Snippet did not fire" name = field(ax, "Type snippet name") assert name is not None, "no text_field titled 'Type snippet name'" before_labels = labels(ax) assert "Untitled snippet" in before_labels, \ f"new snippet row not listed; labels={sorted(set(before_labels))[:40]}" assert ax.set_value(name.id, "RB Text Marker"), "set_value on the name box failed" time.sleep(1.2) after_labels = labels(ax) assert "RB Text Marker" in after_labels, \ f"renamed row text missing; labels={sorted(set(after_labels))[:40]}" # State-relative: other snippets may ALSO be called 'Untitled snippet', so flip on # the COUNT of that row text (membership alone is not decisive with leftover state). before_n = before_labels.count("Untitled snippet") after_n = after_labels.count("Untitled snippet") assert kit.rb_flip(before_n, after_n, expect="list row text follows the renamed snippet"), \ f"'Untitled snippet' row count unchanged ({before_n} -> {after_n})" assert after_n == before_n - 1, \ f"expected exactly one 'Untitled snippet' row to be renamed ({before_n} -> {after_n})" @pytest.mark.rb(depth=1, jump_kind="transition", expect="'RB Search Marker' row hidden by a non-matching query and " "restored by a matching one") def test_search_filters_snippet_list_text(self, ax): app_ready(ax) go_home(ax) assert rb_enter_new_snippet(ax), "menu File ▸ New Snippet did not fire" name = field(ax, "Type snippet name") assert name is not None, "no text_field titled 'Type snippet name'" assert ax.set_value(name.id, "RB Search Marker"), "set_value on the name box failed" time.sleep(1.0) s = field(ax, "Search...") assert s is not None, "no text_field titled 'Search...'" assert ax.set_value(s.id, "zzzznomatch"), "set_value on the search box failed" time.sleep(1.5) filtered = labels(ax) row_when_filtered = "RB Search Marker" in filtered gone = (not row_when_filtered) and ("No Snippet Selected" in filtered) s2 = field(ax, "Search...") assert s2 is not None, "search box disappeared while filtering" assert ax.set_value(s2.id, "RB Search Marker"), "set_value on the search box failed" time.sleep(1.5) restored = labels(ax) row_when_matching = "RB Search Marker" in restored back = row_when_matching assert kit.rb_flip(row_when_filtered, row_when_matching, expect="search hides then re-shows the snippet row"), \ (f"row visibility did not flip: filtered={row_when_filtered} " f"matching={row_when_matching}") assert gone, ("query 'zzzznomatch' did not hide the row / show 'No Snippet Selected'; " f"labels={sorted(set(filtered))[:40]}") assert back, ("query 'RB Search Marker' did not restore the row; " f"labels={sorted(set(restored))[:40]}") s3 = field(ax, "Search...") if s3 is not None: ax.set_value(s3.id, "") time.sleep(0.4)