wintestkit 0.1.1rc1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. wintestkit/__init__.py +141 -0
  2. wintestkit/__main__.py +5 -0
  3. wintestkit/app.py +264 -0
  4. wintestkit/artifacts.py +194 -0
  5. wintestkit/cli.py +136 -0
  6. wintestkit/commands/__init__.py +6 -0
  7. wintestkit/commands/check.py +61 -0
  8. wintestkit/commands/common.py +80 -0
  9. wintestkit/commands/discover.py +78 -0
  10. wintestkit/commands/doctor.py +49 -0
  11. wintestkit/commands/highlight.py +82 -0
  12. wintestkit/commands/import_namemapping.py +34 -0
  13. wintestkit/commands/init.py +124 -0
  14. wintestkit/commands/inspect.py +126 -0
  15. wintestkit/commands/report.py +42 -0
  16. wintestkit/commands/run.py +126 -0
  17. wintestkit/commands/serve.py +17 -0
  18. wintestkit/commands/spy.py +59 -0
  19. wintestkit/commands/unused.py +121 -0
  20. wintestkit/config.py +462 -0
  21. wintestkit/controls.py +231 -0
  22. wintestkit/coverage.py +445 -0
  23. wintestkit/discovery.py +1229 -0
  24. wintestkit/doctor.py +392 -0
  25. wintestkit/engine/__init__.py +1 -0
  26. wintestkit/engine/actions.py +496 -0
  27. wintestkit/engine/diagnose.py +468 -0
  28. wintestkit/engine/locator.py +405 -0
  29. wintestkit/engine/overlay.py +266 -0
  30. wintestkit/engine/properties.py +327 -0
  31. wintestkit/engine/query.py +87 -0
  32. wintestkit/engine/relocate.py +150 -0
  33. wintestkit/engine/resolve.py +218 -0
  34. wintestkit/engine/spy.py +228 -0
  35. wintestkit/engine/suggest.py +303 -0
  36. wintestkit/engine/treedump.py +137 -0
  37. wintestkit/engine/waits.py +139 -0
  38. wintestkit/errors.py +117 -0
  39. wintestkit/events.py +120 -0
  40. wintestkit/expect.py +348 -0
  41. wintestkit/model.py +1433 -0
  42. wintestkit/name_mapping.py +113 -0
  43. wintestkit/object_previews.py +345 -0
  44. wintestkit/protocol.py +3 -0
  45. wintestkit/py.typed +0 -0
  46. wintestkit/pytest_plugin.py +713 -0
  47. wintestkit/replay.py +160 -0
  48. wintestkit/report/__init__.py +1 -0
  49. wintestkit/report/html.py +48 -0
  50. wintestkit/report/results.py +139 -0
  51. wintestkit/report/template.html +677 -0
  52. wintestkit/runtime.py +322 -0
  53. wintestkit/scaffold/__init__.py +1 -0
  54. wintestkit/scaffold/flow_main.py.tmpl +13 -0
  55. wintestkit/scaffold/main.py.tmpl +8 -0
  56. wintestkit/scaffold/pytest.toml.tmpl +3 -0
  57. wintestkit/scaffold/skills/wintestkit-tests/SKILL.md +294 -0
  58. wintestkit/scaffold/skills/wintestkit-tests/references/api.md +119 -0
  59. wintestkit/scaffold/skills/wintestkit-tests/references/fixing-breakages.md +61 -0
  60. wintestkit/scaffold/skills/wintestkit-tests/references/migration-from-testcomplete.md +78 -0
  61. wintestkit/scaffold/test_smoke.py.tmpl +8 -0
  62. wintestkit/server.py +726 -0
  63. wintestkit/targets.py +551 -0
  64. wintestkit/uia/__init__.py +5 -0
  65. wintestkit/uia/com.py +188 -0
  66. wintestkit/uia/constants.py +242 -0
  67. wintestkit/uia/dpi.py +42 -0
  68. wintestkit/uia/element.py +479 -0
  69. wintestkit/uia/input.py +251 -0
  70. wintestkit/uia/patterns.py +302 -0
  71. wintestkit/uia/png.py +32 -0
  72. wintestkit/uia/screenshot.py +276 -0
  73. wintestkit/uia/webp.py +16 -0
  74. wintestkit/uia/win32.py +629 -0
  75. wintestkit-0.1.1rc1.dist-info/METADATA +130 -0
  76. wintestkit-0.1.1rc1.dist-info/RECORD +79 -0
  77. wintestkit-0.1.1rc1.dist-info/WHEEL +4 -0
  78. wintestkit-0.1.1rc1.dist-info/entry_points.txt +5 -0
  79. wintestkit-0.1.1rc1.dist-info/licenses/LICENSE +21 -0
wintestkit/__init__.py ADDED
@@ -0,0 +1,141 @@
1
+ """UI test automation for Windows WPF applications."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import importlib
6
+ from typing import TYPE_CHECKING, Any
7
+
8
+ __version__ = "0.1.1rc1"
9
+
10
+ if TYPE_CHECKING:
11
+ from wintestkit import errors as errors
12
+ from wintestkit.app import App as App
13
+ from wintestkit.config import WtkConfig as WtkConfig
14
+ from wintestkit.config import load_config as load_config
15
+ from wintestkit.controls import BoundButton as BoundButton
16
+ from wintestkit.controls import BoundCheckBox as BoundCheckBox
17
+ from wintestkit.controls import BoundComboBox as BoundComboBox
18
+ from wintestkit.controls import BoundDataGrid as BoundDataGrid
19
+ from wintestkit.controls import BoundListBox as BoundListBox
20
+ from wintestkit.controls import BoundListItem as BoundListItem
21
+ from wintestkit.controls import BoundRadioButton as BoundRadioButton
22
+ from wintestkit.controls import BoundTabControl as BoundTabControl
23
+ from wintestkit.controls import BoundText as BoundText
24
+ from wintestkit.controls import BoundTextBox as BoundTextBox
25
+ from wintestkit.controls import BoundTreeView as BoundTreeView
26
+ from wintestkit.controls import Button as Button
27
+ from wintestkit.controls import CheckBox as CheckBox
28
+ from wintestkit.controls import ComboBox as ComboBox
29
+ from wintestkit.controls import DataGrid as DataGrid
30
+ from wintestkit.controls import ListBox as ListBox
31
+ from wintestkit.controls import ListItem as ListItem
32
+ from wintestkit.controls import RadioButton as RadioButton
33
+ from wintestkit.controls import TabControl as TabControl
34
+ from wintestkit.controls import Text as Text
35
+ from wintestkit.controls import TextBox as TextBox
36
+ from wintestkit.controls import TreeView as TreeView
37
+ from wintestkit.expect import expect as expect
38
+ from wintestkit.model import BoundControl as BoundControl
39
+ from wintestkit.model import BoundElement as BoundElement
40
+ from wintestkit.model import BoundElements as BoundElements
41
+ from wintestkit.model import BoundWindow as BoundWindow
42
+ from wintestkit.model import Element as Element
43
+ from wintestkit.model import Elements as Elements
44
+ from wintestkit.model import Page as Page
45
+ from wintestkit.model import PageObject as PageObject
46
+ from wintestkit.model import Window as Window
47
+
48
+ __all__ = [
49
+ "App",
50
+ "BoundButton",
51
+ "BoundCheckBox",
52
+ "BoundComboBox",
53
+ "BoundControl",
54
+ "BoundDataGrid",
55
+ "BoundElement",
56
+ "BoundElements",
57
+ "BoundListBox",
58
+ "BoundListItem",
59
+ "BoundRadioButton",
60
+ "BoundTabControl",
61
+ "BoundText",
62
+ "BoundTextBox",
63
+ "BoundTreeView",
64
+ "BoundWindow",
65
+ "Button",
66
+ "CheckBox",
67
+ "ComboBox",
68
+ "DataGrid",
69
+ "Element",
70
+ "Elements",
71
+ "ListBox",
72
+ "ListItem",
73
+ "Page",
74
+ "PageObject",
75
+ "RadioButton",
76
+ "TabControl",
77
+ "Text",
78
+ "TextBox",
79
+ "TreeView",
80
+ "Window",
81
+ "WtkConfig",
82
+ "__version__",
83
+ "errors",
84
+ "expect",
85
+ "load_config",
86
+ ]
87
+
88
+ # Public names are imported lazily so that merely loading the pytest plugin (which happens in
89
+ # every pytest run once wintestkit is installed) does not initialise COM or import UI Automation.
90
+ _LAZY: dict[str, tuple[str, str]] = {
91
+ "App": ("wintestkit.app", "App"),
92
+ "BoundButton": ("wintestkit.controls", "BoundButton"),
93
+ "BoundCheckBox": ("wintestkit.controls", "BoundCheckBox"),
94
+ "BoundComboBox": ("wintestkit.controls", "BoundComboBox"),
95
+ "BoundDataGrid": ("wintestkit.controls", "BoundDataGrid"),
96
+ "BoundListBox": ("wintestkit.controls", "BoundListBox"),
97
+ "BoundListItem": ("wintestkit.controls", "BoundListItem"),
98
+ "BoundRadioButton": ("wintestkit.controls", "BoundRadioButton"),
99
+ "BoundTabControl": ("wintestkit.controls", "BoundTabControl"),
100
+ "BoundText": ("wintestkit.controls", "BoundText"),
101
+ "BoundTextBox": ("wintestkit.controls", "BoundTextBox"),
102
+ "BoundTreeView": ("wintestkit.controls", "BoundTreeView"),
103
+ "Button": ("wintestkit.controls", "Button"),
104
+ "CheckBox": ("wintestkit.controls", "CheckBox"),
105
+ "ComboBox": ("wintestkit.controls", "ComboBox"),
106
+ "DataGrid": ("wintestkit.controls", "DataGrid"),
107
+ "ListBox": ("wintestkit.controls", "ListBox"),
108
+ "ListItem": ("wintestkit.controls", "ListItem"),
109
+ "RadioButton": ("wintestkit.controls", "RadioButton"),
110
+ "TabControl": ("wintestkit.controls", "TabControl"),
111
+ "Text": ("wintestkit.controls", "Text"),
112
+ "TextBox": ("wintestkit.controls", "TextBox"),
113
+ "TreeView": ("wintestkit.controls", "TreeView"),
114
+ "BoundControl": ("wintestkit.model", "BoundControl"),
115
+ "BoundElement": ("wintestkit.model", "BoundElement"),
116
+ "BoundElements": ("wintestkit.model", "BoundElements"),
117
+ "BoundWindow": ("wintestkit.model", "BoundWindow"),
118
+ "Element": ("wintestkit.model", "Element"),
119
+ "Elements": ("wintestkit.model", "Elements"),
120
+ "Page": ("wintestkit.model", "Page"),
121
+ "PageObject": ("wintestkit.model", "PageObject"),
122
+ "Window": ("wintestkit.model", "Window"),
123
+ "WtkConfig": ("wintestkit.config", "WtkConfig"),
124
+ "expect": ("wintestkit.expect", "expect"),
125
+ "load_config": ("wintestkit.config", "load_config"),
126
+ }
127
+
128
+
129
+ def __getattr__(name: str) -> Any:
130
+ if name == "errors":
131
+ return importlib.import_module("wintestkit.errors")
132
+ target = _LAZY.get(name)
133
+ if target is None:
134
+ raise AttributeError(f"module 'wintestkit' has no attribute {name!r}")
135
+ value = getattr(importlib.import_module(target[0]), target[1])
136
+ globals()[name] = value
137
+ return value
138
+
139
+
140
+ def __dir__() -> list[str]:
141
+ return sorted(__all__)
wintestkit/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ """Run the WinTestKit command-line interface."""
2
+
3
+ from wintestkit.cli import main
4
+
5
+ raise SystemExit(main())
wintestkit/app.py ADDED
@@ -0,0 +1,264 @@
1
+ """The application under test: launching, attaching, locating windows and closing."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import os
7
+ import subprocess
8
+ import time
9
+ from collections.abc import Callable, Mapping, Sequence
10
+ from pathlib import Path
11
+ from types import TracebackType
12
+ from typing import Any
13
+
14
+ from wintestkit.engine.diagnose import diagnose_window
15
+ from wintestkit.engine.locator import WindowLocator
16
+ from wintestkit.errors import (
17
+ ActionError,
18
+ AppError,
19
+ AppNotRunningError,
20
+ UIAError,
21
+ WindowNotFoundError,
22
+ )
23
+ from wintestkit.uia import element, patterns, win32
24
+ from wintestkit.uia.element import UIAElement
25
+
26
+ log = logging.getLogger("wintestkit.app")
27
+
28
+ _POLL_INTERVAL = 0.1
29
+
30
+
31
+ class App:
32
+ """A running application under test: the set of processes sharing an exe name.
33
+
34
+ Instances are created with :meth:`launch` or :meth:`attach`.
35
+ """
36
+
37
+ def __init__(
38
+ self,
39
+ process_name: str,
40
+ *,
41
+ launched: bool = False,
42
+ popen: subprocess.Popen[bytes] | None = None,
43
+ pinned_pid: int | None = None,
44
+ by_name: bool = True,
45
+ baseline: frozenset[int] = frozenset(),
46
+ ) -> None:
47
+ __tracebackhide__ = True
48
+ self.process_name = process_name
49
+ self.launched = launched
50
+ self._popen = popen
51
+ self._pinned_pid = pinned_pid
52
+ self._by_name = by_name
53
+ self._baseline = baseline
54
+
55
+ # -- construction ---------------------------------------------------------------------------
56
+
57
+ @classmethod
58
+ def launch(
59
+ cls,
60
+ path: str | Path,
61
+ args: Sequence[str] = (),
62
+ cwd: str | Path | None = None,
63
+ env: Mapping[str, str] | None = None,
64
+ process: str | None = None,
65
+ startup_timeout: float = 30.0,
66
+ progress: Callable[[str], None] | None = None,
67
+ ) -> App:
68
+ """Start ``path`` and wait until it shows a main window.
69
+
70
+ ``progress`` is called with ``"process"`` once the process has started and with
71
+ ``"window"`` once it is waiting for the main window.
72
+ """
73
+ __tracebackhide__ = True
74
+ exe = Path(path)
75
+ if not exe.is_file():
76
+ raise AppError(f"Application executable not found: {exe}")
77
+ process_name = process or exe.name
78
+ baseline = frozenset(win32.pids_by_name(process_name))
79
+ try:
80
+ popen = subprocess.Popen(
81
+ [str(exe), *args],
82
+ cwd=str(cwd) if cwd is not None else None,
83
+ env={**os.environ, **(env or {})},
84
+ creationflags=0,
85
+ )
86
+ except OSError as exc:
87
+ raise AppError(f"Could not start {exe}: {exc}") from exc
88
+ app = cls(process_name, launched=True, popen=popen, baseline=baseline)
89
+ log.info("launched %s (pid %d)", exe, popen.pid)
90
+ if progress is not None:
91
+ progress("process")
92
+ app._wait_for_startup(startup_timeout, progress)
93
+ return app
94
+
95
+ @classmethod
96
+ def attach(cls, process: str | None = None, pid: int | None = None) -> App:
97
+ """Attach to a running application by exe name or process id."""
98
+ __tracebackhide__ = True
99
+ if pid is not None:
100
+ names = {p: name for p, name in win32.list_processes()}
101
+ if pid not in names:
102
+ raise AppNotRunningError(f"No process with id {pid} is running")
103
+ return cls(process or names[pid], pinned_pid=pid, by_name=False)
104
+ if process is None:
105
+ raise ValueError("attach() needs a process name or a pid")
106
+ if not win32.pids_by_name(process):
107
+ raise AppNotRunningError(f"No running process named {process}")
108
+ return cls(process)
109
+
110
+ # -- state ----------------------------------------------------------------------------------
111
+
112
+ @property
113
+ def pids(self) -> list[int]:
114
+ """Live process ids belonging to the application."""
115
+ __tracebackhide__ = True
116
+ found: set[int] = set()
117
+ if self._by_name:
118
+ found.update(set(win32.pids_by_name(self.process_name)) - self._baseline)
119
+ if self._pinned_pid is not None and self._pinned_pid in dict(win32.list_processes()):
120
+ found.add(self._pinned_pid)
121
+ if self._popen is not None and self._popen.poll() is None:
122
+ found.add(self._popen.pid)
123
+ return sorted(found)
124
+
125
+ def is_running(self) -> bool:
126
+ __tracebackhide__ = True
127
+ return bool(self.pids)
128
+
129
+ def top_level_windows(self) -> list[UIAElement]:
130
+ """Visible top-level windows of the application in z-order (owned windows included).
131
+
132
+ Uses ``EnumWindows`` rather than the UIA desktop root, whose children can take seconds to
133
+ enumerate on machines with slow UIA providers.
134
+ """
135
+ __tracebackhide__ = True
136
+ pids = set(self.pids)
137
+ if not pids:
138
+ return []
139
+ windows: list[UIAElement] = []
140
+ for hwnd in win32.top_level_windows(pids):
141
+ try:
142
+ windows.append(element.from_handle(hwnd))
143
+ except UIAError:
144
+ continue # the window closed while enumerating
145
+ return windows
146
+
147
+ def main_window(self, timeout: float = 0.0) -> UIAElement:
148
+ """The first unowned top-level ``Window`` in z-order; polls up to ``timeout`` seconds."""
149
+ __tracebackhide__ = True
150
+ deadline = time.monotonic() + timeout
151
+ while True:
152
+ if not self.is_running():
153
+ raise AppNotRunningError(f"{self.process_name} is not running")
154
+ for hwnd in win32.top_level_windows(set(self.pids)):
155
+ if win32.window_owner(hwnd) != 0:
156
+ continue
157
+ try:
158
+ window = element.from_handle(hwnd)
159
+ if window.control_type == "Window":
160
+ return window
161
+ except UIAError:
162
+ continue
163
+ if time.monotonic() >= deadline:
164
+ break
165
+ time.sleep(_POLL_INTERVAL)
166
+ windows = self.top_level_windows()
167
+ raise WindowNotFoundError(diagnose_window(self, WindowLocator(), [], windows))
168
+
169
+ def wait_for_exit(self, timeout: float) -> bool:
170
+ """Wait until no process of the application is left; ``False`` on timeout."""
171
+ __tracebackhide__ = True
172
+ deadline = time.monotonic() + timeout
173
+ while self.is_running():
174
+ if time.monotonic() >= deadline:
175
+ return False
176
+ time.sleep(0.05)
177
+ return True
178
+
179
+ # -- shutdown -------------------------------------------------------------------------------
180
+
181
+ def close(self, timeout: float = 10.0) -> None:
182
+ """Ask every window to close (owned ones first), then kill if it does not exit."""
183
+ __tracebackhide__ = True
184
+ windows = self.top_level_windows()
185
+ windows.sort(key=lambda w: 0 if win32.window_owner(w.native_window_handle) else 1)
186
+ for window in windows:
187
+ try:
188
+ patterns.window_close(window)
189
+ except (ActionError, UIAError):
190
+ win32.PostMessageW(window.native_window_handle, win32.WM_CLOSE, 0, 0)
191
+ time.sleep(0.05)
192
+ if not self.wait_for_exit(timeout):
193
+ log.warning("%s did not exit within %.1fs; killing it", self.process_name, timeout)
194
+ self.kill()
195
+
196
+ def kill(self) -> None:
197
+ """Forcefully terminate every process of the application (and their children)."""
198
+ __tracebackhide__ = True
199
+ for pid in self.pids:
200
+ subprocess.run(
201
+ ["taskkill", "/PID", str(pid), "/T", "/F"],
202
+ capture_output=True,
203
+ check=False,
204
+ )
205
+ self.wait_for_exit(5.0)
206
+ if self._popen is not None:
207
+ self._popen.poll()
208
+
209
+ def __enter__(self) -> App:
210
+ __tracebackhide__ = True
211
+ return self
212
+
213
+ def __exit__(
214
+ self,
215
+ exc_type: type[BaseException] | None,
216
+ exc: BaseException | None,
217
+ tb: TracebackType | None,
218
+ ) -> None:
219
+ __tracebackhide__ = True
220
+ if self.launched:
221
+ self.close()
222
+
223
+ # -- internals ------------------------------------------------------------------------------
224
+
225
+ def _wait_for_startup(
226
+ self, startup_timeout: float, progress: Callable[[str], None] | None = None
227
+ ) -> None:
228
+ __tracebackhide__ = True
229
+ assert self._popen is not None
230
+ deadline = time.monotonic() + startup_timeout
231
+ self._wait_for_input_idle(self._popen.pid, min(10.0, startup_timeout))
232
+ if progress is not None:
233
+ progress("window")
234
+ while True:
235
+ try:
236
+ self.main_window()
237
+ return
238
+ except AppNotRunningError:
239
+ code = self._popen.poll()
240
+ raise AppError(
241
+ f"{self.process_name} exited before showing a window (exit code {code})"
242
+ ) from None
243
+ except WindowNotFoundError:
244
+ pass
245
+ if time.monotonic() >= deadline:
246
+ self.kill()
247
+ raise AppError(
248
+ f"{self.process_name} did not show a window within {startup_timeout:g}s"
249
+ )
250
+ time.sleep(_POLL_INTERVAL)
251
+
252
+ @staticmethod
253
+ def _wait_for_input_idle(pid: int, timeout: float) -> None:
254
+ __tracebackhide__ = True
255
+ access = win32.PROCESS_QUERY_LIMITED_INFORMATION | win32.SYNCHRONIZE | 0x0400
256
+ handle: Any = win32.OpenProcess(access, False, pid)
257
+ if not handle:
258
+ return
259
+ try:
260
+ win32.WaitForInputIdle(
261
+ handle, int(timeout * 1000)
262
+ ) # fails harmlessly for non-GUI launchers
263
+ finally:
264
+ win32.CloseHandle(handle)
@@ -0,0 +1,194 @@
1
+ """Failure artifacts: screenshots and a UI tree dump captured when a test fails."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import difflib
6
+ import hashlib
7
+ import logging
8
+ import os
9
+ import re
10
+ from dataclasses import dataclass, field
11
+ from pathlib import Path
12
+ from typing import TYPE_CHECKING, Any
13
+
14
+ if TYPE_CHECKING:
15
+ from wintestkit.app import App
16
+
17
+ log = logging.getLogger("wintestkit.artifacts")
18
+
19
+ _MAX_ID_LENGTH = 120
20
+ TREE_MAX_DEPTH = 12
21
+ TREE_MAX_NODES = 3000
22
+ TREE_TEXT_MAX_BYTES = 512 * 1024
23
+ BASELINE_MAX_FILES = 500
24
+
25
+
26
+ def _stable_tree(text: str) -> str:
27
+ """Drop volatile screen coordinates from UI tree text before it is persisted or compared."""
28
+ return re.sub(r" \(-?\d+,-?\d+ \d+x\d+\)", "", text)
29
+
30
+
31
+ @dataclass
32
+ class ArtifactSet:
33
+ """Files captured for one test."""
34
+
35
+ directory: Path
36
+ screenshots: list[Path] = field(default_factory=lambda: [])
37
+ tree_dump: Path | None = None
38
+ tree_diff: Path | None = None
39
+
40
+ def add_screenshot(self, path: Path) -> None:
41
+ if path not in self.screenshots:
42
+ self.screenshots.append(path)
43
+
44
+
45
+ def safe_id(nodeid: str) -> str:
46
+ """A file-system safe, collision-resistant name for a test id."""
47
+ cleaned = re.sub(r"[^A-Za-z0-9._-]", "_", nodeid)[:_MAX_ID_LENGTH]
48
+ return f"{cleaned}-{hashlib.sha1(nodeid.encode('utf-8')).hexdigest()[:8]}"
49
+
50
+
51
+ def artifacts_dir(report_dir: Path, nodeid: str) -> Path:
52
+ return report_dir / "artifacts" / safe_id(nodeid)
53
+
54
+
55
+ def relative_to_report(path: Path, report_dir: Path) -> str:
56
+ """``path`` relative to the report directory with forward slashes."""
57
+ try:
58
+ return path.relative_to(report_dir).as_posix()
59
+ except ValueError:
60
+ return path.as_posix()
61
+
62
+
63
+ def capture_step_screenshot(app: App | None, directory: Path, seq: int) -> Path | None:
64
+ """Screenshot of the application's main window after step ``seq``; never raises."""
65
+ if app is None:
66
+ return None
67
+ try:
68
+ from wintestkit.uia import screenshot
69
+
70
+ image = screenshot.capture_window(app.main_window().native_window_handle)
71
+ if image is None:
72
+ return None
73
+ return screenshot.save(image, directory / "steps" / f"{seq}.webp")
74
+ except Exception:
75
+ log.warning("could not capture the step screenshot", exc_info=True)
76
+ return None
77
+
78
+
79
+ def capture_failure(app: App | None, directory: Path) -> ArtifactSet:
80
+ """Capture ``window.webp``, ``desktop.webp`` and ``tree.txt``.
81
+
82
+ Every artifact is captured independently and best effort: one failing does not stop the
83
+ others, and nothing here ever raises.
84
+ """
85
+ artifacts = ArtifactSet(directory)
86
+ window: Any = None
87
+ if app is not None:
88
+ try:
89
+ window = app.main_window()
90
+ from wintestkit.uia import screenshot
91
+
92
+ image = screenshot.capture_window(window.native_window_handle)
93
+ if image is not None:
94
+ artifacts.add_screenshot(screenshot.save(image, directory / "window.webp"))
95
+ except Exception:
96
+ log.warning("could not capture the window screenshot", exc_info=True)
97
+ try:
98
+ from wintestkit.uia import screenshot
99
+
100
+ artifacts.add_screenshot(
101
+ screenshot.save(screenshot.capture_screen(), directory / "desktop.webp")
102
+ )
103
+ except Exception:
104
+ log.warning("could not capture the desktop screenshot", exc_info=True)
105
+ if window is not None:
106
+ try:
107
+ from wintestkit.engine import treedump
108
+
109
+ text = _stable_tree(
110
+ treedump.dump(
111
+ window,
112
+ max_depth=TREE_MAX_DEPTH,
113
+ max_nodes=TREE_MAX_NODES,
114
+ max_bytes=TREE_TEXT_MAX_BYTES,
115
+ )
116
+ )
117
+ tree_path = directory / "tree.txt"
118
+ tree_path.parent.mkdir(parents=True, exist_ok=True)
119
+ tree_path.write_text(text, encoding="utf-8")
120
+ artifacts.tree_dump = tree_path
121
+ except Exception:
122
+ log.warning("could not dump the UI tree", exc_info=True)
123
+ return artifacts
124
+
125
+
126
+ def capture_tree_text(app: App | None) -> str | None:
127
+ """Return a bounded UI tree for an app, or ``None`` when it is unavailable."""
128
+ if app is None:
129
+ return None
130
+ try:
131
+ from wintestkit.engine import treedump
132
+
133
+ text = treedump.dump(
134
+ app.main_window(),
135
+ max_depth=TREE_MAX_DEPTH,
136
+ max_nodes=TREE_MAX_NODES,
137
+ max_bytes=TREE_TEXT_MAX_BYTES,
138
+ )
139
+ return _stable_tree(text)
140
+ except Exception:
141
+ log.warning("could not capture the UI tree baseline", exc_info=True)
142
+ return None
143
+
144
+
145
+ def write_tree_diff(baseline: Path, current: Path, target: Path) -> bool:
146
+ """Write a bounded unified diff between a previous passing tree and this failure."""
147
+ try:
148
+ with baseline.open("rb") as stream:
149
+ before_bytes = stream.read(TREE_TEXT_MAX_BYTES + 1)
150
+ with current.open("rb") as stream:
151
+ after_bytes = stream.read(TREE_TEXT_MAX_BYTES + 1)
152
+ if len(before_bytes) > TREE_TEXT_MAX_BYTES or len(after_bytes) > TREE_TEXT_MAX_BYTES:
153
+ return False
154
+ before, after = before_bytes.decode("utf-8"), after_bytes.decode("utf-8")
155
+ diff = list(
156
+ difflib.unified_diff(
157
+ before.splitlines(),
158
+ after.splitlines(),
159
+ fromfile="last passing UI tree",
160
+ tofile="failing UI tree",
161
+ lineterm="",
162
+ )
163
+ )
164
+ if not diff:
165
+ return False
166
+ target.parent.mkdir(parents=True, exist_ok=True)
167
+ encoded = ("\n".join(diff[:2000]) + "\n").encode("utf-8")[:TREE_TEXT_MAX_BYTES]
168
+ target.write_bytes(encoded.decode("utf-8", "ignore").encode("utf-8"))
169
+ return True
170
+ except (OSError, UnicodeError):
171
+ return False
172
+
173
+
174
+ def baseline_path(report_dir: Path, target: str, nodeid: str) -> Path:
175
+ """Stable per-target and per-test baseline location; one file is retained per pair."""
176
+ key = hashlib.sha256(f"{target}\0{nodeid}".encode()).hexdigest()
177
+ return report_dir / "ui-tree-baselines" / f"{key}.txt"
178
+
179
+
180
+ def store_tree_text(text: str | None, path: Path) -> None:
181
+ """Best-effort bounded baseline store; artifacts never turn a passing test into a failure."""
182
+ try:
183
+ if text is None:
184
+ return
185
+ encoded = text.encode("utf-8")[:TREE_TEXT_MAX_BYTES].decode("utf-8", "ignore").encode()
186
+ path.parent.mkdir(parents=True, exist_ok=True)
187
+ temporary = path.with_suffix(f".{os.getpid()}.tmp")
188
+ temporary.write_bytes(encoded)
189
+ os.replace(temporary, path)
190
+ files = sorted(path.parent.glob("*.txt"), key=lambda p: p.stat().st_mtime, reverse=True)
191
+ for stale in files[BASELINE_MAX_FILES:]:
192
+ stale.unlink(missing_ok=True)
193
+ except Exception:
194
+ log.warning("could not store the UI tree baseline", exc_info=True)