[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7F135KPK2TBTQEGEMMHFPCD":3,"skill-same:01M7F135KPK2TBTQEGEMMHFPCD":46},{"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":26,"commitSha":27,"skillDirectory":28,"forksCount":14,"repositoryHtmlUrl":29,"repositoryHomepageUrl":29,"ownerHtmlUrl":30,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":31,"install":32,"resources":45},"01M7F135KPK2TBTQEGEMMHFPCD","windows-desktop-e2e",null,"E2E testing for Windows native desktop apps (WPF, WinForms, Win32\u002FMFC, Qt) using pywinauto and Windows UI Automation. Use when writing E2E tests for a Windows native desktop app with pywinauto or UI Automation.","Mr-Nobody-Anonymous\u002FAll-skills","Mr-Nobody-Anonymous","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F184253119?v=4","01M7AEXFJHKTYQW5R0ZCQQTWFV","anonymous","01M7C00M3GQR4QKP9GZA42GFAK",0,"MIT","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fecc\u002Fwindows-desktop-e2e\u002FSKILL.md",[],[],"2026-11-16 10:05:34",false,"---\nname: windows-desktop-e2e\ndescription: E2E testing for Windows native desktop apps (WPF, WinForms, Win32\u002FMFC, Qt) using pywinauto and Windows UI Automation. Use when writing E2E tests for a Windows native desktop app with pywinauto or UI Automation.\nmetadata:\n  origin: 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 | 5\u002F5 | Excellent | `x:Name` maps directly to AutomationId |\n| WinForms | 4\u002F5 | Good | `AccessibleName` = AutomationId |\n| UWP \u002F WinUI 3 | 5\u002F5 | Excellent | Full Microsoft support |\n| Qt 6.x | 5\u002F5 | Excellent | Accessibility enabled by default; class names change to `Qt6*` |\n| Qt 5.15+ | 4\u002F5 | Good | Improved Accessibility module |\n| Qt 5.7–5.14 | 3\u002F5 | Fair | Needs `QT_ACCESSIBILITY=1`; objectName manual |\n| Win32 \u002F MFC | 3\u002F5 | 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 | 5\u002F5 | Excellent | `x:Name` maps directly to AutomationId |\n| WinForms | 4\u002F5 | Good | `AccessibleName` = AutomationId |\n| UWP \u002F WinUI 3 | 5\u002F5 | Excellent | Full Microsoft support |\n| Qt 6.x | 5\u002F5 | Excellent | Accessibility enabled by default; class names change to `Qt6*` |\n| Qt 5.15+ | 4\u002F5 | Good | Improved Accessibility module |\n| Qt 5.7–5.14 | 3\u002F5 | Fair | Needs `QT_ACCESSIBILITY=1`; objectName manual |\n| Win32 \u002F MFC | 3\u002F5 | 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,"metadata":24,"description":7},{"origin":25},"ECC","main","2d1750717747097b602acf30bd09a7cbd4b4c6ea","awesome_skills\u002Fecc\u002Fwindows-desktop-e2e","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous","2026-11-09 11:45:36",{"source":8,"skillName":5,"commands":33,"prompt":43,"zipAvailable":44},[34,37,40],{"tool":35,"command":36},"npx","npx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill windows-desktop-e2e",{"tool":38,"command":39},"bunx","bunx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill windows-desktop-e2e",{"tool":41,"command":42},"pnpm","pnpm dlx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill windows-desktop-e2e","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fecc\u002Fwindows-desktop-e2e\u002FSKILL.md",true,[],[47,54,61,68,75,82],{"skillNo":48,"name":49,"nameZh":6,"description":50,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":51,"categories":52,"keywords":53,"publishedAt":19},"01M7FFFZPC2025JQQHPHDX154J","dei-assessment","Assess diversity, equity, and inclusion with metrics. TRIGGERS - Use when user needs help with dei-assessment related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fdei-assessment\u002FSKILL.md",[],[],{"skillNo":55,"name":56,"nameZh":6,"description":57,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":58,"categories":59,"keywords":60,"publishedAt":19},"01M7FFFWN8H4WA7A6Y398QKB6J","dei-action-plan","Create DEI action plans with goals and initiatives. TRIGGERS - Use when user needs help with dei-action-plan related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fdei-action-plan\u002FSKILL.md",[],[],{"skillNo":62,"name":63,"nameZh":6,"description":64,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":65,"categories":66,"keywords":67,"publishedAt":19},"01M7FFFSHTM0QZRVZ2NRJTJ0PY","culture-fit-assessment","Design culture add assessment processes. TRIGGERS - Use when user needs help with culture-fit-assessment related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fculture-fit-assessment\u002FSKILL.md",[],[],{"skillNo":69,"name":70,"nameZh":6,"description":71,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":72,"categories":73,"keywords":74,"publishedAt":19},"01M7FFFMA12RKEQA38KHJSXXPS","cowork-to-code-bridge","Use an already-installed, independently verified cowork-to-code bridge to run narrowly approved actions on the user's own macOS, Linux, or WSL2 machine through a local file queue.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fcowork-to-code-bridge\u002FSKILL.md",[],[],{"skillNo":76,"name":77,"nameZh":6,"description":78,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":79,"categories":80,"keywords":81,"publishedAt":19},"01M7FFFH1F6M8YRGW5V487GH1K","counter-offer-response","Draft counter-offer responses for retention. TRIGGERS - Use when user needs help with counter-offer-response related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fcounter-offer-response\u002FSKILL.md",[],[],{"skillNo":83,"name":84,"nameZh":6,"description":85,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":86,"categories":87,"keywords":88,"publishedAt":19},"01M7FFFDGEHV8Y7J9N40HZXW52","continuous-feedback-system","Design continuous feedback systems. TRIGGERS - Use when user needs help with continuous-feedback-system related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fcontinuous-feedback-system\u002FSKILL.md",[],[]]