VoyagerXHF's picture
Upload folder using huggingface_hub (part 7)
e5a3ec0 verified
Raw History Blame Contribute Delete
16.7 kB
"""Shared AT-SPI primitives for RecreationBench pytest tests.
Tier-1 testgen ships ONE of these (uploaded next to the tests) instead of a
bespoke ~500-line ``atspi_helpers.py`` per app. Every generic primitive the
per-app helpers reinvented lives here — tree search, state, actions, real input
(xdotool), waits, and the VLM ``screenshot_assert``. The only app-specific bit,
"which frame is my app", is parameterized: ``get_app()`` resolves the target by
the ``RB_APP_NAME`` the runner already detected, so the SAME module works for
every app.
Tests import this and use pytest-check for soft assertions; result collection is
handled by ``conftest.py`` (which writes the legacy ``<module>_results.json`` so
the frozen-manifest scorer is unchanged). App-specific *workflows* (open a file,
expand a tree) stay in the test file or a local fixture — only the primitives are
shared.
"""
from __future__ import annotations
import json
import os
import subprocess
import time
import gi
gi.require_version("Atspi", "2.0")
from gi.repository import Atspi # noqa: E402
# Bound EVERY AT-SPI method call. A synchronous action (do_action) on an item that opens
# a MODAL runs the app's handler on its single main thread; if that handler enters a
# nested event loop (GTK gtk_dialog_run, Qt QDialog::exec, wx modal), it does not return
# until the dialog closes, so the D-Bus reply never comes and the call HANGS the whole
# pytest module. libatspi has a global call timeout (default ~800ms) but it is not
# reliably applied to actions that enter a nested loop; set it explicitly so a blocked
# call raises fast (and the test is dropped) instead of wedging the module. Reads are
# well under this; only nested-loop blocks hit it. (call_timeout_ms, app_startup_ms)
try:
Atspi.set_timeout(1500, 15000)
except Exception: # older libatspi without set_timeout
pass
# Re-export the kit's true-jump helpers so a test file has ONE import surface:
# ``from rb_atspi import rb_showing, rb_reach``. (Depth is measured via the ``rb``
# pytest fixture in conftest.py; app attach is the ``app`` fixture — both by RB_APP_NAME.)
try: # noqa: E402
from rb_testgen_kit import rb_reach, rb_showing # noqa: F401
except Exception: # pragma: no cover - kit absent; primitives below still work
pass
# --------------------------------------------------------------------------- #
# App / frame resolution
# --------------------------------------------------------------------------- #
def _desktop():
return Atspi.get_desktop(0)
def get_app(name: str | None = None, timeout: float = 25.0):
"""Return the AT-SPI application Accessible for the app under test.
``name`` defaults to the ``RB_APP_NAME`` the runner detected (a process-tree
match). Falls back to the single non-shell app on the bus if the name does
not match, so tests are robust to a11y-name drift.
"""
name = name or os.environ.get("RB_APP_NAME", "")
deadline = time.time() + timeout
ignore = {"", "gnome-shell", "at-spi2-registryd", "mutter-x11-frames"}
last_apps: list = []
while time.time() < deadline:
desktop = _desktop()
apps = []
for i in range(desktop.get_child_count()):
app = desktop.get_child_at_index(i)
if app is None:
continue
an = app.get_name() or ""
if an in ignore:
continue
apps.append(app)
if name and (an == name or name in an or an in name):
return app
last_apps = apps
time.sleep(0.4)
# name never matched: if exactly one real app is on the bus, use it.
if len(last_apps) == 1:
return last_apps[0]
for app in last_apps:
if (app.get_name() or "").strip():
return app
return None
def get_main_frame(app=None):
"""Return the app's top-level frame (or the app node itself)."""
if app is None:
app = get_app()
if app is None:
return None
for i in range(app.get_child_count()):
c = app.get_child_at_index(i)
if c is not None and (c.get_role_name() or "") in ("frame", "window"):
return c
return app
# --------------------------------------------------------------------------- #
# Tree traversal / finding
# --------------------------------------------------------------------------- #
def walk(node, cb, depth: int = 0, maxdepth: int = 60):
if node is None or depth > maxdepth:
return
try:
cb(node, depth)
except Exception:
pass
try:
n = node.get_child_count()
except Exception:
return
for i in range(n):
try:
c = node.get_child_at_index(i)
except Exception:
continue
walk(c, cb, depth + 1, maxdepth)
def find_all(
root, role: str | None = None, name: str | None = None, name_sub: str | None = None
):
out: list = []
def cb(n, _d):
try:
if role is not None and (n.get_role_name() or "") != role:
return
nm = n.get_name() or ""
if name is not None and nm != name:
return
if name_sub is not None and name_sub not in nm:
return
out.append(n)
except Exception:
pass
walk(root, cb)
return out
def find_first(
root, role: str | None = None, name: str | None = None, name_sub: str | None = None
):
res = find_all(root, role=role, name=name, name_sub=name_sub)
return res[0] if res else None
def cell_names(root):
return [(c.get_name() or "") for c in find_all(root, role="table cell")]
def roles_present(root):
seen: set[str] = set()
walk(root, lambda n, _d: seen.add(n.get_role_name() or ""))
return seen
def widget_count(root):
n = [0]
walk(root, lambda _n, _d: n.__setitem__(0, n[0] + 1))
return n[0]
# --------------------------------------------------------------------------- #
# State
# --------------------------------------------------------------------------- #
def _state(n, st) -> bool:
try:
return n.get_state_set().contains(st)
except Exception:
return False
def is_checked(n) -> bool:
return _state(n, Atspi.StateType.CHECKED)
def is_showing(n) -> bool:
return _state(n, Atspi.StateType.SHOWING)
def is_enabled(n) -> bool:
return _state(n, Atspi.StateType.ENABLED)
def is_visible(n) -> bool:
return _state(n, Atspi.StateType.VISIBLE)
def is_focused(n) -> bool:
return _state(n, Atspi.StateType.FOCUSED)
def get_text(n) -> str:
try:
return Atspi.Text.get_text(n, 0, Atspi.Text.get_character_count(n))
except Exception:
try:
return n.get_name() or ""
except Exception:
return ""
# --------------------------------------------------------------------------- #
# Actions
# --------------------------------------------------------------------------- #
def _action_iface(n):
try:
return n.get_action_iface()
except Exception:
return None
def action_names(n) -> list[str]:
ai = _action_iface(n)
if ai is None:
return []
try:
return [ai.get_action_name(i) for i in range(ai.get_n_actions())]
except Exception:
return []
def do_action(n, want: str) -> bool:
ai = _action_iface(n)
if ai is None:
return False
try:
for i in range(ai.get_n_actions()):
if (ai.get_action_name(i) or "").lower() == want.lower():
ai.do_action(i)
return True
except Exception:
return False
return False
def do_action_safe(n, want: str) -> bool:
"""Fire an AT-SPI action, tolerating a modal-opener. do_action on an item that opens
a modal blocks in the app's nested event loop; Atspi.set_timeout (module init) now
bounds that to ~1.5s, after which the call raises and we swallow it. PREFER
open_modal()/click_node() (async xdotool) for anything that opens a dialog/menu —
this is only the fallback. Returns True if the action was issued."""
ai = _action_iface(n)
if ai is None:
return False
idx = None
try:
for i in range(ai.get_n_actions()):
if (ai.get_action_name(i) or "").lower() == want.lower():
idx = i
break
except Exception:
return False
if idx is None:
return False
try:
ai.do_action(idx)
except Exception:
pass
return True
def press(n) -> bool:
return do_action(n, "Press") or do_action(n, "click")
def toggle(n) -> bool:
return do_action(n, "Toggle") or press(n)
def show_menu(n) -> bool:
"""Open a menu WITHOUT blocking. A menu-open can enter a grab/nested loop, so drive
it with a synthetic mouse click (xdotool, async — returns immediately) rather than a
synchronous do_action. Falls back to the (now timeout-bounded) do_action_safe."""
if click_node(n) is not None:
return True
return do_action_safe(n, "ShowMenu") or do_action_safe(n, "click")
def open_modal(n) -> bool:
"""Trigger something that may spawn a MODAL dialog (File>Open, a menu item that
opens a dialog) WITHOUT hanging. Uses a synthetic xdotool click (async) so the app
can enter its modal nested loop while the test proceeds to read/dismiss the new
window. NEVER use do_action for a modal-opener: do_action runs the handler
synchronously and blocks in the nested loop until the modal closes (see the
Atspi.set_timeout note at module top). After open_modal(), read the dialog via
AT-SPI (bounded reads) and dismiss with press_escape()/key()."""
return click_node(n) is not None
# --------------------------------------------------------------------------- #
# Real input via xdotool (needed to SELECT rows / reach webviews)
# --------------------------------------------------------------------------- #
def xdo(*args) -> bool:
try:
subprocess.run(
["xdotool", *[str(a) for a in args]],
timeout=8,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
return True
except Exception:
return False
def center(n):
try:
ext = n.get_extents(Atspi.CoordType.SCREEN)
if ext.width <= 0 or ext.height <= 0:
return None
return (ext.x + ext.width // 2, ext.y + ext.height // 2)
except Exception:
return None
def click_node(n, button: int = 1):
"""Real mouse click at the node's on-screen center (selects rows, focuses
webviews — synthetic AT-SPI focus often won't)."""
c = center(n)
if c is None:
return None
xdo("mousemove", c[0], c[1], "click", button)
return c
def key(*keys) -> bool:
return xdo("key", *keys)
def press_escape() -> None:
key("Escape")
def type_text(text: str, delay: int = 20) -> bool:
return xdo("type", "--delay", str(delay), text)
def close_all_dialogs(rounds: int = 3) -> None:
for _ in range(rounds):
press_escape()
time.sleep(0.15)
def focus_app_window(app=None, settle: float = 0.4) -> bool:
"""Raise + keyboard-focus the app's top-level X11 window so xdotool clicks/typing
reliably land in it. A freshly-relaunched window is frequently NOT window-manager
focused yet — synthetic input then goes nowhere or to the wrong window, which is the
cold-baseline flakiness (the warm run_live instance was focused long ago, so it hid
this). Called once by the ``app`` fixture when the app is acquired, so a cold
run_baseline behaves like the warm run_live. Best-effort — never raises, never fails a
test; activating the already-mapped main window before any modal is opened is benign.
"""
pid = None
try:
if app is None:
app = get_app()
if app is not None:
pid = app.get_process_id()
except Exception:
pid = None
def _search(*args) -> str | None:
try:
r = subprocess.run(
["xdotool", "search", "--onlyvisible", *args],
capture_output=True,
text=True,
timeout=5,
)
wids = [w for w in r.stdout.split() if w.strip()]
return wids[-1] if wids else None
except Exception:
return None
wid = _search("--pid", str(pid)) if pid else None
if (
wid is None
): # pid-owned window not found (e.g. window owned by a child); fall back to title
name = os.environ.get("RB_APP_NAME", "")
wid = _search("--name", name) if name else None
if wid is None:
return False
try:
subprocess.run(
["xdotool", "windowactivate", "--sync", wid, "windowfocus", wid],
timeout=6,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
time.sleep(settle)
return True
except Exception:
return False
# --------------------------------------------------------------------------- #
# Waits (replaces time.sleep spam — poll for the observation instead)
# --------------------------------------------------------------------------- #
def wait_for(predicate, timeout: float = 6.0, interval: float = 0.25) -> bool:
deadline = time.time() + timeout
while time.time() < deadline:
try:
if predicate():
return True
except Exception:
pass
time.sleep(interval)
return False
def wait_node(root_fn, timeout: float = 6.0, **find_kw):
"""Poll until a node matching find_kw appears; return it or None."""
out = [None]
def _p():
root = root_fn() if callable(root_fn) else root_fn
n = find_first(root, **find_kw)
out[0] = n
return n is not None
wait_for(_p, timeout=timeout)
return out[0]
# --------------------------------------------------------------------------- #
# VLM screenshot assertion (opaque/visual cores: WebKit/QtWebEngine/canvas)
# --------------------------------------------------------------------------- #
def _results_dir() -> str:
return os.environ.get("RB_RESULTS_DIR") or os.environ.get("RESULTS_DIR") or "."
def screenshot_assert(
test_name: str, description: str, results_dir: str | None = None, window=None
):
"""Capture a PNG (optionally cropped to ``window``'s extents) and record a
natural-language assertion for the downstream VLM judge. Writes to both the
append-only jsonl (authoritative key set, survives per-module truncation) and
the tolerant assertions.json dict — exactly the contract phase-2 consumes.
"""
rd = results_dir or _results_dir()
ss_dir = os.path.join(rd, "screenshots")
os.makedirs(ss_dir, exist_ok=True)
fname = f"{test_name}.png"
path = os.path.join(ss_dir, fname)
ok = False
for cmd in (
["import", "-window", "root", path],
["scrot", "-o", path],
["gnome-screenshot", "-f", path],
):
try:
subprocess.run(
cmd, timeout=15, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
)
if os.path.exists(path) and os.path.getsize(path) > 0:
ok = True
break
except Exception:
continue
if ok and window is not None:
try:
ext = window.get_extents(Atspi.CoordType.SCREEN)
if ext.width > 0 and ext.height > 0:
subprocess.run(
[
"convert",
path,
"-crop",
f"{ext.width}x{ext.height}+{ext.x}+{ext.y}",
path,
],
timeout=15,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
except Exception:
pass
if not ok:
return False
try:
with open(os.path.join(ss_dir, "screenshot_asserts.jsonl"), "a") as f:
f.write(
json.dumps({"screenshot": fname, "description": description}) + "\n"
)
except Exception:
pass
try:
aj = os.path.join(ss_dir, "assertions.json")
data = {}
if os.path.exists(aj):
try:
data = json.load(open(aj))
except Exception:
data = {}
data[test_name] = {"screenshot": fname, "description": description}
json.dump(data, open(aj, "w"))
except Exception:
pass
return True