VoyagerXHF's picture
Upload folder using huggingface_hub (part 5)
3fbbdd9 verified
Raw History Blame Contribute Delete
24.6 kB
"""AX state tests for massCode — menu check marks, <select> values, custom checkboxes, focus."""
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 popups(ax):
return ax.find(role="popup", max_results=12, max_depth=26)
def named_button(ax, name):
for b in ax.find(role="button", max_results=40, max_depth=26):
if (b.name or "").strip() == name.strip():
return b
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 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 mark_of(ax, path):
"""'✓' when a checkbox/radio menu item is checked, else None."""
el = menu_el(ax, path)
if el is None:
return None
return ax.get(el.id, ["AXMenuItemMarkChar"]).get("AXMenuItemMarkChar")
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 one of
Storage / Editor / Markdown / Appearance / Language 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 popup_options(ax, popup_value):
"""AXPress the popup with this value; return (opened_ok, [all option labels])."""
tgt = None
for p in popups(ax):
if (p.value or "") == popup_value:
tgt = p
break
if tgt is None:
return False, []
ax.action(tgt.id, "AXPress")
time.sleep(0.9)
best = []
for p in popups(ax):
opts = [o.value for o in ax.find(role="menu_item", root_id=p.id,
max_results=300, max_depth=4)]
if len(opts) > len(best):
best = opts
return True, best
def select_option(ax, popup_value, option_label, settle=1.0):
"""AXPress a <select> popup then AXPress one of the options it exposes."""
tgt = None
for p in popups(ax):
if (p.value or "") == popup_value:
tgt = p
break
if tgt is None:
return False
ax.action(tgt.id, "AXPress")
time.sleep(0.9)
for p in popups(ax):
for o in ax.find(role="menu_item", root_id=p.id, max_results=300, max_depth=4):
if (o.value or "") == option_label:
ok = ax.action(o.id, "AXPress")
time.sleep(settle)
return ok
esc()
return False
def popup_value_now(ax, candidates):
"""Current value of whichever popup currently holds one of `candidates`."""
for p in popups(ax):
if (p.value or "") in candidates:
return p.value
return None
def checkbox_children(ax, label_text):
"""massCode renders checkboxes as a div whose tick <svg> only exists when CHECKED:
the form-item group holding exactly this one label has 3 direct group children when
CHECKED and 2 when UNCHECKED. Returns that count (or None)."""
for g in ax.find(role="group", max_results=600, max_depth=26):
labs = ax.find(role="label", root_id=g.id, max_results=4, max_depth=3)
if len(labs) == 1 and (labs[0].value or "").strip() == label_text:
return len(ax.find(role="group", root_id=g.id, max_results=6, max_depth=1))
return None
def click_label(ax, label_text):
"""Toggle a custom checkbox by CG-clicking its visible label."""
for l in ax.find(role="label", max_results=300, max_depth=26):
if (l.value or "").strip() == label_text:
return ax.click_element_cg(l.id)
return False
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 additions ─────────────────────────────────────────────────────────
CHECK = "✓" # AXMenuItemMarkChar for a checked item
SORT_OPTS = ("Date Modified", "Date Created", "Name")
def _mk(mark):
"""Normalise AXMenuItemMarkChar: an UNCHECKED item reports None (some toolkits
report ''), a CHECKED item reports its mark character. Keeps the CHECKED/UNCHECKED
distinction while tolerating the empty-string spelling of 'no mark'."""
return mark if mark else None
def sort_marks(ax):
"""(Date Modified, Date Created, Name) mark chars — the radio group's state."""
return tuple(_mk(mark_of(ax, ["View", "Sort Snippets By", o])) for o in SORT_OPTS)
def is_enabled(ax, el):
return bool(ax.get(el.id, ["AXEnabled"]).get("AXEnabled"))
# ── menu CHECKED / radio state ──────────────────────────────────────────────
class TestMenuCheckState:
"""Native menu-item CHECKED state (AXMenuItemMarkChar). massCode persists these in
electron-store, so every test reads the mark BEFORE, flips it, and restores it."""
@pytest.mark.rb(depth=0, jump_kind="transition",
expect="View ▸ Compact Mode AXMenuItemMarkChar flips None <-> '✓' "
"and is restored to its entry value")
def test_compact_mode_check_state_flips_and_restores(self, ax):
app_ready(ax)
path = ["View", "Compact Mode"]
assert menu_el(ax, path) is not None, "View ▸ Compact Mode menu item missing"
before = _mk(mark_of(ax, path))
assert rb_enter_menu(ax, path), "could not press View ▸ Compact Mode"
after = _mk(mark_of(ax, path))
# restore BEFORE asserting — the setting persists across app relaunches
rb_enter_menu(ax, path)
restored = _mk(mark_of(ax, path))
assert kit.rb_flip(before, after,
expect="Compact Mode ✓ toggles"), \
f"Compact Mode mark did not change: {before!r} -> {after!r}"
assert {before, after} == {None, CHECK}, \
f"expected the mark to move between None and '✓', got {before!r}/{after!r}"
assert restored == before, \
f"Compact Mode not restored: {restored!r} != {before!r}"
@pytest.mark.rb(depth=0, jump_kind="transition",
expect="View ▸ Hide Subfolder Snippets AXMenuItemMarkChar flips "
"None <-> '✓' and is restored to its entry value")
def test_hide_subfolder_snippets_check_state_flips_and_restores(self, ax):
app_ready(ax)
path = ["View", "Hide Subfolder Snippets"]
assert menu_el(ax, path) is not None, "View ▸ Hide Subfolder Snippets missing"
before = _mk(mark_of(ax, path))
assert rb_enter_menu(ax, path), "could not press View ▸ Hide Subfolder Snippets"
after = _mk(mark_of(ax, path))
rb_enter_menu(ax, path)
restored = _mk(mark_of(ax, path))
assert kit.rb_flip(before, after,
expect="Hide Subfolder Snippets ✓ toggles"), \
f"Hide Subfolder Snippets mark did not change: {before!r} -> {after!r}"
assert {before, after} == {None, CHECK}, \
f"expected the mark to move between None and '✓', got {before!r}/{after!r}"
assert restored == before, \
f"Hide Subfolder Snippets not restored: {restored!r} != {before!r}"
@pytest.mark.rb(depth=1, jump_kind="transition",
expect="View ▸ Sort Snippets By submenu: exactly one of "
"Date Modified / Date Created / Name is ✓, and the ✓ MOVES "
"to whichever item is pressed (radio exclusivity)")
def test_sort_radio_exclusive_and_moves(self, ax):
app_ready(ax)
for opt in SORT_OPTS:
assert menu_el(ax, ["View", "Sort Snippets By", opt]) is not None, \
f"Sort Snippets By ▸ {opt} missing"
original = sort_marks(ax)
assert rb_enter_menu(ax, ["View", "Sort Snippets By", "Name"]), \
"could not press Sort Snippets By ▸ Name"
m1 = sort_marks(ax)
assert rb_enter_menu(ax, ["View", "Sort Snippets By", "Date Created"]), \
"could not press Sort Snippets By ▸ Date Created"
m2 = sort_marks(ax)
# restore the originally-checked option (this setting persists)
orig_idx = [i for i, m in enumerate(original) if m == CHECK]
if orig_idx:
rb_enter_menu(ax, ["View", "Sort Snippets By", SORT_OPTS[orig_idx[0]]])
restored = sort_marks(ax)
assert original.count(CHECK) == 1, \
f"exactly one sort option must be ✓ on entry, got {original!r}"
assert m1 == (None, None, CHECK), \
f"after pressing Name expected (None, None, '✓'), got {m1!r}"
assert m2 == (None, CHECK, None), \
f"after pressing Date Created expected (None, '✓', None), got {m2!r}"
assert kit.rb_flip(m1, m2,
expect="sort radio ✓ moves from Name to Date Created"), \
f"sort radio mark did not move: {m1!r} -> {m2!r}"
assert restored == original, \
f"sort radio not restored: {restored!r} != {original!r}"
# ── HTML <select> popup state ───────────────────────────────────────────────
class TestSelectPopupState:
"""<select> popups expose only the SELECTED option while collapsed and ALL options
once AXPressed — so the option list itself is a reachable surface."""
@pytest.mark.rb(depth=2, jump_kind="reach",
expect="both Wrap options (Word Wrap, Off) exposed when the select "
"expands")
def test_wrap_select_expands_to_all_options(self, ax):
app_ready(ax)
assert rb_enter_preferences_pane(ax, "Editor"), \
"could not reach Preferences ▸ Editor"
cur = popup_value_now(ax, {"Word Wrap", "Off"})
assert cur in ("Word Wrap", "Off"), \
f"Wrap select not found; popup values = {[p.value for p in popups(ax)]}"
target = "Off" if cur == "Word Wrap" else "Word Wrap"
before = kit.rb_showing(ax, max_depth=20)
opened, opts = popup_options(ax, cur)
after = kit.rb_showing(ax, max_depth=20)
esc()
assert opened, "the Wrap select did not respond to AXPress"
assert kit.rb_reach(before, after, target=target), \
f"expanding the Wrap select did not expose {target!r} (options seen: {opts!r})"
assert set(opts) == {"Word Wrap", "Off"}, \
f"expected Wrap options {{'Word Wrap', 'Off'}}, got {sorted(set(opts))!r}"
rb_enter_close_surface(ax)
@pytest.mark.rb(depth=1, jump_kind="transition",
expect="Preferences ▸ Editor Wrap select value flips Word Wrap <-> Off "
"and is restored")
def test_wrap_select_value_changes_and_restores(self, ax):
app_ready(ax)
assert rb_enter_preferences_pane(ax, "Editor"), \
"could not reach Preferences ▸ Editor"
cur = popup_value_now(ax, {"Word Wrap", "Off"})
assert cur in ("Word Wrap", "Off"), \
f"Wrap select not found; popup values = {[p.value for p in popups(ax)]}"
other = "Off" if cur == "Word Wrap" else "Word Wrap"
changed = select_option(ax, cur, other)
now = popup_value_now(ax, {"Word Wrap", "Off"})
# restore first — a Preferences popup change is written to electron-store
if now == other:
select_option(ax, other, cur)
back = popup_value_now(ax, {"Word Wrap", "Off"})
assert changed, f"could not select the {other!r} option of the Wrap select"
assert kit.rb_flip(cur, now, expect="Wrap select value changes"), \
f"Wrap select value did not change: {cur!r} -> {now!r}"
assert now == other, f"expected Wrap == {other!r}, got {now!r}"
assert back == cur, f"Wrap not restored: {back!r} != {cur!r}"
rb_enter_close_surface(ax)
@pytest.mark.rb(depth=2, jump_kind="value",
expect="Trailing Comma options None / All / ES5")
def test_trailing_comma_select_options(self, ax):
app_ready(ax)
assert rb_enter_preferences_pane(ax, "Editor"), \
"could not reach Preferences ▸ Editor"
cur = popup_value_now(ax, {"None", "All", "ES5"})
assert cur in ("None", "All", "ES5"), \
f"Trailing Comma select not found; popups = {[p.value for p in popups(ax)]}"
opened, opts = popup_options(ax, cur)
esc()
assert opened, "the Trailing Comma select did not respond to AXPress"
assert kit.rb_value(sorted(opts), sorted(["None", "All", "ES5"])), \
f"expected Trailing Comma options ['All', 'ES5', 'None'], got {sorted(opts)!r}"
rb_enter_close_surface(ax)
@pytest.mark.rb(depth=2, jump_kind="value",
expect="8 hash algorithms MD5…SHA512")
def test_hash_algorithm_select_options(self, ax):
app_ready(ax)
assert rb_enter_devtool(ax, "Hash Generator"), \
"could not reach Developer Tools ▸ Hash Generator"
ps = popups(ax)
assert ps, "Hash Generator exposes no Algorithm select"
cur = ps[0].value
opened, opts = popup_options(ax, cur)
esc()
screenshot_assert(
"states_hash_algorithms",
"massCode Developer Tools page. The left rail lists Text Tools "
"(Case Converter, Slug Generator, Sort Lines, URL Parser), "
"Cryptography / Security (Hash Generator, HMAC Generator, Password "
"Generator, UUID Generator) and Encoders / Decoders, with Hash Generator "
"highlighted as the active row. The Hash Generator pane on the right shows "
"an Input String box, an Algorithm dropdown whose selected value is one of "
"the eight algorithms MD5 / RIPEMD160 / SHA1 / SHA224 / SHA256 / SHA3 / "
"SHA384 / SHA512 (MD5 by default), and a Result field below it.",
RESULTS_DIR)
assert opened, "the Algorithm select did not respond to AXPress"
expected = ["MD5", "RIPEMD160", "SHA1", "SHA224",
"SHA256", "SHA3", "SHA384", "SHA512"]
assert kit.rb_value(sorted(opts), sorted(expected)), \
f"expected the 8 hash algorithms {sorted(expected)!r}, got {sorted(opts)!r}"
rb_enter_close_surface(ax)
# ── custom (display:none input) checkbox state ──────────────────────────────
class TestCustomCheckboxState:
"""massCode's checkboxes hide the real <input>, so CHECKED is observed structurally:
the form-item group has 3 direct group children when ticked and 2 when not."""
@pytest.mark.rb(depth=1, jump_kind="transition",
expect="Password Generator 'Symbols' checkbox: tick node appears / "
"disappears (2 <-> 3 child groups) and is restored")
def test_password_symbols_checkbox_toggles(self, ax):
app_ready(ax)
assert rb_enter_devtool(ax, "Password Generator"), \
"could not reach Developer Tools ▸ Password Generator"
before = checkbox_children(ax, "Symbols")
assert before in (2, 3), \
f"Symbols checkbox not found / unexpected shape (children={before!r})"
clicked = click_label(ax, "Symbols")
time.sleep(1.2)
after = checkbox_children(ax, "Symbols")
screenshot_assert(
"states_password_options",
"massCode Developer Tools page with Password Generator selected (highlighted) "
"in the Cryptography / Security group of the left rail. The pane shows a "
"Length text field (default 10) with a 'Max: 2048' hint beside it, an Options "
"row of four custom checkboxes labelled Numbers, Symbols, Lowercase and "
"Uppercase (Numbers, Lowercase and Uppercase are ticked by default), a "
"Generate button and a Result field. The Symbols checkbox has just been "
"clicked, so its tick mark is inverted relative to the other three.",
RESULTS_DIR)
# restore
click_label(ax, "Symbols")
time.sleep(1.2)
restored = checkbox_children(ax, "Symbols")
assert clicked, "could not click the Symbols checkbox label"
assert kit.rb_flip(before, after,
expect="Symbols checkbox tick appears/disappears"), \
f"Symbols checkbox state did not change: {before!r} -> {after!r}"
assert {before, after} == {2, 3}, \
f"expected the child-group count to move between 2 and 3, got {before!r}/{after!r}"
assert restored == before, \
f"Symbols checkbox not restored: {restored!r} != {before!r}"
# ── focus + enabled state ───────────────────────────────────────────────────
class TestFocusAndEnabledState:
@pytest.mark.rb(depth=0, jump_kind="transition",
expect="File ▸ Find moves AXFocused onto the 'Search...' text field "
"(False -> True)")
def test_find_menu_focuses_search_field(self, ax):
app_ready(ax)
go_home(ax)
# park focus elsewhere first so the flip is genuine
press_labelled_group(ax, "Inbox")
time.sleep(0.6)
s = field(ax, "Search...")
assert s is not None, f"no 'Search...' text field on home; labels={labels(ax)[:20]}"
before = bool(ax.get(s.id, ["AXFocused"]).get("AXFocused"))
assert rb_enter_menu(ax, ["File", "Find"], settle=1.2), \
"could not press File ▸ Find"
s = field(ax, "Search...")
assert s is not None, "'Search...' text field vanished after File ▸ Find"
after = bool(ax.get(s.id, ["AXFocused"]).get("AXFocused"))
assert after is True, "File ▸ Find did not focus the 'Search...' field"
assert kit.rb_flip(before, after,
expect="search field becomes focused"), \
f"AXFocused did not change: {before!r} -> {after!r}"
@pytest.mark.rb(depth=1, jump_kind="none",
expect="every core control (snippet name / Add Tag / Search... fields, "
"language popup, File ▸ New Snippet, Editor ▸ Copy Snippet to "
"Clipboard, View ▸ Compact Mode) reports AXEnabled == True and "
"the search field's AXValue is settable")
def test_core_controls_report_enabled(self, ax):
app_ready(ax)
go_home(ax)
assert rb_enter_new_snippet(ax), "could not create a snippet via File ▸ New Snippet"
controls = {}
for placeholder in ("Type snippet name", "Add Tag", "Search..."):
el = field(ax, placeholder)
assert el is not None, \
f"text field {placeholder!r} not found; labels={labels(ax)[:20]}"
controls[f"text_field {placeholder!r}"] = el
ps = popups(ax)
assert ps, "no language <select> popup in the snippet editor column"
controls["language popup"] = ps[0]
for path in (["File", "New Snippet"],
["Editor", "Copy Snippet to Clipboard"],
["View", "Compact Mode"]):
el = menu_el(ax, path)
assert el is not None, f"menu item {' ▸ '.join(path)} not found"
controls["menu " + " ▸ ".join(path)] = el
disabled = [k for k, el in controls.items() if not is_enabled(ax, el)]
assert disabled == [], f"controls reporting AXEnabled != True: {disabled}"
search = field(ax, "Search...")
assert search is not None, "'Search...' text field disappeared"
assert ax.is_attribute_settable(search.id, "AXValue") is True, \
"'Search...' AXValue is not settable"