[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7BGF0JWF2NKEB7SWG9ADJBC":3,"skill-same:01M7BGF0JWF2NKEB7SWG9ADJBC":48},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":25,"commitSha":26,"skillDirectory":27,"forksCount":28,"repositoryHtmlUrl":29,"repositoryHomepageUrl":30,"ownerHtmlUrl":31,"ownerBlogUrl":6,"ownerDescription":32,"updatedAt":33,"install":34,"resources":47},"01M7BGF0JWF2NKEB7SWG9ADJBC","windows-desktop-e2e",null,"E2E testing for Windows native desktop apps (WPF, WinForms, Win32\u002FMFC, Qt) using pywinauto and Windows UI Automation.","YYC-Cube\u002FYYC3-Knowledge-Base","YYC-Cube","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F235006543?v=4","01M79J2PH4SWD2X0825X6PN748","yyc3","01M79J2PHVK3F6ZBYT8K2SCZCW",1,"MIT","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-AI-应用工具\u002FYYC3-AI-应用工具-Everything-claude-code\u002Fskills\u002Fwindows-desktop-e2e\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: windows-desktop-e2e\ndescription: E2E testing for Windows native desktop apps (WPF, WinForms, Win32\u002FMFC, Qt) using pywinauto and Windows UI Automation.\norigin: ECC\n---\n\n# Windows Desktop E2E Testing\n\nEnd-to-end testing for Windows native desktop applications using **pywinauto** backed by Windows UI Automation (UIA). Covers WPF, WinForms, Win32\u002FMFC, and Qt (5.x \u002F 6.x) — with Qt-specific guidance as a dedicated section.\n\n## When to Activate\n\n- Writing or running E2E tests for a Windows native desktop application\n- Setting up a desktop GUI test suite from scratch\n- Diagnosing flaky or failing desktop automation tests\n- Adding testability (AutomationId, accessible names) to an existing app\n- Integrating desktop E2E into a CI\u002FCD pipeline (GitHub Actions `windows-latest`)\n\n### When NOT to Use\n\n- Web applications → use `e2e-testing` skill (Playwright)\n- Electron \u002F CEF \u002F WebView2 apps → the HTML layer needs browser automation, not UIA\n- Mobile apps → use platform-specific tools (UIAutomator, XCUITest)\n- Pure unit or integration tests that don't need a running GUI\n\n## Core Concepts\n\nAll Windows desktop automation relies on **UI Automation (UIA)**, a Windows-built-in accessibility API. Every supported framework exposes a tree of UIA elements with properties Claude can read and act on:\n\n```\nYour test (Python)\n    └── pywinauto (UIA backend)\n        └── Windows UI Automation API   ← built into Windows, framework-agnostic\n            └── App's UIA provider      ← each framework ships its own\n                └── Running .exe\n```\n\n**UIA quality by framework:**\n\n| Framework | AutomationId | Reliability | Notes |\n|-----------|-------------|-------------|-------|\n| WPF | ★★★★★ | Excellent | `x:Name` maps directly to AutomationId |\n| WinForms | ★★★★☆ | Good | `AccessibleName` = AutomationId |\n| UWP \u002F WinUI 3 | ★★★★★ | Excellent | Full Microsoft support |\n| Qt 6.x | ★★★★★ | Excellent | Accessibility enabled by default; class names change to `Qt6*` |\n| Qt 5.15+ | ★★★★☆ | Good | Improved Accessibility module |\n| Qt 5.7–5.14 | ★★★☆☆ | Fair | Needs `QT_ACCESSIBILITY=1`; objectName manual |\n| Win32 \u002F MFC | ★★★☆☆ | Fair | Control IDs accessible; text matching common |\n\n## Setup & Prerequisites\n\n```bash\n# Python 3.8+, Windows only\npip install pywinauto pytest pytest-html Pillow pytest-timeout\n# Optional: screen recording\n# Install ffmpeg and add to PATH: https:\u002F\u002Fffmpeg.org\u002Fdownload.html\n```\n\nVerify UIA is reachable:\n\n```python\nfrom pywinauto import Desktop\nDesktop(backend=\"uia\").windows()  # lists all top-level windows\n```\n\nInstall **Accessibility Insights for Windows** (free, from Microsoft) — your DevTools equivalent for inspecting the UIA element tree before writing any test.\n\n## Testability Setup (by Framework)\n\nThe single most impactful thing you can do is **give every interactive control a stable AutomationId** before writing tests.\n\n### WPF\n\n```xml\n\u003C!-- XAML: x:Name becomes AutomationId automatically -->\n\u003CTextBox x:Name=\"usernameInput\" \u002F>\n\u003CPasswordBox x:Name=\"passwordInput\" \u002F>\n\u003CButton x:Name=\"btnLogin\" Content=\"Login\" \u002F>\n\u003CTextBlock x:Name=\"lblError\" \u002F>\n```\n\n### WinForms\n\n```csharp\n\u002F\u002F Set in designer or code\nusernameInput.AccessibleName = \"usernameInput\";\npasswordInput.AccessibleName = \"passwordInput\";\nbtnLogin.AccessibleName = \"btnLogin\";\nlblError.AccessibleName = \"lblError\";\n```\n\n### Win32 \u002F MFC\n\n```cpp\n\u002F\u002F Control resource IDs in .rc file are exposed as AutomationId strings\n\u002F\u002F IDC_EDIT_USERNAME -> AutomationId \"1001\"\n\u002F\u002F Prefer SetWindowText for Name; add IAccessible for richer support\n```\n\n### Qt — see dedicated section below\n\n---\n\n## Page Object Model\n\n```\ntests\u002F\n├── conftest.py          # app launch fixture, failure screenshot\n├── pytest.ini\n├── config.py\n├── pages\u002F\n│   ├── __init__.py      # required for imports\n│   ├── base_page.py     # locators, wait, screenshot helpers\n│   ├── login_page.py\n│   └── main_page.py\n├── tests\u002F\n│   ├── __init__.py\n│   ├── test_login.py\n│   └── test_main_flow.py\n└── artifacts\u002F           # screenshots, videos, logs\n```\n\n### base_page.py\n\n```python\nimport os, time\nfrom pywinauto import Desktop\nfrom config import ACTION_TIMEOUT, ARTIFACT_DIR\n\nclass BasePage:\n    def __init__(self, window):\n        self.window = window\n\n    # --- Locators (priority order) ---\n\n    def by_id(self, auto_id, **kw):\n        \"\"\"AutomationId — most stable. Use as first choice.\"\"\"\n        return self.window.child_window(auto_id=auto_id, **kw)\n\n    def by_name(self, name, **kw):\n        \"\"\"Visible text \u002F accessible name.\"\"\"\n        return self.window.child_window(title=name, **kw)\n\n    def by_class(self, cls, index=0, **kw):\n        \"\"\"Control class + index — fragile, avoid if possible.\"\"\"\n        return self.window.child_window(class_name=cls, found_index=index, **kw)\n\n    # --- Waits ---\n\n    def wait_visible(self, spec, timeout=ACTION_TIMEOUT):\n        spec.wait(\"visible\", timeout=timeout)\n        return spec\n\n    def wait_gone(self, spec, timeout=ACTION_TIMEOUT):\n        spec.wait_not(\"visible\", timeout=timeout)\n        return spec\n\n    def wait_window(self, title, timeout=ACTION_TIMEOUT):\n        \"\"\"Wait for a new top-level window (dialogs, child windows).\"\"\"\n        dlg = Desktop(backend=\"uia\").window(title=title)\n        dlg.wait(\"visible\", timeout=timeout)\n        return dlg\n\n    def wait_until(self, fn, timeout=ACTION_TIMEOUT, interval=0.3):\n        \"\"\"Poll an arbitrary condition — use when UIA events are unreliable.\"\"\"\n        deadline = time.time() + timeout\n        while time.time() \u003C deadline:\n            try:\n                if fn():\n                    return True\n            except Exception:\n                pass\n            time.sleep(interval)\n        raise TimeoutError(f\"Condition not met within {timeout}s\")\n\n    # --- Actions ---\n\n    def click(self, spec):\n        self.wait_visible(spec)\n        spec.click_input()\n\n    def type_text(self, spec, text):\n        self.wait_visible(spec)\n        ctrl = spec.wrapper_object()\n        try:\n            ctrl.set_edit_text(text)\n        except Exception as e:\n            # Qt 5.x fallback: UIA Value Pattern may be incomplete\n            import sys, pywinauto.keyboard as kb\n            print(f\"[windows-desktop-e2e] set_edit_text failed ({e}), using keyboard fallback\", file=sys.stderr)\n            ctrl.click_input()\n            kb.send_keys(\"^a\")\n            kb.send_keys(text, with_spaces=True)\n\n    def get_text(self, spec):\n        ctrl = spec.wrapper_object()\n        for attr in (\"window_text\", \"get_value\"):\n            try:\n                v = getattr(ctrl, attr)()\n                if v:\n                    return v\n            except Exception:\n                pass\n        return \"\"\n\n    # --- Artifacts ---\n\n    def screenshot(self, name):\n        os.makedirs(ARTIFACT_DIR, exist_ok=True)\n        path = os.path.join(ARTIFACT_DIR, f\"{name}.png\")\n        self.window.capture_as_image().save(path)\n        return path\n```\n\n### login_page.py\n\n```python\nfrom pages.base_page import BasePage\n\nclass LoginPage(BasePage):\n    @property\n    def username(self): return self.by_id(\"usernameInput\")\n\n    @property\n    def password(self): return self.by_id(\"passwordInput\")\n\n    @property\n    def btn_login(self): return self.by_id(\"btnLogin\")\n\n    @property\n    def error_label(self): return self.by_id(\"lblError\")\n\n    def login(self, user, pwd):\n        self.type_text(self.username, user)\n        self.type_text(self.password, pwd)\n        self.click(self.btn_login)\n\n    def login_ok(self, user, pwd, main_title=\"Main Window\"):\n        self.login(user, pwd)\n        return self.wait_window(main_title)\n\n    def login_fail(self, user, pwd):\n        self.login(user, pwd)\n        self.wait_visible(self.error_label)\n        return self.get_text(self.error_label)\n```\n\n### conftest.py\n\n> For new projects prefer the **Tier 1 sandbox fixture** (see below) — it adds filesystem isolation at zero extra cost. This basic fixture is for minimal\u002Flegacy setups only.\n\n```python\nimport os, pytest\nos.environ[\"QT_ACCESSIBILITY\"] = \"1\"  # Required for Qt 5.x UIA support\n\nfrom pywinauto import Application\nfrom config import APP_PATH, MAIN_WINDOW_TITLE, LAUNCH_TIMEOUT, ARTIFACT_DIR\n\n@pytest.fixture\ndef app(request):\n    if not APP_PATH:\n        pytest.exit(\"APP_PATH environment variable is not set\", returncode=1)\n    proc = Application(backend=\"uia\").start(APP_PATH, timeout=LAUNCH_TIMEOUT)\n    win  = proc.window(title=MAIN_WINDOW_TITLE)\n    win.wait(\"visible\", timeout=LAUNCH_TIMEOUT)\n    yield win\n    # Screenshot on failure\n    if getattr(getattr(request.node, \"rep_call\", None), \"failed\", False):\n        os.makedirs(ARTIFACT_DIR, exist_ok=True)\n        try:\n            win.capture_as_image().save(\n                os.path.join(ARTIFACT_DIR, f\"FAIL_{request.node.name}.png\")\n            )\n        except Exception:\n            pass\n    # Graceful exit first, force-kill as fallback\n    # proc is a pywinauto Application — use wait_for_process_exit(), not wait_for_process()\n    try:\n        win.close()\n        proc.wait_for_process_exit(timeout=5)\n    except Exception:\n        proc.kill()\n\n@pytest.hookimpl(tryfirst=True, hookwrapper=True)\ndef pytest_runtest_makereport(item, call):\n    outcome = yield\n    setattr(item, f\"rep_{outcome.get_result().when}\", outcome.get_result())\n```\n\n### config.py\n\n```python\nimport os\nAPP_PATH          = os.environ.get(\"APP_PATH\", \"\")           # set via env — no default path\nMAIN_WINDOW_TITLE = os.environ.get(\"APP_TITLE\", \"\")\nLAUNCH_TIMEOUT    = int(os.environ.get(\"LAUNCH_TIMEOUT\", \"15\"))\nACTION_TIMEOUT    = int(os.environ.get(\"ACTION_TIMEOUT\", \"10\"))\nARTIFACT_DIR      = os.path.join(os.path.dirname(__file__), \"artifacts\")\n```\n\n### pytest.ini\n\n```ini\n[pytest]\ntestpaths = tests\nmarkers =\n    smoke: fast smoke tests for critical paths\n    flaky: known-unstable tests\naddopts = -v --tb=short --html=artifacts\u002Freport.html --self-contained-html\n```\n\n## Locator Strategy\n\n```\nAutomationId  >  Name (text)  >  ClassName + index  >  XPath\n  (stable)         (readable)       (fragile)           (last resort)\n```\n\nInspect with Accessibility Insights → **Properties** pane → look for `AutomationId` first.\n\n```python\n# Inspect at runtime — paste into a REPL to explore the tree\nwin.print_control_identifiers()\n# or narrow scope:\nwin.child_window(auto_id=\"groupBox1\").print_control_identifiers()\n```\n\n## Wait Patterns\n\n```python\n# Wait for control to appear\npage.wait_visible(page.by_id(\"statusLabel\"))\n\n# Wait for control to disappear (e.g. loading spinner)\npage.wait_gone(page.by_id(\"spinnerOverlay\"))\n\n# Wait for a dialog to pop up\ndlg = page.wait_window(\"Confirm Delete\")\n\n# Custom condition (e.g. text changes)\npage.wait_until(lambda: page.get_text(page.by_id(\"lblStatus\")) == \"Ready\")\n```\n\n**Never use `time.sleep()` as primary synchronization** — use `wait()` or `wait_until()`.\n\n## Artifact Management\n\n```python\n# Screenshot on demand\npage.screenshot(\"after_login\")\n\n# Full-screen capture (when window is off-screen or minimised)\nimport pyautogui\npyautogui.screenshot(\"artifacts\u002Ffullscreen.png\")\n\n# Screen recording with ffmpeg (start before test, stop after)\nimport subprocess\n\ndef start_recording(name):\n    return subprocess.Popen([\n        \"ffmpeg\", \"-f\", \"gdigrab\", \"-framerate\", \"10\",\n        \"-i\", \"desktop\", \"-y\", f\"artifacts\u002Fvideos\u002F{name}.mp4\"\n    ], stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)\n\ndef stop_recording(proc):\n    proc.stdin.write(b\"q\"); proc.stdin.flush(); proc.wait(timeout=10)\n```\n\n## Per-Step Trace (opt-in)\n\nThe default failure screenshot is often too thin for diagnosing flaky tests. The step-level trace below is **off by default** — enable it only when reproducing a flaky case.\n\n### Enable\n\n```bash\nE2E_TRACE=1 pytest tests\u002Ftest_login.py -v\n# Include typed text in the JSONL log (DO NOT use on tests that type credentials\u002FPII):\nE2E_TRACE=1 E2E_TRACE_INCLUDE_TEXT=1 pytest ...\n```\n\n### Patch into BasePage\n\n```python\nimport os, json, time\nTRACE_ENABLED      = os.environ.get(\"E2E_TRACE\") == \"1\"\nTRACE_INCLUDE_TEXT = os.environ.get(\"E2E_TRACE_INCLUDE_TEXT\") == \"1\"\n\nclass BasePage:\n    _step = 0\n\n    def _trace(self, action, spec=None, text=None):\n        if not TRACE_ENABLED:\n            return\n        BasePage._step += 1\n        idx = f\"{BasePage._step:03d}\"\n        os.makedirs(ARTIFACT_DIR, exist_ok=True)\n        try:\n            self.window.capture_as_image().save(\n                os.path.join(ARTIFACT_DIR, f\"step_{idx}_{action}.png\"))\n        except Exception:\n            pass  # capture failure must not break the test\n        rec = {\n            \"ts\": time.time(), \"step\": BasePage._step, \"action\": action,\n            \"locator\": getattr(spec, \"criteria\", None),\n            \"text\": text if TRACE_INCLUDE_TEXT else (\"\u003Credacted>\" if text else None),\n        }\n        with open(os.path.join(ARTIFACT_DIR, \"trace.jsonl\"), \"a\") as f:\n            f.write(json.dumps(rec) + \"\\n\")\n\n    def click(self, spec):\n        self.wait_visible(spec); self._trace(\"click_before\", spec)\n        spec.click_input();      self._trace(\"click_after\",  spec)\n\n    def type_text(self, spec, text):\n        self.wait_visible(spec); self._trace(\"type_before\", spec, text)\n        # ... existing set_edit_text \u002F keyboard fallback ...\n        self._trace(\"type_after\", spec)\n```\n\n### Caveats\n\n- **PII \u002F credentials**: `type_text` content is `\u003Credacted>` by default. Never set `E2E_TRACE_INCLUDE_TEXT=1` on login or payment flows.\n- **Overhead**: ~50–200ms per action + one PNG per step on disk. Don't enable on the default CI matrix — only on a dedicated flake-repro job.\n- **Artifact bloat**: a long flow produces tens of MB; tune `retention-days` accordingly.\n- **Parallel\u002Frerun hygiene**: this simple example appends to `trace.jsonl` and uses a class-level counter. Clear the artifact directory before reruns, and use per-worker artifact dirs for parallel tests.\n- **Coverage gap**: actions performed outside `BasePage` (raw `pywinauto` calls in test code) are not traced.\n\n## Flaky Test Handling\n\n```python\n# Quarantine — equivalent to Playwright's test.fixme()\n@pytest.mark.skip(reason=\"Flaky: animation race on slow CI. Issue #42\")\ndef test_animated_transition(self, app): ...\n\n# Skip in CI only\n@pytest.mark.skipif(os.environ.get(\"CI\") == \"true\", reason=\"Flaky in CI #43\")\ndef test_heavy_load(self, app): ...\n```\n\nCommon causes and fixes:\n\n| Cause | Fix |\n|-------|-----|\n| Control not ready | Replace `time.sleep` with `wait_visible` |\n| Window not focused | Add `win.set_focus()` before interactions |\n| Animation in progress | `wait_until(lambda: not loading_indicator.exists())` |\n| Dialog timing | `wait_window(title, timeout=15)` |\n| CI display not ready | Set `DISPLAY` or use virtual desktop in CI |\n| `set_edit_text` raises NotImplementedError | UIA ValuePattern missing (common on Qt 5.x) — `BasePage.type_text` already falls back to `keyboard.send_keys` |\n| Control exists but `wait_visible` times out | Window minimised or off-screen — call `win.restore()` + `win.set_focus()` before waiting |\n\n## Test Isolation & Sandbox\n\nThree tiers of isolation — use the lightest tier that satisfies your needs.\n\n### Tier 1 — Filesystem Isolation (default, always use)\n\nEach test gets its own `APPDATA` \u002F `LOCALAPPDATA` \u002F `TEMP` via `subprocess.Popen` and `Application.connect()`. pytest's `tmp_path` fixture handles cleanup automatically.\n\n```python\n# conftest.py — replace the basic `app` fixture with this\nimport os, subprocess, pytest\nfrom pywinauto import Application\nfrom config import APP_PATH, APP_ARGS, APP_TITLE, LAUNCH_TIMEOUT, ACTION_TIMEOUT, ARTIFACT_DIR\n\n@pytest.fixture(scope=\"function\")\ndef app(request, tmp_path):\n    \"\"\"Fresh process + isolated user-data dirs per test.\"\"\"\n    if not APP_PATH:\n        pytest.exit(\"APP_PATH not set\", returncode=1)\n\n    # Redirect all per-user storage to an isolated tmp directory\n    sandbox_env = os.environ.copy()\n    sandbox_env[\"QT_ACCESSIBILITY\"]  = \"1\"\n    sandbox_env[\"APPDATA\"]           = str(tmp_path \u002F \"AppData\" \u002F \"Roaming\")\n    sandbox_env[\"LOCALAPPDATA\"]      = str(tmp_path \u002F \"AppData\" \u002F \"Local\")\n    sandbox_env[\"TEMP\"] = sandbox_env[\"TMP\"] = str(tmp_path \u002F \"Temp\")\n    for p in (sandbox_env[\"APPDATA\"], sandbox_env[\"LOCALAPPDATA\"], sandbox_env[\"TEMP\"]):\n        os.makedirs(p, exist_ok=True)\n\n    if not APP_TITLE:\n        pytest.exit(\"APP_TITLE environment variable is not set\", returncode=1)\n\n    # shlex.split handles quoted args with spaces; plain split() breaks on them\n    import shlex\n    # Launch via subprocess so we can pass env; connect pywinauto by PID\n    proc = subprocess.Popen(\n        [APP_PATH] + shlex.split(APP_ARGS),\n        env=sandbox_env,\n    )\n    pw_app = Application(backend=\"uia\").connect(process=proc.pid, timeout=LAUNCH_TIMEOUT)\n    win    = pw_app.window(title=APP_TITLE)\n    win.wait(\"visible\", timeout=LAUNCH_TIMEOUT)\n    yield win\n\n    if getattr(getattr(request.node, \"rep_call\", None), \"failed\", False):\n        os.makedirs(ARTIFACT_DIR, exist_ok=True)\n        try:\n            win.capture_as_image().save(\n                os.path.join(ARTIFACT_DIR, f\"FAIL_{request.node.name}.png\")\n            )\n        except Exception:\n            pass\n    try:\n        win.close()\n        proc.wait(timeout=5)\n    except Exception:\n        proc.kill()\n    # tmp_path is cleaned up automatically by pytest\n\n@pytest.hookimpl(tryfirst=True, hookwrapper=True)\ndef pytest_runtest_makereport(item, call):\n    outcome = yield\n    setattr(item, f\"rep_{outcome.get_result().when}\", outcome.get_result())\n```\n\n### Tier 2 — Windows Job Object (optional: process-lifetime containment)\n\nAttach the process to a Job Object so it is **automatically terminated** when\nthe test fixture's job handle is GC'd. Also prevents the app from spawning\nchild processes that escape fixture cleanup.\n\n> **Scope of isolation:** Job Objects do NOT virtualize filesystem access or\n> block network traffic. File-write and network isolation require AppContainer,\n> Windows Firewall rules, or Tier 3 (Windows Sandbox). Use Tier 2 only for\n> process-lifetime and child-process containment.\n\nRequires no extra dependencies.\n\n```python\nimport ctypes, ctypes.wintypes as wt\n\ndef restrict_process(pid: int):\n    \"\"\"\n    Attach the process to a Job Object that prevents it from:\n    - spawning processes outside the job (LIMIT_KILL_ON_JOB_CLOSE)\n    Does NOT block network — use Windows Firewall rules for that.\n    \"\"\"\n    JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x00002000\n    # Minimal rights: SET_QUOTA (0x0100) | TERMINATE (0x0001)\n    PROCESS_SET_QUOTA_AND_TERMINATE    = 0x0101\n\n    kernel32 = ctypes.windll.kernel32\n    job   = kernel32.CreateJobObjectW(None, None)\n    hproc = kernel32.OpenProcess(PROCESS_SET_QUOTA_AND_TERMINATE, False, pid)\n\n    # Correct struct layout — LimitFlags is at offset +16, not +44\n    class JOBOBJECT_BASIC_LIMIT_INFORMATION(ctypes.Structure):\n        _fields_ = [\n            (\"PerProcessUserTimeLimit\", wt.LARGE_INTEGER),\n            (\"PerJobUserTimeLimit\",     wt.LARGE_INTEGER),\n            (\"LimitFlags\",             wt.DWORD),\n            (\"MinimumWorkingSetSize\",   ctypes.c_size_t),\n            (\"MaximumWorkingSetSize\",   ctypes.c_size_t),\n            (\"ActiveProcessLimit\",      wt.DWORD),\n            (\"Affinity\",               ctypes.c_size_t),\n            (\"PriorityClass\",          wt.DWORD),\n            (\"SchedulingClass\",        wt.DWORD),\n        ]\n\n    info = JOBOBJECT_BASIC_LIMIT_INFORMATION()\n    info.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE\n    ok = kernel32.SetInformationJobObject(job, 2, ctypes.byref(info), ctypes.sizeof(info))\n    if not ok:\n        raise ctypes.WinError()\n    kernel32.AssignProcessToJobObject(job, hproc)\n    kernel32.CloseHandle(hproc)\n    return job  # keep alive — job closes (kills proc) when GC'd\n\n# After proc = subprocess.Popen(...):  job = restrict_process(proc.pid)\n```\n\n### Tier 3 — Windows Sandbox (CI full-OS isolation)\n\nWhen you need a clean Windows image per run (no leftover registry keys, no\nshared GPU state, true isolation), run the **entire test suite** inside\n[Windows Sandbox](https:\u002F\u002Flearn.microsoft.com\u002Fwindows\u002Fsecurity\u002Fapplication-security\u002Fapplication-isolation\u002Fwindows-sandbox\u002Fwindows-sandbox-overview).\n\n**Requirement:** Windows 10\u002F11 Pro or Enterprise, Virtualization enabled.\n\nCreate `e2e-sandbox.wsb` in your project root:\n\n```xml\n\u003CConfiguration>\n  \u003CMappedFolders>\n    \u003C!-- App binary (read-only) -->\n    \u003CMappedFolder>\n      \u003CHostFolder>C:\\path\\to\\your\\build\\Release\u003C\u002FHostFolder>\n      \u003CSandboxFolder>C:\\app\u003C\u002FSandboxFolder>\n      \u003CReadOnly>true\u003C\u002FReadOnly>\n    \u003C\u002FMappedFolder>\n    \u003C!-- Test suite (read-write for artifacts) -->\n    \u003CMappedFolder>\n      \u003CHostFolder>C:\\path\\to\\your\\e2e_test\u003C\u002FHostFolder>\n      \u003CSandboxFolder>C:\\e2e_test\u003C\u002FSandboxFolder>\n      \u003CReadOnly>false\u003C\u002FReadOnly>\n    \u003C\u002FMappedFolder>\n  \u003C\u002FMappedFolders>\n  \u003CLogonCommand>\n    \u003C!--\n      Windows Sandbox starts with no Python. Install it silently first,\n      then install deps and run tests. Artifacts are written back to the\n      host via the MappedFolder above.\n    -->\n    \u003CCommand>powershell -Command \"\n      winget install --id Python.Python.3.11 --silent --accept-package-agreements;\n      $env:PATH += ';' + $env:LOCALAPPDATA + '\\Programs\\Python\\Python311\\Scripts';\n      cd C:\\e2e_test;\n      pip install -r requirements.txt;\n      pytest tests\\ -v\n    \"\u003C\u002FCommand>\n  \u003C\u002FLogonCommand>\n\u003C\u002FConfiguration>\n```\n\nLaunch: `WindowsSandbox.exe e2e-sandbox.wsb`\n\n> pywinauto and the app both run **inside** the sandbox (same session required).\n> Artifacts are written back to the host via the mapped folder.\n\n### Tier comparison\n\n| Tier | Isolation | Setup cost | Works on CI | Use when |\n|------|-----------|-----------|-------------|----------|\n| 1 — `tmp_path` env redirect | Filesystem | Zero | Always | Default for all tests |\n| 2 — Job Object | Process tree | Low | Always | Prevent child-process escape |\n| 3 — Windows Sandbox | Full OS | Medium | Needs Pro\u002FEnterprise image | Nightly clean-room runs |\n\n### Prevent hanging tests\n\nAdd `pytest-timeout` to cap any single test. In `pytest.ini` set `timeout = 60` and `timeout_method = thread`. Note: `thread` method cannot kill Qt app subprocesses on Windows — add `atexit.register(lambda: [p.kill() for p in psutil.Process().children(recursive=True)])` in `conftest.py` to reap orphans.\n\n## CI\u002FCD Integration\n\n```yaml\n# .github\u002Fworkflows\u002Fe2e-desktop.yml\nname: Desktop E2E\non: [push, pull_request]\n\njobs:\n  e2e:\n    runs-on: windows-latest   # real GUI environment, no Xvfb needed\n    steps:\n      - uses: actions\u002Fcheckout@v4\n\n      - uses: actions\u002Fsetup-python@v5\n        with: { python-version: \"3.11\" }\n\n      - name: Install deps\n        run: pip install pywinauto pytest pytest-html Pillow\n\n      - name: Build app\n        run: cmake --build build --config Release  # adjust to your build system\n\n      - name: Run E2E\n        env:\n          APP_PATH: ${{ github.workspace }}\\build\\Release\\MyApp.exe\n          APP_TITLE: \"My Application\"\n          CI: \"true\"\n        run: pytest tests\u002F --html=artifacts\u002Freport.html --self-contained-html --junitxml=artifacts\u002Fresults.xml -v\n\n      - uses: actions\u002Fupload-artifact@v4\n        if: always()\n        with:\n          name: e2e-artifacts\n          path: artifacts\u002F\n          retention-days: 14\n```\n\n## Qt Specific\n\n### Enable UIA in Qt 5.x\n\nQt 5.x accessibility is disabled by default in some builds (especially 5.7–5.14). Set the environment variable **before** launching. Qt 6.x enables accessibility by default — skip this step for Qt 6.\n\n```python\n# conftest.py — add at module top\nimport os\nos.environ[\"QT_ACCESSIBILITY\"] = \"1\"\n```\n\nOr export it in CI:\n\n```yaml\nenv:\n  QT_ACCESSIBILITY: \"1\"\n```\n\n### Add Stable Identifiers to Qt Widgets\n\n```cpp\n\u002F\u002F Preferred: both objectName and accessibleName\nvoid setTestId(QWidget* w, const char* id) {\n    w->setObjectName(id);\n    w->setAccessibleName(id);  \u002F\u002F becomes UIA Name property\n}\n\n\u002F\u002F In your dialog constructor:\nsetTestId(ui->usernameEdit, \"usernameInput\");\nsetTestId(ui->passwordEdit, \"passwordInput\");\nsetTestId(ui->loginButton,  \"btnLogin\");\nsetTestId(ui->errorLabel,   \"lblError\");\n```\n\nCentralise all IDs in a header to avoid typos:\n\n```cpp\n\u002F\u002F test_ids.h\n#define TID_USERNAME   \"usernameInput\"\n#define TID_PASSWORD   \"passwordInput\"\n#define TID_BTN_LOGIN  \"btnLogin\"\n#define TID_LBL_ERROR  \"lblError\"\n```\n\n### Qt-Specific Quirks\n\n**QComboBox** — the dropdown is a separate top-level window:\n\n```python\nfrom pywinauto import Desktop\n\ndef select_combo_item(page, combo_spec, item_text):\n    page.click(combo_spec)\n    # Dropdown appears as a new root-level window\n    # class_name varies by Qt version — verify with Accessibility Insights\n    # Qt 5.x: \"Qt5QWindowIcon\"  |  Qt 6.x: \"Qt6QWindowIcon\" — verify with Accessibility Insights\n    popup = Desktop(backend=\"uia\").window(class_name_re=\"Qt[56]QWindowIcon\")\n    popup.wait(\"visible\", timeout=5)\n    popup.child_window(title=item_text).click_input()\n```\n\n**QMessageBox \u002F QDialog** — also separate top-level windows:\n\n```python\ndlg = page.wait_window(\"Confirm\")          # wait for dialog title\ndlg.child_window(title=\"OK\").click_input() # click button inside it\n```\n\n**QTableWidget \u002F QTableView** — row\u002Fcell access:\n\n```python\ntable = page.by_id(\"tblUsers\").wrapper_object()\ncell  = table.cell(row=0, column=1)\nprint(cell.window_text())\n```\n\n**Self-drawn controls** (`paintEvent`-only, `QGraphicsView`, `QOpenGLWidget`) — UIA cannot see their internals. Use the Fallback section below.\n\n## Fallback: Screenshot Mode\n\nWhen a control is not reachable via UIA (self-drawn, third-party, game engine):\n\n```bash\npip install pyautogui Pillow opencv-python\n```\n\n```python\nimport pyautogui, cv2, numpy as np\nfrom PIL import Image\n\ndef find_image_on_screen(template_path, confidence=0.85):\n    \"\"\"Locate a template image on screen. Returns (x, y) center or None.\"\"\"\n    screen   = np.array(pyautogui.screenshot())\n    template = np.array(Image.open(template_path))\n    result   = cv2.matchTemplate(\n        cv2.cvtColor(screen, cv2.COLOR_RGB2BGR),\n        cv2.cvtColor(template, cv2.COLOR_RGB2BGR),\n        cv2.TM_CCOEFF_NORMED,\n    )\n    _, max_val, _, max_loc = cv2.minMaxLoc(result)\n    if max_val >= confidence:\n        h, w = template.shape[:2]\n        return max_loc[0] + w \u002F\u002F 2, max_loc[1] + h \u002F\u002F 2\n    return None\n\ndef click_image(template_path, confidence=0.85):\n    pos = find_image_on_screen(template_path, confidence)\n    if pos is None:\n        raise RuntimeError(f\"Image not found on screen: {template_path}\")\n    pyautogui.click(*pos)\n```\n\n### DPI \u002F Scaling Rules (screenshot mode only)\n\nScreenshot matching is brutally sensitive to Windows display scaling (100% \u002F 125% \u002F 150%). Three hard rules:\n\n1. **Capture templates at the same scale as the target machine.** Don't try to rescue a mismatch with `PIL.Image.resize` — `cv2.matchTemplate` is very fragile against resampling artefacts.\n2. **Pin the CI display scaling.** On `windows-latest` add a step like `Set-DisplayResolution 1920 1080 -Force` and disable per-monitor DPI scaling, so screenshot dimensions are reproducible.\n3. **Record the scale alongside each artefact.** On capture, write `GetDpiForWindow(hwnd) \u002F 96` to `artifacts\u002F\u003Ctest>\u002Fmetadata.json` — postmortems become obvious instead of guess-work.\n\n> Process-level DPI awareness (`SetProcessDpiAwarenessContext`) **can conflict with Qt's own DPI handling** when the app under test is Qt-based. Prefer \"same-scale templates + CI pin\" over flipping process-wide DPI mode in fixtures.\n\n### Debugging Match Confidence\n\nWhen tuning the `confidence` threshold, the only sane workflow is to **see** where the match landed. The helper below is diagnosis-only — do not call it from test code.\n\n```python\ndef debug_match(template_path, out=\"artifacts\u002Fmatch_debug.png\", confidence=0.85):\n    \"\"\"Diagnosis-only. Draw the best-match rectangle + score back on the current screen.\n\n    NOT for production tests — use when calibrating confidence or chasing false matches.\n    \"\"\"\n    import os, cv2, pyautogui, numpy as np\n    screen = np.array(pyautogui.screenshot())[:, :, ::-1]\n    tpl    = cv2.imread(template_path)\n    if tpl is None:\n        raise RuntimeError(f\"Template unreadable: {template_path}\")\n    res    = cv2.matchTemplate(screen, tpl, cv2.TM_CCOEFF_NORMED)\n    _, mv, _, ml = cv2.minMaxLoc(res)\n    h, w   = tpl.shape[:2]\n    colour = (0, 255, 0) if mv >= confidence else (0, 0, 255)  # green pass \u002F red fail\n    cv2.rectangle(screen, ml, (ml[0]+w, ml[1]+h), colour, 2)\n    cv2.putText(screen, f\"score={mv:.3f} thr={confidence}\",\n                (ml[0], max(20, ml[1]-6)),\n                cv2.FONT_HERSHEY_SIMPLEX, 0.7, colour, 2)\n    os.makedirs(os.path.dirname(out) or \".\", exist_ok=True)\n    cv2.imwrite(out, screen)\n    return mv\n```\n\n**Use sparingly** — image matching breaks on DPI changes, theme switches, and partial occlusion.\nAlways try UIA first; fall back to screenshots only for genuinely unreachable controls.\n\n## Anti-Patterns\n\n```python\n# BAD: fixed sleep\ntime.sleep(3)\npage.click(page.by_id(\"btnSubmit\"))\n\n# GOOD: condition wait\npage.wait_visible(page.by_id(\"btnSubmit\"))\npage.click(page.by_id(\"btnSubmit\"))\n```\n\n```python\n# BAD: brittle class+index locator as primary strategy\npage.by_class(\"Edit\", index=2).type_keys(\"hello\")\n\n# GOOD: AutomationId\npage.by_id(\"usernameInput\").set_edit_text(\"hello\")\n```\n\n```python\n# BAD: assert on pixel coordinates\nassert btn.rectangle().left == 120\n\n# GOOD: assert on content \u002F state\nassert page.get_text(page.by_id(\"lblStatus\")) == \"Logged in\"\nassert page.by_id(\"btnLogout\").is_enabled()\n```\n\n```python\n# BAD: share app instance across all tests (state leaks)\n@pytest.fixture(scope=\"session\")\ndef app(): ...\n\n# GOOD: fresh process per test (or per class at most)\n@pytest.fixture(scope=\"function\")\ndef app(): ...\n```\n\n## Running Tests\n\n```bash\n# All tests\npytest tests\u002F -v\n\n# Smoke only\npytest tests\u002F -m smoke -v\n\n# Specific file\npytest tests\u002Ftest_login.py -v\n\n# With custom app path\nAPP_PATH=\"C:\\build\\Release\\MyApp.exe\" APP_TITLE=\"MyApp\" pytest tests\u002F -v\n\n# Detect flaky tests (repeat each 5 times)\npip install pytest-repeat\npytest tests\u002Ftest_login.py --count=5 -v\n```\n\n## Related Skills\n\n- `e2e-testing` — Playwright E2E for web applications\n- `cpp-testing` — C++ unit\u002Fintegration testing with GoogleTest\n- `cpp-coding-standards` — C++ code style and patterns\n","# Windows Desktop E2E Testing\n\nEnd-to-end testing for Windows native desktop applications using **pywinauto** backed by Windows UI Automation (UIA). Covers WPF, WinForms, Win32\u002FMFC, and Qt (5.x \u002F 6.x) — with Qt-specific guidance as a dedicated section.\n\n## When to Activate\n\n- Writing or running E2E tests for a Windows native desktop application\n- Setting up a desktop GUI test suite from scratch\n- Diagnosing flaky or failing desktop automation tests\n- Adding testability (AutomationId, accessible names) to an existing app\n- Integrating desktop E2E into a CI\u002FCD pipeline (GitHub Actions `windows-latest`)\n\n### When NOT to Use\n\n- Web applications → use `e2e-testing` skill (Playwright)\n- Electron \u002F CEF \u002F WebView2 apps → the HTML layer needs browser automation, not UIA\n- Mobile apps → use platform-specific tools (UIAutomator, XCUITest)\n- Pure unit or integration tests that don't need a running GUI\n\n## Core Concepts\n\nAll Windows desktop automation relies on **UI Automation (UIA)**, a Windows-built-in accessibility API. Every supported framework exposes a tree of UIA elements with properties Claude can read and act on:\n\n```\nYour test (Python)\n    └── pywinauto (UIA backend)\n        └── Windows UI Automation API   ← built into Windows, framework-agnostic\n            └── App's UIA provider      ← each framework ships its own\n                └── Running .exe\n```\n\n**UIA quality by framework:**\n\n| Framework | AutomationId | Reliability | Notes |\n|-----------|-------------|-------------|-------|\n| WPF | ★★★★★ | Excellent | `x:Name` maps directly to AutomationId |\n| WinForms | ★★★★☆ | Good | `AccessibleName` = AutomationId |\n| UWP \u002F WinUI 3 | ★★★★★ | Excellent | Full Microsoft support |\n| Qt 6.x | ★★★★★ | Excellent | Accessibility enabled by default; class names change to `Qt6*` |\n| Qt 5.15+ | ★★★★☆ | Good | Improved Accessibility module |\n| Qt 5.7–5.14 | ★★★☆☆ | Fair | Needs `QT_ACCESSIBILITY=1`; objectName manual |\n| Win32 \u002F MFC | ★★★☆☆ | Fair | Control IDs accessible; text matching common |\n\n## Setup & Prerequisites\n\n```bash\n# Python 3.8+, Windows only\npip install pywinauto pytest pytest-html Pillow pytest-timeout\n# Optional: screen recording\n# Install ffmpeg and add to PATH: https:\u002F\u002Fffmpeg.org\u002Fdownload.html\n```\n\nVerify UIA is reachable:\n\n```python\nfrom pywinauto import Desktop\nDesktop(backend=\"uia\").windows()  # lists all top-level windows\n```\n\nInstall **Accessibility Insights for Windows** (free, from Microsoft) — your DevTools equivalent for inspecting the UIA element tree before writing any test.\n\n## Testability Setup (by Framework)\n\nThe single most impactful thing you can do is **give every interactive control a stable AutomationId** before writing tests.\n\n### WPF\n\n```xml\n\u003C!-- XAML: x:Name becomes AutomationId automatically -->\n\u003CTextBox x:Name=\"usernameInput\" \u002F>\n\u003CPasswordBox x:Name=\"passwordInput\" \u002F>\n\u003CButton x:Name=\"btnLogin\" Content=\"Login\" \u002F>\n\u003CTextBlock x:Name=\"lblError\" \u002F>\n```\n\n### WinForms\n\n```csharp\n\u002F\u002F Set in designer or code\nusernameInput.AccessibleName = \"usernameInput\";\npasswordInput.AccessibleName = \"passwordInput\";\nbtnLogin.AccessibleName = \"btnLogin\";\nlblError.AccessibleName = \"lblError\";\n```\n\n### Win32 \u002F MFC\n\n```cpp\n\u002F\u002F Control resource IDs in .rc file are exposed as AutomationId strings\n\u002F\u002F IDC_EDIT_USERNAME -> AutomationId \"1001\"\n\u002F\u002F Prefer SetWindowText for Name; add IAccessible for richer support\n```\n\n### Qt — see dedicated section below\n\n---\n\n## Page Object Model\n\n```\ntests\u002F\n├── conftest.py          # app launch fixture, failure screenshot\n├── pytest.ini\n├── config.py\n├── pages\u002F\n│   ├── __init__.py      # required for imports\n│   ├── base_page.py     # locators, wait, screenshot helpers\n│   ├── login_page.py\n│   └── main_page.py\n├── tests\u002F\n│   ├── __init__.py\n│   ├── test_login.py\n│   └── test_main_flow.py\n└── artifacts\u002F           # screenshots, videos, logs\n```\n\n### base_page.py\n\n```python\nimport os, time\nfrom pywinauto import Desktop\nfrom config import ACTION_TIMEOUT, ARTIFACT_DIR\n\nclass BasePage:\n    def __init__(self, window):\n        self.window = window\n\n    # --- Locators (priority order) ---\n\n    def by_id(self, auto_id, **kw):\n        \"\"\"AutomationId — most stable. Use as first choice.\"\"\"\n        return self.window.child_window(auto_id=auto_id, **kw)\n\n    def by_name(self, name, **kw):\n        \"\"\"Visible text \u002F accessible name.\"\"\"\n        return self.window.child_window(title=name, **kw)\n\n    def by_class(self, cls, index=0, **kw):\n        \"\"\"Control class + index — fragile, avoid if possible.\"\"\"\n        return self.window.child_window(class_name=cls, found_index=index, **kw)\n\n    # --- Waits ---\n\n    def wait_visible(self, spec, timeout=ACTION_TIMEOUT):\n        spec.wait(\"visible\", timeout=timeout)\n        return spec\n\n    def wait_gone(self, spec, timeout=ACTION_TIMEOUT):\n        spec.wait_not(\"visible\", timeout=timeout)\n        return spec\n\n    def wait_window(self, title, timeout=ACTION_TIMEOUT):\n        \"\"\"Wait for a new top-level window (dialogs, child windows).\"\"\"\n        dlg = Desktop(backend=\"uia\").window(title=title)\n        dlg.wait(\"visible\", timeout=timeout)\n        return dlg\n\n    def wait_until(self, fn, timeout=ACTION_TIMEOUT, interval=0.3):\n        \"\"\"Poll an arbitrary condition — use when UIA events are unreliable.\"\"\"\n        deadline = time.time() + timeout\n        while time.time() \u003C deadline:\n            try:\n                if fn():\n                    return True\n            except Exception:\n                pass\n            time.sleep(interval)\n        raise TimeoutError(f\"Condition not met within {timeout}s\")\n\n    # --- Actions ---\n\n    def click(self, spec):\n        self.wait_visible(spec)\n        spec.click_input()\n\n    def type_text(self, spec, text):\n        self.wait_visible(spec)\n        ctrl = spec.wrapper_object()\n        try:\n            ctrl.set_edit_text(text)\n        except Exception as e:\n            # Qt 5.x fallback: UIA Value Pattern may be incomplete\n            import sys, pywinauto.keyboard as kb\n            print(f\"[windows-desktop-e2e] set_edit_text failed ({e}), using keyboard fallback\", file=sys.stderr)\n            ctrl.click_input()\n            kb.send_keys(\"^a\")\n            kb.send_keys(text, with_spaces=True)\n\n    def get_text(self, spec):\n        ctrl = spec.wrapper_object()\n        for attr in (\"window_text\", \"get_value\"):\n            try:\n                v = getattr(ctrl, attr)()\n                if v:\n                    return v\n            except Exception:\n                pass\n        return \"\"\n\n    # --- Artifacts ---\n\n    def screenshot(self, name):\n        os.makedirs(ARTIFACT_DIR, exist_ok=True)\n        path = os.path.join(ARTIFACT_DIR, f\"{name}.png\")\n        self.window.capture_as_image().save(path)\n        return path\n```\n\n### login_page.py\n\n```python\nfrom pages.base_page import BasePage\n\nclass LoginPage(BasePage):\n    @property\n    def username(self): return self.by_id(\"usernameInput\")\n\n    @property\n    def password(self): return self.by_id(\"passwordInput\")\n\n    @property\n    def btn_login(self): return self.by_id(\"btnLogin\")\n\n    @property\n    def error_label(self): return self.by_id(\"lblError\")\n\n    def login(self, user, pwd):\n        self.type_text(self.username, user)\n        self.type_text(self.password, pwd)\n        self.click(self.btn_login)\n\n    def login_ok(self, user, pwd, main_title=\"Main Window\"):\n        self.login(user, pwd)\n        return self.wait_window(main_title)\n\n    def login_fail(self, user, pwd):\n        self.login(user, pwd)\n        self.wait_visible(self.error_label)\n        return self.get_text(self.error_label)\n```\n\n### conftest.py\n\n> For new projects prefer the **Tier 1 sandbox fixture** (see below) — it adds filesystem isolation at zero extra cost. This basic fixture is for minimal\u002Flegacy setups only.\n\n```python\nimport os, pytest\nos.environ[\"QT_ACCESSIBILITY\"] = \"1\"  # Required for Qt 5.x UIA support\n\nfrom pywinauto import Application\nfrom config import APP_PATH, MAIN_WINDOW_TITLE, LAUNCH_TIMEOUT, ARTIFACT_DIR\n\n@pytest.fixture\ndef app(request):\n    if not APP_PATH:\n        pytest.exit(\"APP_PATH environment variable is not set\", returncode=1)\n    proc = Application(backend=\"uia\").start(APP_PATH, timeout=LAUNCH_TIMEOUT)\n    win  = proc.window(title=MAIN_WINDOW_TITLE)\n    win.wait(\"visible\", timeout=LAUNCH_TIMEOUT)\n    yield win\n    # Screenshot on failure\n    if getattr(getattr(request.node, \"rep_call\", None), \"failed\", False):\n        os.makedirs(ARTIFACT_DIR, exist_ok=True)\n        try:\n            win.capture_as_image().save(\n                os.path.join(ARTIFACT_DIR, f\"FAIL_{request.node.name}.png\")\n            )\n        except Exception:\n            pass\n    # Graceful exit first, force-kill as fallback\n    # proc is a pywinauto Application — use wait_for_process_exit(), not wait_for_process()\n    try:\n        win.close()\n        proc.wait_for_process_exit(timeout=5)\n    except Exception:\n        proc.kill()\n\n@pytest.hookimpl(tryfirst=True, hookwrapper=True)\ndef pytest_runtest_makereport(item, call):\n    outcome = yield\n    setattr(item, f\"rep_{outcome.get_result().when}\", outcome.get_result())\n```\n\n### config.py\n\n```python\nimport os\nAPP_PATH          = os.environ.get(\"APP_PATH\", \"\")           # set via env — no default path\nMAIN_WINDOW_TITLE = os.environ.get(\"APP_TITLE\", \"\")\nLAUNCH_TIMEOUT    = int(os.environ.get(\"LAUNCH_TIMEOUT\", \"15\"))\nACTION_TIMEOUT    = int(os.environ.get(\"ACTION_TIMEOUT\", \"10\"))\nARTIFACT_DIR      = os.path.join(os.path.dirname(__file__), \"artifacts\")\n```\n\n### pytest.ini\n\n```ini\n[pytest]\ntestpaths = tests\nmarkers =\n    smoke: fast smoke tests for critical paths\n    flaky: known-unstable tests\naddopts = -v --tb=short --html=artifacts\u002Freport.html --self-contained-html\n```\n\n## Locator Strategy\n\n```\nAutomationId  >  Name (text)  >  ClassName + index  >  XPath\n  (stable)         (readable)       (fragile)           (last resort)\n```\n\nInspect with Accessibility Insights → **Properties** pane → look for `AutomationId` first.\n\n```python\n# Inspect at runtime — paste into a REPL to explore the tree\nwin.print_control_identifiers()\n# or narrow scope:\nwin.child_window(auto_id=\"groupBox1\").print_control_identifiers()\n```\n\n## Wait Patterns\n\n```python\n# Wait for control to appear\npage.wait_visible(page.by_id(\"statusLabel\"))\n\n# Wait for control to disappear (e.g. loading spinner)\npage.wait_gone(page.by_id(\"spinnerOverlay\"))\n\n# Wait for a dialog to pop up\ndlg = page.wait_window(\"Confirm Delete\")\n\n# Custom condition (e.g. text changes)\npage.wait_until(lambda: page.get_text(page.by_id(\"lblStatus\")) == \"Ready\")\n```\n\n**Never use `time.sleep()` as primary synchronization** — use `wait()` or `wait_until()`.\n\n## Artifact Management\n\n```python\n# Screenshot on demand\npage.screenshot(\"after_login\")\n\n# Full-screen capture (when window is off-screen or minimised)\nimport pyautogui\npyautogui.screenshot(\"artifacts\u002Ffullscreen.png\")\n\n# Screen recording with ffmpeg (start before test, stop after)\nimport subprocess\n\ndef start_recording(name):\n    return subprocess.Popen([\n        \"ffmpeg\", \"-f\", \"gdigrab\", \"-framerate\", \"10\",\n        \"-i\", \"desktop\", \"-y\", f\"artifacts\u002Fvideos\u002F{name}.mp4\"\n    ], stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)\n\ndef stop_recording(proc):\n    proc.stdin.write(b\"q\"); proc.stdin.flush(); proc.wait(timeout=10)\n```\n\n## Per-Step Trace (opt-in)\n\nThe default failure screenshot is often too thin for diagnosing flaky tests. The step-level trace below is **off by default** — enable it only when reproducing a flaky case.\n\n### Enable\n\n```bash\nE2E_TRACE=1 pytest tests\u002Ftest_login.py -v\n# Include typed text in the JSONL log (DO NOT use on tests that type credentials\u002FPII):\nE2E_TRACE=1 E2E_TRACE_INCLUDE_TEXT=1 pytest ...\n```\n\n### Patch into BasePage\n\n```python\nimport os, json, time\nTRACE_ENABLED      = os.environ.get(\"E2E_TRACE\") == \"1\"\nTRACE_INCLUDE_TEXT = os.environ.get(\"E2E_TRACE_INCLUDE_TEXT\") == \"1\"\n\nclass BasePage:\n    _step = 0\n\n    def _trace(self, action, spec=None, text=None):\n        if not TRACE_ENABLED:\n            return\n        BasePage._step += 1\n        idx = f\"{BasePage._step:03d}\"\n        os.makedirs(ARTIFACT_DIR, exist_ok=True)\n        try:\n            self.window.capture_as_image().save(\n                os.path.join(ARTIFACT_DIR, f\"step_{idx}_{action}.png\"))\n        except Exception:\n            pass  # capture failure must not break the test\n        rec = {\n            \"ts\": time.time(), \"step\": BasePage._step, \"action\": action,\n            \"locator\": getattr(spec, \"criteria\", None),\n            \"text\": text if TRACE_INCLUDE_TEXT else (\"\u003Credacted>\" if text else None),\n        }\n        with open(os.path.join(ARTIFACT_DIR, \"trace.jsonl\"), \"a\") as f:\n            f.write(json.dumps(rec) + \"\\n\")\n\n    def click(self, spec):\n        self.wait_visible(spec); self._trace(\"click_before\", spec)\n        spec.click_input();      self._trace(\"click_after\",  spec)\n\n    def type_text(self, spec, text):\n        self.wait_visible(spec); self._trace(\"type_before\", spec, text)\n        # ... existing set_edit_text \u002F keyboard fallback ...\n        self._trace(\"type_after\", spec)\n```\n\n### Caveats\n\n- **PII \u002F credentials**: `type_text` content is `\u003Credacted>` by default. Never set `E2E_TRACE_INCLUDE_TEXT=1` on login or payment flows.\n- **Overhead**: ~50–200ms per action + one PNG per step on disk. Don't enable on the default CI matrix — only on a dedicated flake-repro job.\n- **Artifact bloat**: a long flow produces tens of MB; tune `retention-days` accordingly.\n- **Parallel\u002Frerun hygiene**: this simple example appends to `trace.jsonl` and uses a class-level counter. Clear the artifact directory before reruns, and use per-worker artifact dirs for parallel tests.\n- **Coverage gap**: actions performed outside `BasePage` (raw `pywinauto` calls in test code) are not traced.\n\n## Flaky Test Handling\n\n```python\n# Quarantine — equivalent to Playwright's test.fixme()\n@pytest.mark.skip(reason=\"Flaky: animation race on slow CI. Issue #42\")\ndef test_animated_transition(self, app): ...\n\n# Skip in CI only\n@pytest.mark.skipif(os.environ.get(\"CI\") == \"true\", reason=\"Flaky in CI #43\")\ndef test_heavy_load(self, app): ...\n```\n\nCommon causes and fixes:\n\n| Cause | Fix |\n|-------|-----|\n| Control not ready | Replace `time.sleep` with `wait_visible` |\n| Window not focused | Add `win.set_focus()` before interactions |\n| Animation in progress | `wait_until(lambda: not loading_indicator.exists())` |\n| Dialog timing | `wait_window(title, timeout=15)` |\n| CI display not ready | Set `DISPLAY` or use virtual desktop in CI |\n| `set_edit_text` raises NotImplementedError | UIA ValuePattern missing (common on Qt 5.x) — `BasePage.type_text` already falls back to `keyboard.send_keys` |\n| Control exists but `wait_visible` times out | Window minimised or off-screen — call `win.restore()` + `win.set_focus()` before waiting |\n\n## Test Isolation & Sandbox\n\nThree tiers of isolation — use the lightest tier that satisfies your needs.\n\n### Tier 1 — Filesystem Isolation (default, always use)\n\nEach test gets its own `APPDATA` \u002F `LOCALAPPDATA` \u002F `TEMP` via `subprocess.Popen` and `Application.connect()`. pytest's `tmp_path` fixture handles cleanup automatically.\n\n```python\n# conftest.py — replace the basic `app` fixture with this\nimport os, subprocess, pytest\nfrom pywinauto import Application\nfrom config import APP_PATH, APP_ARGS, APP_TITLE, LAUNCH_TIMEOUT, ACTION_TIMEOUT, ARTIFACT_DIR\n\n@pytest.fixture(scope=\"function\")\ndef app(request, tmp_path):\n    \"\"\"Fresh process + isolated user-data dirs per test.\"\"\"\n    if not APP_PATH:\n        pytest.exit(\"APP_PATH not set\", returncode=1)\n\n    # Redirect all per-user storage to an isolated tmp directory\n    sandbox_env = os.environ.copy()\n    sandbox_env[\"QT_ACCESSIBILITY\"]  = \"1\"\n    sandbox_env[\"APPDATA\"]           = str(tmp_path \u002F \"AppData\" \u002F \"Roaming\")\n    sandbox_env[\"LOCALAPPDATA\"]      = str(tmp_path \u002F \"AppData\" \u002F \"Local\")\n    sandbox_env[\"TEMP\"] = sandbox_env[\"TMP\"] = str(tmp_path \u002F \"Temp\")\n    for p in (sandbox_env[\"APPDATA\"], sandbox_env[\"LOCALAPPDATA\"], sandbox_env[\"TEMP\"]):\n        os.makedirs(p, exist_ok=True)\n\n    if not APP_TITLE:\n        pytest.exit(\"APP_TITLE environment variable is not set\", returncode=1)\n\n    # shlex.split handles quoted args with spaces; plain split() breaks on them\n    import shlex\n    # Launch via subprocess so we can pass env; connect pywinauto by PID\n    proc = subprocess.Popen(\n        [APP_PATH] + shlex.split(APP_ARGS),\n        env=sandbox_env,\n    )\n    pw_app = Application(backend=\"uia\").connect(process=proc.pid, timeout=LAUNCH_TIMEOUT)\n    win    = pw_app.window(title=APP_TITLE)\n    win.wait(\"visible\", timeout=LAUNCH_TIMEOUT)\n    yield win\n\n    if getattr(getattr(request.node, \"rep_call\", None), \"failed\", False):\n        os.makedirs(ARTIFACT_DIR, exist_ok=True)\n        try:\n            win.capture_as_image().save(\n                os.path.join(ARTIFACT_DIR, f\"FAIL_{request.node.name}.png\")\n            )\n        except Exception:\n            pass\n    try:\n        win.close()\n        proc.wait(timeout=5)\n    except Exception:\n        proc.kill()\n    # tmp_path is cleaned up automatically by pytest\n\n@pytest.hookimpl(tryfirst=True, hookwrapper=True)\ndef pytest_runtest_makereport(item, call):\n    outcome = yield\n    setattr(item, f\"rep_{outcome.get_result().when}\", outcome.get_result())\n```\n\n### Tier 2 — Windows Job Object (optional: process-lifetime containment)\n\nAttach the process to a Job Object so it is **automatically terminated** when\nthe test fixture's job handle is GC'd. Also prevents the app from spawning\nchild processes that escape fixture cleanup.\n\n> **Scope of isolation:** Job Objects do NOT virtualize filesystem access or\n> block network traffic. File-write and network isolation require AppContainer,\n> Windows Firewall rules, or Tier 3 (Windows Sandbox). Use Tier 2 only for\n> process-lifetime and child-process containment.\n\nRequires no extra dependencies.\n\n```python\nimport ctypes, ctypes.wintypes as wt\n\ndef restrict_process(pid: int):\n    \"\"\"\n    Attach the process to a Job Object that prevents it from:\n    - spawning processes outside the job (LIMIT_KILL_ON_JOB_CLOSE)\n    Does NOT block network — use Windows Firewall rules for that.\n    \"\"\"\n    JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x00002000\n    # Minimal rights: SET_QUOTA (0x0100) | TERMINATE (0x0001)\n    PROCESS_SET_QUOTA_AND_TERMINATE    = 0x0101\n\n    kernel32 = ctypes.windll.kernel32\n    job   = kernel32.CreateJobObjectW(None, None)\n    hproc = kernel32.OpenProcess(PROCESS_SET_QUOTA_AND_TERMINATE, False, pid)\n\n    # Correct struct layout — LimitFlags is at offset +16, not +44\n    class JOBOBJECT_BASIC_LIMIT_INFORMATION(ctypes.Structure):\n        _fields_ = [\n            (\"PerProcessUserTimeLimit\", wt.LARGE_INTEGER),\n            (\"PerJobUserTimeLimit\",     wt.LARGE_INTEGER),\n            (\"LimitFlags\",             wt.DWORD),\n            (\"MinimumWorkingSetSize\",   ctypes.c_size_t),\n            (\"MaximumWorkingSetSize\",   ctypes.c_size_t),\n            (\"ActiveProcessLimit\",      wt.DWORD),\n            (\"Affinity\",               ctypes.c_size_t),\n            (\"PriorityClass\",          wt.DWORD),\n            (\"SchedulingClass\",        wt.DWORD),\n        ]\n\n    info = JOBOBJECT_BASIC_LIMIT_INFORMATION()\n    info.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE\n    ok = kernel32.SetInformationJobObject(job, 2, ctypes.byref(info), ctypes.sizeof(info))\n    if not ok:\n        raise ctypes.WinError()\n    kernel32.AssignProcessToJobObject(job, hproc)\n    kernel32.CloseHandle(hproc)\n    return job  # keep alive — job closes (kills proc) when GC'd\n\n# After proc = subprocess.Popen(...):  job = restrict_process(proc.pid)\n```\n\n### Tier 3 — Windows Sandbox (CI full-OS isolation)\n\nWhen you need a clean Windows image per run (no leftover registry keys, no\nshared GPU state, true isolation), run the **entire test suite** inside\n[Windows Sandbox](https:\u002F\u002Flearn.microsoft.com\u002Fwindows\u002Fsecurity\u002Fapplication-security\u002Fapplication-isolation\u002Fwindows-sandbox\u002Fwindows-sandbox-overview).\n\n**Requirement:** Windows 10\u002F11 Pro or Enterprise, Virtualization enabled.\n\nCreate `e2e-sandbox.wsb` in your project root:\n\n```xml\n\u003CConfiguration>\n  \u003CMappedFolders>\n    \u003C!-- App binary (read-only) -->\n    \u003CMappedFolder>\n      \u003CHostFolder>C:\\path\\to\\your\\build\\Release\u003C\u002FHostFolder>\n      \u003CSandboxFolder>C:\\app\u003C\u002FSandboxFolder>\n      \u003CReadOnly>true\u003C\u002FReadOnly>\n    \u003C\u002FMappedFolder>\n    \u003C!-- Test suite (read-write for artifacts) -->\n    \u003CMappedFolder>\n      \u003CHostFolder>C:\\path\\to\\your\\e2e_test\u003C\u002FHostFolder>\n      \u003CSandboxFolder>C:\\e2e_test\u003C\u002FSandboxFolder>\n      \u003CReadOnly>false\u003C\u002FReadOnly>\n    \u003C\u002FMappedFolder>\n  \u003C\u002FMappedFolders>\n  \u003CLogonCommand>\n    \u003C!--\n      Windows Sandbox starts with no Python. Install it silently first,\n      then install deps and run tests. Artifacts are written back to the\n      host via the MappedFolder above.\n    -->\n    \u003CCommand>powershell -Command \"\n      winget install --id Python.Python.3.11 --silent --accept-package-agreements;\n      $env:PATH += ';' + $env:LOCALAPPDATA + '\\Programs\\Python\\Python311\\Scripts';\n      cd C:\\e2e_test;\n      pip install -r requirements.txt;\n      pytest tests\\ -v\n    \"\u003C\u002FCommand>\n  \u003C\u002FLogonCommand>\n\u003C\u002FConfiguration>\n```\n\nLaunch: `WindowsSandbox.exe e2e-sandbox.wsb`\n\n> pywinauto and the app both run **inside** the sandbox (same session required).\n> Artifacts are written back to the host via the mapped folder.\n\n### Tier comparison\n\n| Tier | Isolation | Setup cost | Works on CI | Use when |\n|------|-----------|-----------|-------------|----------|\n| 1 — `tmp_path` env redirect | Filesystem | Zero | Always | Default for all tests |\n| 2 — Job Object | Process tree | Low | Always | Prevent child-process escape |\n| 3 — Windows Sandbox | Full OS | Medium | Needs Pro\u002FEnterprise image | Nightly clean-room runs |\n\n### Prevent hanging tests\n\nAdd `pytest-timeout` to cap any single test. In `pytest.ini` set `timeout = 60` and `timeout_method = thread`. Note: `thread` method cannot kill Qt app subprocesses on Windows — add `atexit.register(lambda: [p.kill() for p in psutil.Process().children(recursive=True)])` in `conftest.py` to reap orphans.\n\n## CI\u002FCD Integration\n\n```yaml\n# .github\u002Fworkflows\u002Fe2e-desktop.yml\nname: Desktop E2E\non: [push, pull_request]\n\njobs:\n  e2e:\n    runs-on: windows-latest   # real GUI environment, no Xvfb needed\n    steps:\n      - uses: actions\u002Fcheckout@v4\n\n      - uses: actions\u002Fsetup-python@v5\n        with: { python-version: \"3.11\" }\n\n      - name: Install deps\n        run: pip install pywinauto pytest pytest-html Pillow\n\n      - name: Build app\n        run: cmake --build build --config Release  # adjust to your build system\n\n      - name: Run E2E\n        env:\n          APP_PATH: ${{ github.workspace }}\\build\\Release\\MyApp.exe\n          APP_TITLE: \"My Application\"\n          CI: \"true\"\n        run: pytest tests\u002F --html=artifacts\u002Freport.html --self-contained-html --junitxml=artifacts\u002Fresults.xml -v\n\n      - uses: actions\u002Fupload-artifact@v4\n        if: always()\n        with:\n          name: e2e-artifacts\n          path: artifacts\u002F\n          retention-days: 14\n```\n\n## Qt Specific\n\n### Enable UIA in Qt 5.x\n\nQt 5.x accessibility is disabled by default in some builds (especially 5.7–5.14). Set the environment variable **before** launching. Qt 6.x enables accessibility by default — skip this step for Qt 6.\n\n```python\n# conftest.py — add at module top\nimport os\nos.environ[\"QT_ACCESSIBILITY\"] = \"1\"\n```\n\nOr export it in CI:\n\n```yaml\nenv:\n  QT_ACCESSIBILITY: \"1\"\n```\n\n### Add Stable Identifiers to Qt Widgets\n\n```cpp\n\u002F\u002F Preferred: both objectName and accessibleName\nvoid setTestId(QWidget* w, const char* id) {\n    w->setObjectName(id);\n    w->setAccessibleName(id);  \u002F\u002F becomes UIA Name property\n}\n\n\u002F\u002F In your dialog constructor:\nsetTestId(ui->usernameEdit, \"usernameInput\");\nsetTestId(ui->passwordEdit, \"passwordInput\");\nsetTestId(ui->loginButton,  \"btnLogin\");\nsetTestId(ui->errorLabel,   \"lblError\");\n```\n\nCentralise all IDs in a header to avoid typos:\n\n```cpp\n\u002F\u002F test_ids.h\n#define TID_USERNAME   \"usernameInput\"\n#define TID_PASSWORD   \"passwordInput\"\n#define TID_BTN_LOGIN  \"btnLogin\"\n#define TID_LBL_ERROR  \"lblError\"\n```\n\n### Qt-Specific Quirks\n\n**QComboBox** — the dropdown is a separate top-level window:\n\n```python\nfrom pywinauto import Desktop\n\ndef select_combo_item(page, combo_spec, item_text):\n    page.click(combo_spec)\n    # Dropdown appears as a new root-level window\n    # class_name varies by Qt version — verify with Accessibility Insights\n    # Qt 5.x: \"Qt5QWindowIcon\"  |  Qt 6.x: \"Qt6QWindowIcon\" — verify with Accessibility Insights\n    popup = Desktop(backend=\"uia\").window(class_name_re=\"Qt[56]QWindowIcon\")\n    popup.wait(\"visible\", timeout=5)\n    popup.child_window(title=item_text).click_input()\n```\n\n**QMessageBox \u002F QDialog** — also separate top-level windows:\n\n```python\ndlg = page.wait_window(\"Confirm\")          # wait for dialog title\ndlg.child_window(title=\"OK\").click_input() # click button inside it\n```\n\n**QTableWidget \u002F QTableView** — row\u002Fcell access:\n\n```python\ntable = page.by_id(\"tblUsers\").wrapper_object()\ncell  = table.cell(row=0, column=1)\nprint(cell.window_text())\n```\n\n**Self-drawn controls** (`paintEvent`-only, `QGraphicsView`, `QOpenGLWidget`) — UIA cannot see their internals. Use the Fallback section below.\n\n## Fallback: Screenshot Mode\n\nWhen a control is not reachable via UIA (self-drawn, third-party, game engine):\n\n```bash\npip install pyautogui Pillow opencv-python\n```\n\n```python\nimport pyautogui, cv2, numpy as np\nfrom PIL import Image\n\ndef find_image_on_screen(template_path, confidence=0.85):\n    \"\"\"Locate a template image on screen. Returns (x, y) center or None.\"\"\"\n    screen   = np.array(pyautogui.screenshot())\n    template = np.array(Image.open(template_path))\n    result   = cv2.matchTemplate(\n        cv2.cvtColor(screen, cv2.COLOR_RGB2BGR),\n        cv2.cvtColor(template, cv2.COLOR_RGB2BGR),\n        cv2.TM_CCOEFF_NORMED,\n    )\n    _, max_val, _, max_loc = cv2.minMaxLoc(result)\n    if max_val >= confidence:\n        h, w = template.shape[:2]\n        return max_loc[0] + w \u002F\u002F 2, max_loc[1] + h \u002F\u002F 2\n    return None\n\ndef click_image(template_path, confidence=0.85):\n    pos = find_image_on_screen(template_path, confidence)\n    if pos is None:\n        raise RuntimeError(f\"Image not found on screen: {template_path}\")\n    pyautogui.click(*pos)\n```\n\n### DPI \u002F Scaling Rules (screenshot mode only)\n\nScreenshot matching is brutally sensitive to Windows display scaling (100% \u002F 125% \u002F 150%). Three hard rules:\n\n1. **Capture templates at the same scale as the target machine.** Don't try to rescue a mismatch with `PIL.Image.resize` — `cv2.matchTemplate` is very fragile against resampling artefacts.\n2. **Pin the CI display scaling.** On `windows-latest` add a step like `Set-DisplayResolution 1920 1080 -Force` and disable per-monitor DPI scaling, so screenshot dimensions are reproducible.\n3. **Record the scale alongside each artefact.** On capture, write `GetDpiForWindow(hwnd) \u002F 96` to `artifacts\u002F\u003Ctest>\u002Fmetadata.json` — postmortems become obvious instead of guess-work.\n\n> Process-level DPI awareness (`SetProcessDpiAwarenessContext`) **can conflict with Qt's own DPI handling** when the app under test is Qt-based. Prefer \"same-scale templates + CI pin\" over flipping process-wide DPI mode in fixtures.\n\n### Debugging Match Confidence\n\nWhen tuning the `confidence` threshold, the only sane workflow is to **see** where the match landed. The helper below is diagnosis-only — do not call it from test code.\n\n```python\ndef debug_match(template_path, out=\"artifacts\u002Fmatch_debug.png\", confidence=0.85):\n    \"\"\"Diagnosis-only. Draw the best-match rectangle + score back on the current screen.\n\n    NOT for production tests — use when calibrating confidence or chasing false matches.\n    \"\"\"\n    import os, cv2, pyautogui, numpy as np\n    screen = np.array(pyautogui.screenshot())[:, :, ::-1]\n    tpl    = cv2.imread(template_path)\n    if tpl is None:\n        raise RuntimeError(f\"Template unreadable: {template_path}\")\n    res    = cv2.matchTemplate(screen, tpl, cv2.TM_CCOEFF_NORMED)\n    _, mv, _, ml = cv2.minMaxLoc(res)\n    h, w   = tpl.shape[:2]\n    colour = (0, 255, 0) if mv >= confidence else (0, 0, 255)  # green pass \u002F red fail\n    cv2.rectangle(screen, ml, (ml[0]+w, ml[1]+h), colour, 2)\n    cv2.putText(screen, f\"score={mv:.3f} thr={confidence}\",\n                (ml[0], max(20, ml[1]-6)),\n                cv2.FONT_HERSHEY_SIMPLEX, 0.7, colour, 2)\n    os.makedirs(os.path.dirname(out) or \".\", exist_ok=True)\n    cv2.imwrite(out, screen)\n    return mv\n```\n\n**Use sparingly** — image matching breaks on DPI changes, theme switches, and partial occlusion.\nAlways try UIA first; fall back to screenshots only for genuinely unreachable controls.\n\n## Anti-Patterns\n\n```python\n# BAD: fixed sleep\ntime.sleep(3)\npage.click(page.by_id(\"btnSubmit\"))\n\n# GOOD: condition wait\npage.wait_visible(page.by_id(\"btnSubmit\"))\npage.click(page.by_id(\"btnSubmit\"))\n```\n\n```python\n# BAD: brittle class+index locator as primary strategy\npage.by_class(\"Edit\", index=2).type_keys(\"hello\")\n\n# GOOD: AutomationId\npage.by_id(\"usernameInput\").set_edit_text(\"hello\")\n```\n\n```python\n# BAD: assert on pixel coordinates\nassert btn.rectangle().left == 120\n\n# GOOD: assert on content \u002F state\nassert page.get_text(page.by_id(\"lblStatus\")) == \"Logged in\"\nassert page.by_id(\"btnLogout\").is_enabled()\n```\n\n```python\n# BAD: share app instance across all tests (state leaks)\n@pytest.fixture(scope=\"session\")\ndef app(): ...\n\n# GOOD: fresh process per test (or per class at most)\n@pytest.fixture(scope=\"function\")\ndef app(): ...\n```\n\n## Running Tests\n\n```bash\n# All tests\npytest tests\u002F -v\n\n# Smoke only\npytest tests\u002F -m smoke -v\n\n# Specific file\npytest tests\u002Ftest_login.py -v\n\n# With custom app path\nAPP_PATH=\"C:\\build\\Release\\MyApp.exe\" APP_TITLE=\"MyApp\" pytest tests\u002F -v\n\n# Detect flaky tests (repeat each 5 times)\npip install pytest-repeat\npytest tests\u002Ftest_login.py --count=5 -v\n```\n\n## Related Skills\n\n- `e2e-testing` — Playwright E2E for web applications\n- `cpp-testing` — C++ unit\u002Fintegration testing with GoogleTest\n- `cpp-coding-standards` — C++ code style and patterns\n",{"name":5,"origin":24,"description":7},"ECC","main","87afe6ce96220accf50a345dea46784c8c9f210e","YYC3-AI-应用工具\u002FYYC3-AI-应用工具-Everything-claude-code\u002Fskills\u002Fwindows-desktop-e2e",0,"https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base","https:\u002F\u002Fkb.yyc3.top\u002F","https:\u002F\u002Fgithub.com\u002FYYC-Cube","万象归元于云枢 | 深栈智启新纪元","2026-11-10 10:37:32",{"source":8,"skillName":5,"commands":35,"prompt":45,"zipAvailable":46},[36,39,42],{"tool":37,"command":38},"npx","npx skills add YYC-Cube\u002FYYC3-Knowledge-Base --skill windows-desktop-e2e",{"tool":40,"command":41},"bunx","bunx skills add YYC-Cube\u002FYYC3-Knowledge-Base --skill windows-desktop-e2e",{"tool":43,"command":44},"pnpm","pnpm dlx skills add YYC-Cube\u002FYYC3-Knowledge-Base --skill windows-desktop-e2e","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-AI-应用工具\u002FYYC3-AI-应用工具-Everything-claude-code\u002Fskills\u002Fwindows-desktop-e2e\u002FSKILL.md",true,[],[49,56,63,70,77,84],{"skillNo":50,"name":51,"nameZh":6,"description":52,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":53,"categories":54,"keywords":55,"publishedAt":19},"01M7CTDWHERCXPQCP0K03A86AS","vercel-sandbox","Run agent-browser + Chrome inside Vercel Sandbox microVMs for browser automation from any Vercel-deployed app. Use when the user needs browser automation in a Vercel app (Next.js, SvelteKit, Nuxt, Remix, Astro, etc.), wants to run headless Chrome without binary size limits, needs persistent browser sessions across commands, or wants ephemeral isolated browser environments. Triggers include \"Vercel Sandbox browser\", \"microVM Chrome\", \"agent-browser in sandbox\", \"browser automation on Vercel\", or any task requiring Chrome in a Vercel Sandbox.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Fvercel-sandbox\u002FSKILL.md",[],[],{"skillNo":57,"name":58,"nameZh":6,"description":59,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":60,"categories":61,"keywords":62,"publishedAt":19},"01M7CTD8D2BNJY54S65M47HEJA","slack","Interact with Slack workspaces using browser automation. Use when the user needs to check unread channels, navigate Slack, send messages, extract data, find information, search conversations, or automate any Slack task. Triggers include \"check my Slack\", \"what channels have unreads\", \"send a message to\", \"search Slack for\", \"extract from Slack\", \"find who said\", or any task requiring programmatic Slack interaction.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Fslack\u002FSKILL.md",[],[],{"skillNo":64,"name":65,"nameZh":6,"description":66,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":67,"categories":68,"keywords":69,"publishedAt":19},"01M7CTCSSB8ZP3Q58C3YZDZK1W","electron","Automate Electron desktop apps (VS Code, Slack, Discord, Figma, Notion, Spotify, etc.) using agent-browser via Chrome DevTools Protocol. Use when the user needs to interact with an Electron app, automate a desktop app, connect to a running app, control a native app, or test an Electron application. Triggers include \"automate Slack app\", \"control VS Code\", \"interact with Discord app\", \"test this Electron app\", \"connect to desktop app\", or any task requiring automation of a native Electron application.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Felectron\u002FSKILL.md",[],[],{"skillNo":71,"name":72,"nameZh":6,"description":73,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":74,"categories":75,"keywords":76,"publishedAt":19},"01M7CTCBJY76688V4DCZGWFHGQ","dogfood","Systematically explore and test a web application to find bugs, UX issues, and other problems. Use when asked to \"dogfood\", \"QA\", \"exploratory test\", \"find issues\", \"bug hunt\", \"test this app\u002Fsite\u002Fplatform\", or review the quality of a web application. Produces a structured report with full reproduction evidence -- step-by-step screenshots, repro videos, and detailed repro steps for every issue -- so findings can be handed directly to the responsible teams.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Fdogfood\u002FSKILL.md",[],[],{"skillNo":78,"name":79,"nameZh":6,"description":80,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":81,"categories":82,"keywords":83,"publishedAt":19},"01M7CTC4H0FFGVEAQR9PA4GA1A","agent-browser","Browser automation CLI for AI agents. Use when the user needs to interact with websites, including navigating pages, filling forms, clicking buttons, taking screenshots, extracting data, testing web apps, or automating any browser task. Triggers include requests to \"open a website\", \"fill out a form\", \"click a button\", \"take a screenshot\", \"scrape data from a page\", \"test this web app\", \"login to a site\", \"automate browser actions\", or any task requiring programmatic web interaction.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Fagent-browser\u002FSKILL.md",[],[],{"skillNo":85,"name":86,"nameZh":6,"description":87,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":88,"categories":89,"keywords":90,"publishedAt":19},"01M7CTBKVFYBG78FDSABSDJTTQ","shadcn","Manages shadcn components and projects — adding, searching, fixing, debugging, styling, and composing UI, including chat interfaces. Provides project context, component docs, and usage examples. Applies when working with shadcn\u002Fui, component registries, presets, --preset codes, or any project with a components.json file. Also triggers for \"shadcn init\", \"create an app with --preset\", \"switch to --preset\", and for building a design system or applying a DESIGN.md or brand spec to shadcn\u002Fui.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-UI-界面组件\u002FYYC3-UI-界面组件-ui\u002Fskills\u002Fshadcn\u002FSKILL.md",[],[]]