RecreationBench / ubuntu /solvespace-solvespace /tests /test_atspi_structure.py
VoyagerXHF's picture
Upload folder using huggingface_hub (part 7)
e5a3ec0 verified
Raw History Blame Contribute Delete
23.5 kB
"""AT-SPI STRUCTURE lane for SolveSpace (parametric 2D/3D CAD, GTK3 + OpenGL).
This lane is the GATE (the app's top-level surfaces exist) PLUS tree-SHAPE deltas
(an interaction changes the SHAPE of the AT-SPI tree: a modal adds a NEW top-level
window; a toggle removes/adds a whole frame). It asserts SHAPE ONLY -- the COUNT /
SET of the app's top-level children before -> interact -> after. It never asserts
content, values, CHECKED, or focus: those belong to the text / computation / state
lanes and are ceded to them here.
Every shape delta below was OBSERVED on the running reference (a pre-loaded box with
a translate/step group; two top-level frames on the bus -- the graphics window and the
Property Browser):
* Opening About or Measuring Volume adds a THIRD top-level child, a new `alert` node
named "Information" (a separate "Message -- SolveSpace" X window). The app's count
of SHOWING top-level children goes 2 -> 3; pressing the alert's OK `push button`
removes it (3 -> 2). Pure tree-SHAPE delta -- the dialog's *text* is the text/
computation lane's job, not asserted here.
* Toggling "Show Property Browser" off makes the whole "Property Browser -- SolveSpace"
frame stop SHOWING, so the app's set of SHOWING frames shrinks 2 -> 1; toggling it
back restores 2. The CHECKED state of that menu item is the STATE lane's verdict;
here only the frame COUNT is the verdict.
A pixel-perfect dead shell whose About/Measure opens no new window, and whose Show
Property Browser toggle removes no frame, produces NO shape delta and MUST fail here --
the observable change in the tree's shape is the only signal.
Mechanics (proven on the reference):
- Menu items have INVALID extents (-2147483648) -> not pixel-clickable. Toggles / PB-nav
fire via ``rb_atspi.do_action(item, "click")`` (in place, no focus). The modal-opener
About fires via ``rb_atspi.do_action_safe(item, "click")`` (bounded, won't hang on the
nested dialog loop). Measure Volume fires via its accelerator (Ctrl+Shift+V) sent to the
activated+focused graphics window with the mouse first moved over the canvas.
- The message alert is a SEPARATE X window ("Message --"/"Error -- SolveSpace"); a single
non-overlapping alert also closes via ``do_action`` on its OK `push button`. The autouse
teardown force-closes any leftover dialog (activate its X window, click OK's live
bottom-center) and restores the Property Browser, so tests are order-independent on this
shared single-instance app. Only ONE dialog is opened per test.
No screenshots in this lane: the dialog-appearance is already screenshotted by the menu /
computation lanes, and the Property-Browser-hidden state is already captured by the state
lane -- shipping them again would be duplicate rendered states. The AT-SPI shape COUNTS are
the verdict here.
"""
import os, time, subprocess, gi
gi.require_version('Atspi', '2.0')
from gi.repository import Atspi
import pytest
from pytest_check import check
import rb_atspi
from rb_atspi import rb_showing, rb_reach
# --------------------------------------------------------------------------- #
# Embedded helpers (encode the proven SolveSpace tree-shape mechanics; local)
# --------------------------------------------------------------------------- #
def _gw(app):
"""The graphics-window frame (owns the menu bar), not the Property Browser."""
for i in range(app.get_child_count()):
f = app.get_child_at_index(i)
nm = f.get_name() or ""
if "SolveSpace" in nm and "Property Browser" not in nm:
return f
return rb_atspi.get_main_frame(app)
def _pb(app):
"""The Property Browser top-level frame, or None if not present (toggling Show
Property Browser off removes it from the tree)."""
for i in range(app.get_child_count()):
f = app.get_child_at_index(i)
if "Property Browser" in (f.get_name() or ""):
return f
return None
def _item(app, name):
"""A `check menu item` in the graphics window's menu bar, by plain visible label."""
return rb_atspi.find_first(_gw(app), role="check menu item", name=name)
def _showing_toplevels(app):
"""(role, name) of the app's SHOWING top-level children (frames + alerts)."""
out = []
for i in range(app.get_child_count()):
c = app.get_child_at_index(i)
if rb_atspi.is_showing(c):
out.append((c.get_role_name(), c.get_name() or ""))
return out
def _n_showing(app):
return len(_showing_toplevels(app))
def _showing_frames(app):
"""(role, name) of the app's SHOWING top-level FRAMES only (excludes alerts)."""
return [
(c.get_role_name(), c.get_name() or "")
for i in range(app.get_child_count())
for c in [app.get_child_at_index(i)]
if c.get_role_name() == "frame" and rb_atspi.is_showing(c)
]
def _n_showing_frames(app):
return len(_showing_frames(app))
def _alerts(app):
"""The app's SHOWING top-level `alert` children (message/error dialogs)."""
return [
app.get_child_at_index(i)
for i in range(app.get_child_count())
if app.get_child_at_index(i).get_role_name() == "alert"
and rb_atspi.is_showing(app.get_child_at_index(i))
]
# --- modal message/error dialog handling (separate X windows) --------------- #
def _dialog_wids(app):
"""X window ids of the app's open Message-/Error- dialogs (separate windows)."""
pid = app.get_process_id()
r = subprocess.run(
["xdotool", "search", "--pid", str(pid)], capture_output=True, text=True
)
out = []
for w in r.stdout.split():
nm = subprocess.run(
["xdotool", "getwindowname", w], capture_output=True, text=True
).stdout.strip()
if nm.startswith("Message —") or nm.startswith("Error —"):
out.append(w)
return out
def _dialog_present(app):
return len(_dialog_wids(app)) > 0
def _close_dialogs(app, rounds=6):
"""Force-close any open Message-/Error- dialog by activating its X window and
clicking OK's live bottom-center (AT-SPI OK extents go stale under overlap)."""
for _ in range(rounds):
wids = _dialog_wids(app)
if not wids:
break
for w in wids:
g = subprocess.run(
["xdotool", "getwindowgeometry", "--shell", w],
capture_output=True,
text=True,
).stdout
d = dict(l.split("=") for l in g.strip().splitlines() if "=" in l)
if not d:
continue
subprocess.run(["xdotool", "windowactivate", "--sync", w])
time.sleep(0.2)
cx = int(d["X"]) + int(d["WIDTH"]) // 2
cy = int(d["Y"]) + int(d["HEIGHT"]) - 22
subprocess.run(["xdotool", "mousemove", str(cx), str(cy), "click", "1"])
time.sleep(0.3)
def _gw_wid(app):
"""X window id of the graphics window (for accelerator focus)."""
pid = app.get_process_id()
r = subprocess.run(
["xdotool", "search", "--pid", str(pid)], capture_output=True, text=True
)
for w in r.stdout.split():
nm = subprocess.run(
["xdotool", "getwindowname", w], capture_output=True, text=True
).stdout.strip()
if (
nm.endswith("— SolveSpace")
and "Property Browser" not in nm
and not nm.startswith(("Message", "Error"))
):
return w
return None
def _accel(app, keys):
"""Send a keyboard accelerator to the graphics window. REQUIRES windowactivate
--sync + windowfocus AND the mouse first moved over the canvas, else the key is
dropped (proven by recon)."""
wid = _gw_wid(app)
if wid:
subprocess.run(["xdotool", "windowactivate", "--sync", wid, "windowfocus", wid])
time.sleep(0.4)
subprocess.run(["xdotool", "mousemove", "400", "400"])
time.sleep(0.2)
subprocess.run(["xdotool", "key", "--clearmodifiers", keys])
time.sleep(0.8)
def _restore_pb(app):
"""If a test left the Property Browser hidden, toggle it back on so the two-frame
shape is restored for the next test."""
if _pb(app) is None or not rb_atspi.is_showing(_pb(app)):
it = _item(app, "Show Property Browser")
if it is not None:
rb_atspi.do_action(it, "click")
rb_atspi.wait_for(
lambda: _pb(app) is not None and rb_atspi.is_showing(_pb(app)),
timeout=4.0,
)
# --------------------------------------------------------------------------- #
# Order-independence: no leftover dialog, PB restored, before + after each test.
# --------------------------------------------------------------------------- #
@pytest.fixture(autouse=True)
def _clean(app):
_close_dialogs(app)
_restore_pb(app)
yield
_close_dialogs(app)
_restore_pb(app)
# --------------------------------------------------------------------------- #
# GATE (jump_kind="none", existence) -- kept to exactly these two (<=30% of lane)
# --------------------------------------------------------------------------- #
@pytest.mark.rb(
jump_kind="none",
expect="app node exposes both a graphics-window frame and a Property Browser frame, both SHOWING",
)
def test_top_level_frames_exist(app):
"""GATE: the `solvespace` application node exposes its TWO top-level surfaces --
a graphics-window frame (name ends '— SolveSpace', not the Property Browser) AND a
'Property Browser — SolveSpace' frame -- and both are SHOWING. This is the launch
surface: no frames / not showing => the app did not come up."""
gw = _gw(app)
pb = _pb(app)
check.is_true(gw is not None, "graphics-window frame missing under the app node")
if gw is not None:
check.equal(gw.get_role_name(), "frame", "graphics window should be a frame")
nm = gw.get_name() or ""
check.is_true(
nm.endswith("— SolveSpace") and "Property Browser" not in nm,
f"graphics-window frame title unexpected: {nm!r}",
)
check.is_true(rb_atspi.is_showing(gw), "graphics-window frame is not SHOWING")
check.is_true(pb is not None, "Property Browser frame missing under the app node")
if pb is not None:
check.equal(pb.get_role_name(), "frame", "Property Browser should be a frame")
check.is_true(rb_atspi.is_showing(pb), "Property Browser frame is not SHOWING")
# Both distinct surfaces present and showing at rest -> the app's baseline shape is 2.
check.equal(
_n_showing_frames(app),
2,
f"expected exactly 2 showing top-level frames at rest, saw {_showing_frames(app)}",
)
@pytest.mark.rb(
jump_kind="none",
expect="graphics window contains one menu bar with >=8 menu children",
)
def test_menu_bar_present_with_menus(app):
"""GATE: the graphics window contains exactly one `menu bar`, and that menu bar has
at least the 8 top-level menus (File/Edit/View/New Group/Sketch/Constrain/Analyze/
Help, among others). Asserts SHAPE only (a menu bar with menu children) -- what those
menus DO is the menu lane's job."""
gw = _gw(app)
assert gw is not None, "graphics-window frame missing"
bars = rb_atspi.find_all(gw, role="menu bar")
check.equal(len(bars), 1, f"expected exactly one menu bar, found {len(bars)}")
if bars:
menus = rb_atspi.find_all(bars[0], role="menu")
check.greater_equal(
len(menus),
8,
f"menu bar should expose >=8 menu children, found {len(menus)}: "
f"{[m.get_name() for m in menus]}",
)
names = {m.get_name() for m in menus}
# A couple of anchor menus that must be present in the top-level bar.
for anchor in ("File", "View", "Help"):
check.is_in(anchor, names, f"expected a top-level '{anchor}' menu in the menu bar")
# --------------------------------------------------------------------------- #
# SHAPE DELTAS (interactive) -- the majority of the lane
# --------------------------------------------------------------------------- #
@pytest.mark.rb(
jump_kind="reach",
expect="Help>About adds a THIRD top-level child: a new 'Information' alert window (showing top-levels 2->3)",
)
def test_about_dialog_adds_toplevel_window(app, rb):
"""SHAPE DELTA: opening Help > About adds a NEW top-level window to the tree. Before,
the app has 2 showing top-level children (graphics + Property Browser) and NO alert;
after, there is a THIRD showing child -- an `alert` named 'Information' (a separate
'Message — SolveSpace' X window) -- so the count goes 2 -> 3 and rb_reach confirms the
'Information' surface newly APPEARED. The dialog's TEXT is the text lane's verdict; here
only the new-window shape is asserted. Teardown closes it."""
_close_dialogs(app)
about = rb_atspi.find_first(_gw(app), role="check menu item", name="About")
assert about is not None, "Help>About menu item missing"
before = rb_showing(app)
n_before = _n_showing(app)
check.equal(n_before, 2, f"expected 2 showing top-levels before About, saw {_showing_toplevels(app)}")
check.equal(len(_alerts(app)), 0, "an alert window was already open before About")
rb.enter("about dialog") # real dialog crossing -> measured depth 1
rb_atspi.do_action_safe(about, "click") # modal-opener: bounded, won't hang
appeared = rb_atspi.wait_for(lambda: _n_showing(app) > n_before, timeout=6.0)
after = rb_showing(app)
# SHAPE verdict: count increased by one AND a new alert node exists.
check.is_true(appeared, "About did not add a new top-level window (count did not increase)")
check.equal(
_n_showing(app),
n_before + 1,
f"expected showing top-levels {n_before}->{n_before + 1} after About, saw {_showing_toplevels(app)}",
)
check.greater_equal(len(_alerts(app)), 1, "no new `alert` node appeared after opening About")
# True-jump: the 'Information' alert surface newly appeared (was not there before).
check.is_true(
rb_reach(before, after, target="Information"),
"rb_reach: the 'Information' alert surface did not newly appear after About",
)
_close_dialogs(app)
@pytest.mark.rb(
jump_kind="reach",
expect="Analyze>Measure Volume (Ctrl+Shift+V) adds a new 'Information' alert window (showing top-levels 2->3)",
)
def test_measure_dialog_adds_toplevel_window(app, rb):
"""SHAPE DELTA via a DIFFERENT user path (a keyboard accelerator, not a menu action):
Measure Volume (Ctrl+Shift+V) also spawns a NEW top-level `alert` ('Information',
a separate 'Message — SolveSpace' X window), so the app's showing top-level count goes
2 -> 3 and rb_reach confirms the new surface appeared. The measured VALUE inside is the
computation lane's verdict; here only the added-window shape counts. Teardown closes it."""
_close_dialogs(app)
before = rb_showing(app)
n_before = _n_showing(app)
check.equal(n_before, 2, f"expected 2 showing top-levels before Measure, saw {_showing_toplevels(app)}")
check.equal(len(_alerts(app)), 0, "an alert window was already open before Measure")
rb.enter("measure volume dialog") # real dialog crossing -> measured depth 1
_accel(app, "ctrl+shift+v")
appeared = rb_atspi.wait_for(lambda: _n_showing(app) > n_before, timeout=6.0)
after = rb_showing(app)
check.is_true(appeared, "Measure Volume did not add a new top-level window (count did not increase)")
check.equal(
_n_showing(app),
n_before + 1,
f"expected showing top-levels {n_before}->{n_before + 1} after Measure, saw {_showing_toplevels(app)}",
)
check.greater_equal(len(_alerts(app)), 1, "no new `alert` node appeared after Measure Volume")
check.is_true(
rb_reach(before, after, target="Information"),
"rb_reach: the 'Information' alert surface did not newly appear after Measure Volume",
)
_close_dialogs(app)
@pytest.mark.rb(
jump_kind="reach",
expect="Opening About adds exactly one ALERT top-level while the FRAME count stays 2 (the added surface is a new window, not a re-parented frame)",
)
def test_dialog_adds_alert_not_frame(app, rb):
"""SHAPE DELTA, partitioned by ROLE, to prove WHAT changed: opening a dialog must add
the new surface as a top-level `alert`, NOT change the number of `frame`s. Before, the
app has 2 frames and 0 alerts; after opening About the alert count goes 0 -> 1 while the
FRAME count stays 2 (the two original frames are untouched). This discriminates a real
'new dialog window' shape delta from an app that merely re-labels/re-parents an existing
frame -- the frame set is invariant, only an alert is added. Teardown closes it."""
_close_dialogs(app)
about = rb_atspi.find_first(_gw(app), role="check menu item", name="About")
assert about is not None, "Help>About menu item missing"
frames_before = set(_showing_frames(app))
n_frames_before = len(frames_before)
n_alerts_before = len(_alerts(app))
check.equal(n_frames_before, 2, f"expected 2 showing frames before the dialog, saw {sorted(frames_before)}")
check.equal(n_alerts_before, 0, "an alert was already open before the dialog")
rb.enter("about dialog") # real dialog crossing -> measured depth 1
rb_atspi.do_action_safe(about, "click")
added_alert = rb_atspi.wait_for(lambda: len(_alerts(app)) > n_alerts_before, timeout=6.0)
frames_after = set(_showing_frames(app))
# Verdict: exactly one alert added, and the FRAME set is unchanged.
check.is_true(added_alert, "opening About added no `alert` top-level")
check.equal(
len(_alerts(app)),
n_alerts_before + 1,
f"expected the alert count 0->1, saw {len(_alerts(app))}",
)
check.equal(
frames_after,
frames_before,
f"the FRAME set changed when opening a dialog (should be invariant): "
f"before={sorted(frames_before)} after={sorted(frames_after)}",
)
check.equal(
len(frames_after),
n_frames_before,
f"the number of showing frames changed on dialog open (expected {n_frames_before})",
)
_close_dialogs(app)
@pytest.mark.rb(
jump_kind="transition",
expect="Pressing the alert's OK push button REMOVES the alert window (showing top-levels 3->2)",
)
def test_ok_removes_toplevel_window(app, rb):
"""SHAPE DELTA in the REMOVE direction: with one dialog open (About) the app has N
showing top-levels including the 'Information' alert; pressing that alert's OK
`push button` (do_action 'click' -- a single non-overlapping alert closes in place)
removes the window from the tree, so the count drops N -> N-1 and the alert node is
gone. The window-count shrinking is the verdict (not what the button 'says')."""
_close_dialogs(app)
about = rb_atspi.find_first(_gw(app), role="check menu item", name="About")
assert about is not None, "Help>About menu item missing"
n_base = _n_showing(app)
rb.enter("about dialog") # cross into the dialog we are about to dismiss -> depth 1
rb_atspi.do_action_safe(about, "click")
check.is_true(
rb_atspi.wait_for(lambda: len(_alerts(app)) >= 1, timeout=6.0),
"precondition: About did not open an alert to dismiss",
)
n_open = _n_showing(app)
check.equal(n_open, n_base + 1, f"expected the alert to raise the count to {n_base + 1}, saw {n_open}")
alerts = _alerts(app)
assert alerts, "no alert present to press OK on"
ok = rb_atspi.find_first(alerts[0], role="push button", name="OK") or rb_atspi.find_first(
alerts[0], role="push button"
)
assert ok is not None, "the alert has no OK push button"
# BEFORE -> interact -> AFTER: pressing OK removes the top-level window.
removed = False
if rb_atspi.do_action(ok, "click"):
removed = rb_atspi.wait_for(lambda: _n_showing(app) < n_open, timeout=6.0)
if not removed: # fall back to the live-geometry X-window close, then re-check
_close_dialogs(app)
removed = _n_showing(app) < n_open
check.is_true(removed, "pressing OK did not remove the alert window (count did not decrease)")
check.equal(
_n_showing(app),
n_open - 1,
f"expected showing top-levels {n_open}->{n_open - 1} after OK, saw {_showing_toplevels(app)}",
)
check.equal(len(_alerts(app)), 0, "the `alert` node is still present after pressing OK")
_close_dialogs(app)
@pytest.mark.rb(
jump_kind="transition",
expect="Show Property Browser toggles the whole PB frame out of the showing-frames set (2->1) and back (1->2)",
)
def test_show_property_browser_changes_frame_count(app, rb):
"""SHAPE DELTA on FRAMES (no new window -- a whole frame removed then restored): the
app has 2 showing top-level frames (graphics + Property Browser). Clicking View > Show
Property Browser makes the 'Property Browser — SolveSpace' frame stop SHOWING, so the
set of showing frames shrinks 2 -> 1; clicking again restores it 1 -> 2. The COUNT/SET
of showing frames changing then restoring is the verdict -- the item's CHECKED state is
the state lane's, deliberately not asserted here. Depth 0: hiding a frame is an in-place
toggle, not a navigation into a new surface."""
_close_dialogs(app)
it = _item(app, "Show Property Browser")
assert it is not None, "View>Show Property Browser menu item missing"
frames_before = set(_showing_frames(app))
n_before = len(frames_before)
check.equal(n_before, 2, f"expected 2 showing frames before toggle, saw {sorted(frames_before)}")
check.is_true(
any("Property Browser" in nm for (_r, nm) in frames_before),
"Property Browser frame should be among the showing frames before the toggle",
)
# Toggle OFF -> the PB frame leaves the showing-frames set.
rb_atspi.do_action(it, "click")
shrank = rb_atspi.wait_for(lambda: _n_showing_frames(app) < n_before, timeout=5.0)
frames_off = set(_showing_frames(app))
check.is_true(shrank, "Show Property Browser off did not reduce the showing-frame count")
check.equal(
len(frames_off),
n_before - 1,
f"expected showing frames {n_before}->{n_before - 1} after hiding PB, saw {sorted(frames_off)}",
)
check.is_false(
any("Property Browser" in nm for (_r, nm) in frames_off),
"the Property Browser frame is still showing after toggling it off",
)
# Toggle BACK ON -> the PB frame returns; the shape is restored.
it2 = _item(app, "Show Property Browser") # re-fetch (tree updates after the action)
rb_atspi.do_action(it2, "click")
restored = rb_atspi.wait_for(lambda: _n_showing_frames(app) == n_before, timeout=5.0)
frames_after = set(_showing_frames(app))
check.is_true(restored, "Show Property Browser on did not restore the showing-frame count")
check.equal(
len(frames_after),
n_before,
f"expected showing frames restored to {n_before}, saw {sorted(frames_after)}",
)
check.is_true(
any("Property Browser" in nm for (_r, nm) in frames_after),
"the Property Browser frame did not reappear after toggling Show Property Browser back on",
)
check.equal(
frames_before,
frames_after,
"the set of showing frames did not restore to its original membership",
)