"""Recreation-Bench Windows pytest conftest — per-test app lifecycle + auto result collection. Provides fixtures: app (per-test: launch → yield → kill), rb (per-test depth tracker), results_dir, frame. Each test's outcome is written into ``_results.json`` incrementally (crash-safe). Design notes: - The ``app`` fixture launches a FRESH app instance for each test and kills it after. - Cold mode (RB_APP_BINARY or RB_LAUNCH_SCRIPT set): per-test launch/kill with retries, PID-based window matching, image-name fallback kill. - Warm mode (neither set): attach to already-running app, no kill on teardown. - Results are flushed to disk after EVERY test (crash-safe). """ from __future__ import annotations import json import os import shutil import subprocess import time import pytest try: import rb_testgen_kit as kit _tier_of = kit.tier_of except Exception: def _tier_of(jk): return {"none": 0, "liveness": 1, "reach": 2, "transition": 2, "value": 3}.get(jk, 2) # ── Results accumulator (flushed after every test for crash safety) ─────────── _results: list[dict] = [] def pytest_configure(config): config.addinivalue_line( "markers", "rb(jump_kind, expect, depth): declare behavioral metadata for scoring", ) def pytest_sessionstart(session): _results.clear() def _extract_rb_marker(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", m.args[0] if m.args else "none") expect = m.kwargs.get("expect", m.args[1] if len(m.args) > 1 else "") depth = m.kwargs.get("depth", None) return jk, expect, depth # ── Depth tracker fixture ──────────────────────────────────────────────────── class _RBDepth: __slots__ = ("depth", "reached") def __init__(self): 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 # ── App lifecycle helpers ──────────────────────────────────────────────────── def _results_dir() -> str: return os.environ.get("RB_RESULTS_DIR") or os.environ.get("RESULTS_DIR", ".") _APP_STARTUP_WAIT = 3 _LAUNCH_RETRIES = 3 def _launch_app() -> int | None: """Launch the app with retries. Handles single-instance apps where the initial PID dies and the real process runs under a different PID (found by exe name). Returns PID or None. """ launch_script = os.environ.get("RB_LAUNCH_SCRIPT", "") binary = os.environ.get("RB_APP_BINARY", "") exe_name = os.path.basename(binary) if binary else "" for attempt in range(_LAUNCH_RETRIES): pid = None if launch_script and os.path.exists(launch_script): try: ps_exe = shutil.which("pwsh") or "powershell" result = subprocess.run( [ps_exe, "-ExecutionPolicy", "Bypass", "-File", launch_script], capture_output=True, text=True, timeout=30, encoding="utf-8", errors="replace", ) for line in result.stdout.strip().splitlines(): line = line.strip() if line.isdigit(): pid = int(line) break except Exception: pass elif binary and os.path.exists(binary): try: proc = subprocess.Popen( [binary], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ) pid = proc.pid except Exception: pass if pid is None: if attempt < _LAUNCH_RETRIES - 1: time.sleep(3) continue # Wait for process to settle time.sleep(_APP_STARTUP_WAIT) # Verify the PID is still alive if _is_pid_alive(pid): return pid # Single-instance app: PID died, find real process by exe name if exe_name: real_pid = _find_pid_by_name(exe_name) if real_pid: return real_pid if attempt < _LAUNCH_RETRIES - 1: time.sleep(3) return None def _is_pid_alive(pid: int) -> bool: """Check if a PID is still running.""" try: result = subprocess.run( ["tasklist", "/FI", f"PID eq {pid}", "/NH", "/FO", "CSV"], capture_output=True, text=True, timeout=5, ) return str(pid) in result.stdout except Exception: return False def _find_pid_by_name(exe_name: str) -> int | None: """Find a running process by image name. Returns PID or None.""" try: result = subprocess.run( ["tasklist", "/FI", f"IMAGENAME eq {exe_name}", "/NH", "/FO", "CSV"], capture_output=True, text=True, timeout=5, ) for line in result.stdout.strip().splitlines(): if exe_name.lower() in line.lower(): parts = line.strip('"').split('","') if len(parts) >= 2 and parts[1].strip('"').isdigit(): return int(parts[1].strip('"')) except Exception: pass return None def _kill_app(pid: int) -> None: """Graceful close first (prevents 'restore session?' on next launch), then force kill as fallback, then verify by image name.""" binary = os.environ.get("RB_APP_BINARY", "") exe_name = os.path.basename(binary) if binary else "" # Step 1: Graceful close (WM_CLOSE) — gives app a chance to save state cleanly try: subprocess.run( ["taskkill", "/PID", str(pid)], capture_output=True, timeout=5, ) except Exception: pass # Wait up to 3s for graceful exit for _ in range(6): if not _is_pid_alive(pid): break time.sleep(0.5) # Step 2: Force kill if still alive if _is_pid_alive(pid): try: subprocess.run( ["taskkill", "/F", "/T", "/PID", str(pid)], capture_output=True, timeout=10, ) except Exception: pass time.sleep(1) # Step 3: Fallback kill by image name (catches single-instance app re-PID) if exe_name and _find_pid_by_name(exe_name): try: subprocess.run( ["taskkill", "/F", "/IM", exe_name], capture_output=True, timeout=10, ) except Exception: pass time.sleep(1) def _wait_for_window_by_pid(pid: int, timeout: float = 30.0): """Wait for a window belonging to the given PID (or its children) to appear.""" try: from pywinauto import Desktop import psutil except ImportError: return None deadline = time.time() + timeout while time.time() < deadline: try: # Build PID tree (app may spawn child processes that own the window) pids = {pid} try: parent = psutil.Process(pid) for child in parent.children(recursive=True): pids.add(child.pid) except (psutil.NoSuchProcess, psutil.AccessDenied): pass for w in Desktop(backend="uia").windows(): try: if w.process_id() in pids: title = w.window_text() or "" # Skip empty/system windows if title and title not in ("", "Program Manager", "Microsoft Text Input Application"): return w except Exception: continue except Exception: pass time.sleep(0.5) return None # ── Stray system dialog dismissal (per-test, M5 fix) ──────────────────────── _STRAY_DIALOG_TITLES = { "Shutdown Event Tracker", "Windows Error Reporting", "Microsoft Visual C++ Runtime Library", "Windows Update", ".NET Framework", "Application Error", "Windows Security", } def _dismiss_stray_system_dialogs() -> None: """Close system-level dialogs that can steal focus or block interaction.""" try: from pywinauto import Desktop from pywinauto.keyboard import send_keys for w in Desktop(backend="uia").windows(): try: title = w.window_text() or "" if any(s in title for s in _STRAY_DIALOG_TITLES): try: w.close() except Exception: try: w.set_focus() send_keys("{ESC}") except Exception: pass except Exception: continue except Exception: pass _post_launch_captured = False def _get_module_from_argv() -> str: """Extract module name from sys.argv (pytest is invoked with the test file path).""" for arg in sys.argv: base = os.path.basename(arg) if base.startswith("test_uia_") and base.endswith(".py"): return base[len("test_uia_"):-len(".py")] return "unknown" def _capture_post_launch(window) -> None: """Capture a desktop screenshot after the first successful app launch per module.""" global _post_launch_captured if _post_launch_captured: return _post_launch_captured = True try: from PIL import ImageGrab rd = _results_dir() ss_dir = os.path.join(rd, "screenshots") os.makedirs(ss_dir, exist_ok=True) module = _get_module_from_argv() img = ImageGrab.grab() img.save(os.path.join(ss_dir, f"post_launch_{module}.png")) except Exception: pass # ── App fixtures ───────────────────────────────────────────────────────────── @pytest.fixture(scope="session") def results_dir() -> str: return _results_dir() @pytest.fixture def app(): """Per-test app lifecycle: launch fresh → yield window → kill. Cold mode: PID-based window matching (precise, no false positives). Warm mode: title-based matching (attaches to already-running app). """ import rb_uia app_name = os.environ.get("RB_APP_NAME", "") binary = os.environ.get("RB_APP_BINARY", "") launch_script = os.environ.get("RB_LAUNCH_SCRIPT", "") # Dismiss system-level stray windows before each test (M5 fix) _dismiss_stray_system_dialogs() if binary or launch_script: # Cold mode: launch fresh app for this test pid = _launch_app() if pid is None: pytest.fail("app failed to launch (all retries exhausted)", pytrace=False) # Wait for window by PID (precise matching, no title ambiguity) w = _wait_for_window_by_pid(pid, timeout=30.0) if w is None: _kill_app(pid) pytest.fail( f"app launched (PID={pid}) but no window found within 30s", pytrace=False, ) rb_uia.focus_app_window(w) # Capture post-launch screenshot (once per module for debugging) _capture_post_launch(w) yield w _kill_app(pid) else: # Warm mode: attach to already-running app (for run_live.ps1) w = rb_uia.get_app(app_name) if w is None: pytest.fail( f"app not found via UIA (RB_APP_NAME={app_name!r})", pytrace=False, ) rb_uia.focus_app_window(w) yield w @pytest.fixture def frame(app): """Alias for the app's top-level window.""" return app # ── Hook: collect results per test + flush immediately (C3 fix) ────────────── @pytest.hookimpl(hookwrapper=True) def pytest_runtest_makereport(item, call): outcome = yield report = outcome.get_result() if call.when != "call" and not (call.when == "setup" and report.failed): return jk, expect, declared_depth = _extract_rb_marker(item) tracker = getattr(item, "_rb", None) measured = tracker.reached if tracker else 0 depth = declared_depth if declared_depth is not None else measured passed = report.passed if call.when == "call" else False msg = "" if report.failed and report.longrepr: msg = str(report.longrepr)[-500:] rec = { "name": item.name, "passed": passed, "message": msg, "depth": depth, "jump_kind": jk, "tier": _tier_of(jk), "expect": expect, } _results.append(rec) # Flush immediately after each test (crash-safe: partial results survive) _flush_results(item) def _flush_results(item=None): """Write current results to disk (incremental, crash-safe).""" rd = _results_dir() module = "unknown" if item: fspath = str(item.fspath.basename if hasattr(item.fspath, "basename") else os.path.basename(str(item.fspath))) if fspath.startswith("test_uia_") and fspath.endswith(".py"): module = fspath[len("test_uia_"):-len(".py")] elif _results: module = _module_from_results() payload = {"module": module, "tests": list(_results)} try: os.makedirs(rd, exist_ok=True) with open(os.path.join(rd, f"{module}_results.json"), "w") as f: json.dump(payload, f, indent=2) except Exception: pass def _module_from_results() -> str: return "unknown" # ── Session finish: final write ────────────────────────────────────────────── def pytest_sessionfinish(session, exitstatus): """Final write of results (covers the case where last test didn't trigger flush).""" rd = _results_dir() module = _module_from_session(session) payload = {"module": module, "tests": list(_results)} try: os.makedirs(rd, exist_ok=True) with open(os.path.join(rd, f"{module}_results.json"), "w") as f: json.dump(payload, f, indent=2) except Exception: pass def _module_from_session(session) -> str: """Extract module name from the test file being run.""" items = session.items if items: fspath = str(items[0].fspath.basename if hasattr(items[0].fspath, "basename") else os.path.basename(str(items[0].fspath))) if fspath.startswith("test_uia_") and fspath.endswith(".py"): return fspath[len("test_uia_"):-len(".py")] return "unknown" # ── Terminal summary: run self-audit ───────────────────────────────────────── def pytest_terminal_summary(terminalreporter, exitstatus, config): rd = _results_dir() if not os.path.isdir(rd): return try: import rb_testgen_kit as k terminalreporter.write_sep("=", "RB Self-Audit") k.rb_audit(rd) k.rb_lint(rd) testgen_dir = os.path.dirname(rd) if os.path.basename(rd) == "baseline_results" else rd if os.path.isdir(testgen_dir): k.rb_lint_sources(testgen_dir) k.rb_audit_depth(testgen_dir, rd) k.rb_audit_tier(testgen_dir, rd) except Exception as e: terminalreporter.write_line(f"[rb_audit] skipped: {e}")