Datasets:
File size: 7,170 Bytes
e5a3ec0 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 | """pytest conftest for RecreationBench AT-SPI tests (Tier-1).
Bridges pytest → the legacy scoring contract so nothing downstream changes:
each test's outcome is written into ``<module>_results.json`` in the exact shape
``{"module": m, "tests": [{"name", "passed", "message"}]}`` that
``atspi_test_runner`` / ``build_manifest`` / ``score_against_manifest`` and the
VLM half already consume. Only test *authoring* (pytest) and *execution* (run
pytest instead of ``python3 test_file``) change; the manifest, fixed-denominator
scorer, and ``vlm_assertions`` are untouched.
Provides:
- ``app`` — the AT-SPI Accessible for the app under test (``rb_atspi.get_app``),
session-scoped (the runner launches one app per module and runs pytest on that
module's file, so a session == one module).
- ``results_dir`` — where ``screenshot_assert`` and results land.
- pytest-check is available to tests for soft assertions (many checks per test,
never abort on the first failure); the test == one scored entry (name = the
test function name → manifest key ``<module>::<test_name>``).
"""
from __future__ import annotations
import json
import os
from pathlib import Path
import pytest
try: # kit is co-located on the VM (PYTHONPATH has the tools dir); pure helpers.
import rb_testgen_kit as _kit
except Exception: # pragma: no cover - kit absent -> record the legacy fields only
_kit = None
# nodeid -> {"name", "passed", "message", depth, jump_kind, expect};
# the call phase (or a failing setup) wins.
_RESULTS: dict = {}
def _results_dir() -> str:
return os.environ.get("RB_RESULTS_DIR") or os.environ.get("RESULTS_DIR") or "."
def pytest_configure(config):
config.addinivalue_line(
"markers",
"rb(jump_kind, expect, depth): declare a behavioral test's interaction tier "
"(none/liveness/reach/transition/value), the specific observed target, and "
"optional navigation depth (else measured from rb_enter/rb_reach calls).",
)
def _rb_meta(item):
"""(jump_kind, expect, declared_depth) from the @pytest.mark.rb(...) marker."""
m = item.get_closest_marker("rb")
if m is None:
return "none", "", None
jk = m.kwargs.get("jump_kind") or (m.args[0] if m.args else "none") or "none"
return jk, m.kwargs.get("expect", "") or "", m.kwargs.get("depth", None)
class _RBDepth:
"""Per-test navigation-depth tracker. A test calls ``rb.enter("<surface>")`` on each
real surface crossing (dialog/page/submenu); ``reached`` is the MAX depth — a runtime
count, so it cannot be faked (no source AST audit needed)."""
def __init__(self) -> None:
self.depth = 0
self.reached = 0
def enter(self, _surface: str = "") -> int:
self.depth += 1
self.reached = max(self.reached, self.depth)
return self.depth
def back(self) -> int:
self.depth = max(0, self.depth - 1)
return self.depth
@pytest.fixture
def rb(request):
"""Depth tracker: ``def test_x(app, rb): rb.enter("prefs")``. Fresh per test;
pytest_runtest_makereport reads its ``reached`` into the record's ``depth``."""
tracker = _RBDepth()
request.node._rb = tracker
return tracker
@pytest.fixture(scope="session")
def results_dir() -> str:
return _results_dir()
@pytest.fixture(scope="session")
def app():
"""Attach to the app under test on the AT-SPI bus (by the detected RB_APP_NAME)."""
import rb_atspi
a = rb_atspi.get_app()
if a is None:
pytest.fail(
f"app not found on the AT-SPI bus (RB_APP_NAME={os.environ.get('RB_APP_NAME')!r})",
pytrace=False,
)
# Focus the app's window before any test drives it: a cold-relaunched window
# (run_baseline) is often not WM-focused, so xdotool input misses — this makes the
# cold path behave like the warm run_live instance. Best-effort, no-op if already focused.
rb_atspi.focus_app_window(a)
return a
@pytest.fixture(scope="session")
def frame(app):
"""The app's main top-level frame/window."""
import rb_atspi
return rb_atspi.get_main_frame(app)
def _shorten(s: str, n: int = 400) -> str:
s = " ".join(str(s).split())
return s[-n:] if len(s) > n else s
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
report = outcome.get_result()
# Score the call phase; also capture a setup failure (fixture/app error) as a
# failed test so a broken precondition scores as fail (never silently skipped).
if report.when == "call" or (report.when == "setup" and report.outcome != "passed"):
name = getattr(item, "originalname", None) or item.name
passed = report.outcome == "passed"
msg = "" if passed else _shorten(report.longreprtext or str(report.longrepr))
# Superset fields: the frozen-manifest scorer reads only name/passed; depth/
# jump_kind/expect are consumed by rb_audit. depth = the marker's declared value
# if given, else the MEASURED max from the `rb` fixture (rb.enter() calls).
jk, expect, decl_depth = _rb_meta(item)
tracker = getattr(item, "_rb", None) # the `rb` fixture, if the test used it
depth = (
decl_depth
if decl_depth is not None
else (tracker.reached if tracker else 0)
)
prev = _RESULTS.get(item.nodeid)
if prev is None or report.when == "call":
_RESULTS[item.nodeid] = {
"name": name,
"passed": passed,
"message": msg,
"depth": int(depth or 0),
"jump_kind": jk,
"expect": str(expect),
}
def pytest_sessionfinish(session, exitstatus):
"""Write per-module <module>_results.json in the legacy contract format."""
rd = _results_dir()
by_module: dict[str, list] = {}
for nodeid, rec in _RESULTS.items():
fstem = Path(nodeid.split("::", 1)[0]).stem
module = fstem.replace("test_atspi_", "")
by_module.setdefault(module, []).append(rec)
for module, tests in by_module.items():
payload = {
"module": module,
"tests": tests,
"passed": sum(1 for t in tests if t.get("passed")),
"total": len(tests),
}
try:
with open(os.path.join(rd, f"{module}_results.json"), "w") as f:
json.dump(payload, f, indent=1)
except Exception:
pass
def pytest_terminal_summary(terminalreporter, exitstatus, config):
"""Finalize self-audit (REPORT-ONLY, never a gate): print the depth/rigor quota
gaps + portability issues in pytest's own summary section, so the orchestrator can
target a deeper reach/value test before it finalizes."""
if _kit is None:
return
rd = _results_dir()
tg = os.environ.get("RB_TESTGEN_DIR") or str(getattr(config, "rootdir", "")) or rd
for fn, args in (
(_kit.rb_audit, (rd,)),
(_kit.rb_lint, (rd,)),
(_kit.rb_lint_sources, (tg,)),
):
try:
fn(*args)
except Exception:
pass
|