VoyagerXHF's picture
Upload folder using huggingface_hub (part 5)
3fbbdd9 verified
Raw History Blame Contribute Delete
23.5 kB
"""AX button behaviour 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 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 text_areas(ax):
return ax.find(role="text_area", max_results=8, max_depth=26)
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 snippet_header_buttons(ax):
"""The snippet-header tool buttons, left→right. For a Plain Text snippet there are
exactly 4: [screenshot, code-preview, add-description, new-fragment]."""
wa = webarea(ax)
if wa is None:
return []
name_field = field(ax, "Type snippet name")
if name_field is None:
return []
p = ax.get(name_field.id, ["AXPosition"]).get("AXPosition", "") or ""
try:
ny = float(p.split("y:")[1].split(" ")[0])
nx = float(p.split("x:")[1].split(" ")[0])
except Exception:
return []
out = [(x, y, b) for (x, y, b) in webarea_buttons(ax)
if abs(y - ny) < 40 and x > nx]
return [b for (_x, _y, b) in sorted(out, key=lambda t: t[0])]
def add_snippet_button(ax):
"""The '+' at the top of the snippet-list column: the button that sits on the same
row as the Search box and to its right."""
s = field(ax, "Search...")
if s is None:
return None
p = ax.get(s.id, ["AXPosition"]).get("AXPosition", "") or ""
try:
sy = float(p.split("y:")[1].split(" ")[0])
sx = float(p.split("x:")[1].split(" ")[0])
except Exception:
return None
cands = [(x, y, b) for (x, y, b) in webarea_buttons(ax)
if abs(y - sy) < 25 and x > sx]
cands.sort(key=lambda t: t[0])
return cands[0][2] if cands 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_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 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
# ─────────────────────────── extra navigation helpers ───────────────────────────
# Named rb_enter_* so the depth audit can see the surfaces each test crosses.
def rb_enter_sidebar_row(ax, row_name, settle=1.0):
"""NAVIGATION: select a sidebar collection (Inbox / Trash / All Snippets / …).
Located by the row's visible LABEL, never by index."""
ok = press_labelled_group(ax, row_name)
time.sleep(settle)
return ok
def rb_enter_preferences(ax):
"""NAVIGATION: open the Preferences/Settings surface from the app menu.
Tries the macOS 13+ 'Settings…' wording first, then the classic 'Preferences…'."""
for label in ("Settings…", "Preferences…", "Settings...", "Preferences..."):
if rb_enter_menu(ax, ["massCode", label], settle=1.6):
return True
return False
def press_named(ax, name, settle=0.8):
"""AXPress a button located by its accessible NAME (devtools buttons have names)."""
b = named_button(ax, name)
if b is None:
return False
ok = ax.action(b.id, "AXPress")
time.sleep(settle)
return ok
def button_names(ax):
return [(b.name or "") for b in ax.find(role="button", max_results=40, max_depth=26)]
def out_value(ax, index=1, timeout=2.0):
"""Poll the devtools output text_area until it is non-empty (reactive tools lag)."""
deadline = time.time() + timeout
val = None
while time.time() < deadline:
tas = text_areas(ax)
if len(tas) > index:
val = tas[index].value
if (val or "").strip():
return val
time.sleep(0.2)
return val
def set_case_input(ax, text):
tas = text_areas(ax)
assert len(tas) >= 2, f"expected an input+output text_area pair, found {len(tas)}"
ax.set_value(tas[0].id, text)
time.sleep(0.4)
return tas
# ══════════════════════════════════ REACH ══════════════════════════════════
class TestSnippetCreationButtons:
"""The '+' button in the snippet-list column must MATERIALISE a snippet editor."""
@pytest.mark.rb(depth=1, jump_kind="reach",
expect="snippet name box + language dropdown + Line 1, Column 1 appear")
def test_add_snippet_button_creates_snippet(self, ax):
app_ready(ax)
go_home(ax)
# Trash is empty -> the editor column collapses to 'No Snippet Selected',
# giving a deterministic SOURCE surface for the reach proof.
assert rb_enter_sidebar_row(ax, "Trash"), "sidebar 'Trash' row is not pressable"
before = kit.rb_showing(ax)
rb_enter_sidebar_row(ax, "Inbox")
b = add_snippet_button(ax)
assert b is not None, "no '+' add-snippet button beside the Search box"
assert "AXPress" in (b.actions or []), "add-snippet button exposes no AXPress action"
assert ax.action(b.id, "AXPress"), "AXPress on the add-snippet button failed"
time.sleep(1.6)
after = kit.rb_showing(ax)
screenshot_assert(
"buttons_new_snippet",
"massCode home shell after pressing the '+' button at the top of the middle "
"snippet-list column (right of the 'Search...' box): the right editor pane no "
"longer says 'No Snippet Selected' but shows a new snippet — a 'Type snippet "
"name' box filled with 'Untitled snippet', an 'Add Tag' row, an empty code "
"editor, a 'Plain Text' language dropdown and the 'Line 1, Column 1' status. "
"A new 'Untitled snippet' row is listed in the snippet-list column.",
)
assert kit.rb_reach(before, after,
target="Type snippet name", source="No Snippet Selected"), (
"'+' did not open a snippet editor (name box never appeared / "
"'No Snippet Selected' never went away)")
class TestSnippetHeaderToolButtons:
"""The 4 icon-only tool buttons to the right of the snippet name box."""
@pytest.mark.rb(depth=2, jump_kind="reach",
expect="screenshot palette with Background / Dark Mode and PNG / SVG buttons")
def test_screenshot_preview_button_opens_palette(self, ax):
app_ready(ax)
go_home(ax)
assert rb_enter_new_snippet(ax), "File ▸ New Snippet did not fire"
hb = snippet_header_buttons(ax)
assert len(hb) >= 4, f"expected >=4 snippet-header tool buttons, found {len(hb)}"
before = kit.rb_showing(ax)
assert ax.action(hb[0].id, "AXPress"), "AXPress on the screenshot button failed"
time.sleep(1.5)
after = kit.rb_showing(ax)
screenshot_assert(
"buttons_screenshot_palette",
"massCode snippet screenshot palette: the editor pane's tag row, 'Plain Text' "
"language dropdown and 'Line N, Column M' status are replaced by a screenshot "
"export panel showing a 'Background' colour control, a 'Dark Mode' switch and "
"two export buttons labelled 'PNG' and 'SVG' (not pressed — they write files). "
"The left sidebar and the snippet list are still visible.",
)
assert kit.rb_reach(before, after, target="Dark Mode", source="Add Tag"), (
"the screenshot tool button did not swap the editor footer for the "
"screenshot palette")
names = button_names(ax)
assert any("PNG" in n for n in names), f"no PNG export button in {names}"
assert any("SVG" in n for n in names), f"no SVG export button in {names}"
# Restore the editor (never press PNG/SVG — they open a save panel).
hb2 = snippet_header_buttons(ax)
ax.action((hb2[0] if hb2 else hb[0]).id, "AXPress")
time.sleep(0.8)
@pytest.mark.rb(depth=2, jump_kind="reach",
expect="'Add description' text area appears")
def test_add_description_button_reveals_textarea(self, ax):
app_ready(ax)
go_home(ax)
assert rb_enter_new_snippet(ax), "File ▸ New Snippet did not fire"
hb = snippet_header_buttons(ax)
assert len(hb) >= 3, f"expected >=3 snippet-header tool buttons, found {len(hb)}"
before = kit.rb_showing(ax)
assert ax.action(hb[2].id, "AXPress"), "AXPress on the add-description button failed"
time.sleep(1.4)
after = kit.rb_showing(ax)
assert kit.rb_reach(before, after, target="Add description"), (
"the add-description button did not reveal the description area")
assert len(text_areas(ax)) >= 2, (
"description area did not add a second text_area next to the code editor")
@pytest.mark.rb(depth=2, jump_kind="reach",
expect="Fragment 1 / Fragment 2 tab bar appears")
def test_new_fragment_button_creates_fragment_tabs(self, ax):
app_ready(ax)
go_home(ax)
assert rb_enter_new_snippet(ax), "File ▸ New Snippet did not fire"
hb = snippet_header_buttons(ax)
assert len(hb) >= 4, f"expected >=4 snippet-header tool buttons, found {len(hb)}"
before = kit.rb_showing(ax)
assert ax.action(hb[3].id, "AXPress"), "AXPress on the new-fragment button failed"
time.sleep(1.5)
after = kit.rb_showing(ax)
assert kit.rb_reach(before, after, target="Fragment 2"), (
"the new-fragment button did not add a second fragment tab")
ls = labels(ax)
assert "Fragment 1" in ls, f"no 'Fragment 1' tab beside 'Fragment 2': {ls[:40]}"
class TestSurfaceCloseButton:
"""The single webarea button on a full-window surface must return to the home shell."""
@pytest.mark.rb(depth=2, jump_kind="reach", expect="home shell restored")
def test_preferences_close_button_returns_home(self, ax):
app_ready(ax)
go_home(ax)
assert rb_enter_preferences(ax), "could not open the Preferences/Settings surface"
before = kit.rb_showing(ax)
assert any("Preferences" in (l or "") for l in labels(ax)), (
"Preferences surface did not render")
assert rb_enter_close_surface(ax), "no close button inside the Preferences webarea"
after = kit.rb_showing(ax)
assert kit.rb_reach(before, after, target="All Snippets", source="Preferences"), (
"the Preferences close button did not bring back the home shell")
# ══════════════════════════════════ VALUE ══════════════════════════════════
class TestDevtoolsCaseConverterButtons:
"""Developer Tools ▸ Case Converter — each named button must produce its exact string."""
@pytest.mark.rb(depth=1, jump_kind="value", expect="helloWorldExample")
def test_case_converter_camel_button(self, ax):
app_ready(ax)
assert rb_enter_devtool(ax, "Case Converter"), "could not open Case Converter"
tas = text_areas(ax)
assert len(tas) >= 2, f"Case Converter needs 2 text areas, found {len(tas)}"
assert ax.set_value(tas[0].id, "hello world example"), "could not fill Input String"
time.sleep(0.8)
btn = named_button(ax, "camelCase")
assert btn is not None, f"no 'camelCase' button; saw {button_names(ax)}"
assert "AXPress" in (btn.actions or []), "camelCase button exposes no AXPress action"
assert ax.action(btn.id, "AXPress"), "AXPress on camelCase failed"
time.sleep(0.8)
out = out_value(ax, 1)
screenshot_assert(
"buttons_case_converter",
"massCode Developer Tools page, Case Converter pane: left rail lists Text Tools "
"(Case Converter, Slug Generator, Sort Lines, URL Parser), Cryptography / "
"Security and Encoders / Decoders. The pane shows an 'Input String' box holding "
"'hello world example', a row of case buttons (lower case, UPPER CASE, camelCase, "
"PascalCase, snake_case, kebab-case, Start Case) plus Clear/Copy, and an 'Output "
"String' box now reading 'helloWorldExample' after camelCase was pressed.",
)
assert kit.rb_value(out, "helloWorldExample"), f"camelCase produced {out!r}"
@pytest.mark.rb(depth=1, jump_kind="value", expect="kebab/snake/Pascal conversions")
def test_case_converter_kebab_snake_pascal_buttons(self, ax):
app_ready(ax)
assert rb_enter_devtool(ax, "Case Converter"), "could not open Case Converter"
expected = [("kebab-case", "hello-world-example"),
("snake_case", "hello_world_example"),
("PascalCase", "HelloWorldExample")]
for label, want in expected:
set_case_input(ax, "hello world example")
btn = named_button(ax, label)
assert btn is not None, f"no {label!r} button; saw {button_names(ax)}"
assert ax.action(btn.id, "AXPress"), f"AXPress on {label} failed"
time.sleep(0.7)
got = out_value(ax, 1)
assert kit.rb_value(got, want), f"{label} produced {got!r}, expected {want!r}"
class TestDevtoolsSortAndGenerateButtons:
"""Developer Tools buttons whose consequence is a computed value."""
@pytest.mark.rb(depth=1, jump_kind="value", expect="sorted then reversed lines")
def test_sort_lines_buttons(self, ax):
app_ready(ax)
assert rb_enter_devtool(ax, "Sort Lines"), "could not open Sort Lines"
tas = text_areas(ax)
assert len(tas) >= 2, f"Sort Lines needs 2 text areas, found {len(tas)}"
assert ax.set_value(tas[0].id, "banana\napple\ncherry"), "could not fill the input"
time.sleep(0.8)
assert press_named(ax, "Sort", settle=0.9), (
f"no pressable 'Sort' button; saw {button_names(ax)}")
sorted_out = out_value(ax, 1)
assert kit.rb_value(sorted_out, "apple\nbanana\ncherry"), (
f"Sort produced {sorted_out!r}")
assert press_named(ax, "Revers", settle=0.9), (
f"no pressable 'Revers' button; saw {button_names(ax)}")
reversed_out = out_value(ax, 1)
assert kit.rb_value(reversed_out, "cherry\napple\nbanana"), (
f"Revers produced {reversed_out!r}")
@pytest.mark.rb(depth=1, jump_kind="value", expect="24-character generated password")
def test_password_generate_button_honours_length(self, ax):
app_ready(ax)
assert rb_enter_devtool(ax, "Password Generator"), (
"could not open Password Generator")
fields = ax.find(role="text_field", max_results=10, max_depth=26)
assert len(fields) >= 2, (
f"Password Generator needs a Length + Result field, found {len(fields)}")
assert ax.set_value(fields[0].id, "24"), "could not set the Length field"
time.sleep(0.6)
assert press_named(ax, "Generate", settle=1.0), (
f"no pressable 'Generate' button; saw {button_names(ax)}")
fields = ax.find(role="text_field", max_results=10, max_depth=26)
assert len(fields) >= 2, "Result field vanished after Generate"
result = (fields[1].value or "")
assert not re.search(r"\s", result), f"password contains whitespace: {result!r}"
assert kit.rb_value(len(result), 24), (
f"Generate honoured neither Length=24 nor produced a password: {result!r}")
# ═══════════════════════════════ TRANSITION ═══════════════════════════════
class TestButtonToggles:
"""Buttons whose consequence is a reversible state flip."""
@pytest.mark.rb(depth=1, jump_kind="transition",
expect="Snippets Showcase preview pane appears/disappears")
def test_code_preview_button_toggles_preview(self, ax):
app_ready(ax)
go_home(ax)
assert rb_enter_new_snippet(ax), "File ▸ New Snippet did not fire"
hb = snippet_header_buttons(ax)
assert len(hb) >= 2, f"expected >=2 snippet-header tool buttons, found {len(hb)}"
before = "Snippets Showcase" in labels(ax)
assert ax.action(hb[1].id, "AXPress"), "AXPress on the code-preview button failed"
time.sleep(1.5)
after = "Snippets Showcase" in labels(ax)
assert kit.rb_flip(before, after, expect="code-preview pane toggles"), (
f"code-preview button did not toggle the preview pane (stayed {before})")
hb2 = snippet_header_buttons(ax)
toggle_back = hb2[1] if len(hb2) >= 2 else hb[1]
assert ax.action(toggle_back.id, "AXPress"), "second AXPress on code-preview failed"
time.sleep(1.5)
restored = "Snippets Showcase" in labels(ax)
assert kit.rb_flip(after, restored, expect="code-preview pane toggles back"), (
"code-preview button is not a toggle — the second press changed nothing")
assert restored == before, (
f"code-preview did not return to its original state ({before} -> {restored})")
@pytest.mark.rb(depth=1, jump_kind="transition", expect="input and result cleared")
def test_devtools_clear_button_empties_fields(self, ax):
app_ready(ax)
assert rb_enter_devtool(ax, "Base64 Encoder / Decoder"), (
"could not open Base64 Encoder / Decoder")
tas = text_areas(ax)
assert len(tas) >= 2, f"Base64 tool needs 2 text areas, found {len(tas)}"
assert ax.set_value(tas[0].id, "Hello massCode"), "could not fill the input"
time.sleep(1.0)
encoded = out_value(ax, 1)
tas = text_areas(ax)
before = ((tas[0].value or ""), (encoded or ""))
assert before[0].strip(), "the input text area stayed empty after set_value"
assert before[1].strip(), "the Base64 result never computed — nothing to clear"
assert press_named(ax, "Clear", settle=0.8), (
f"no pressable 'Clear' button; saw {button_names(ax)}")
tas = text_areas(ax)
assert len(tas) >= 2, "text areas vanished after Clear"
after = ((tas[0].value or ""), (tas[1].value or ""))
assert kit.rb_flip(before, after, expect="Clear empties input and result"), (
f"Clear changed nothing: {before!r}")
assert not after[0].strip(), f"input not cleared: {after[0]!r}"
assert not after[1].strip(), f"result not cleared: {after[1]!r}"