webcompy-testing 0.0.14__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.
- webcompy_testing/__init__.py +62 -0
- webcompy_testing/_app.py +34 -0
- webcompy_testing/_asgi.py +109 -0
- webcompy_testing/_dom.py +149 -0
- webcompy_testing/_ports.py +1394 -0
- webcompy_testing/_renderer.py +359 -0
- webcompy_testing/_restore.py +62 -0
- webcompy_testing/_scope.py +35 -0
- webcompy_testing/_utils.py +30 -0
- webcompy_testing/browser_runner/__init__.py +25 -0
- webcompy_testing/browser_runner/_runner.py +480 -0
- webcompy_testing/py.typed +0 -0
- webcompy_testing-0.0.14.dist-info/METADATA +45 -0
- webcompy_testing-0.0.14.dist-info/RECORD +16 -0
- webcompy_testing-0.0.14.dist-info/WHEEL +4 -0
- webcompy_testing-0.0.14.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,1394 @@
|
|
|
1
|
+
"""Fake port implementations for browserless testing."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import contextlib
|
|
7
|
+
import logging
|
|
8
|
+
import re
|
|
9
|
+
from collections.abc import Callable, Coroutine
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from typing import Any, Literal
|
|
12
|
+
from unittest.mock import MagicMock
|
|
13
|
+
|
|
14
|
+
from webcompy.ports._async_scheduler import AsyncSchedulerPort
|
|
15
|
+
from webcompy.ports._custom_element import CustomElementBinding, CustomElementPort
|
|
16
|
+
from webcompy.ports._dom import DOMNode
|
|
17
|
+
from webcompy.ports._event_source import EventSourcePort
|
|
18
|
+
from webcompy.ports._fetch import FetchPort, FetchStream, Response
|
|
19
|
+
from webcompy.ports._ffi import FFIPort
|
|
20
|
+
from webcompy.ports._history import HistoryPort
|
|
21
|
+
from webcompy.ports._host import HostPort
|
|
22
|
+
from webcompy.ports._media_query import MediaQueryPort
|
|
23
|
+
from webcompy.ports._transition import TransitionPort, TransitionStyle
|
|
24
|
+
from webcompy.ports._websocket import WebSocketConnection, WebSocketPort
|
|
25
|
+
from webcompy_server.ports._dom import ServerDOMPort
|
|
26
|
+
from webcompy_testing._dom import FakeDOMNode
|
|
27
|
+
|
|
28
|
+
_logger = logging.getLogger(__name__)
|
|
29
|
+
|
|
30
|
+
_MAX_DRAIN_ITERATIONS = 1000
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class _FakeCustomElementBinding(CustomElementBinding):
|
|
34
|
+
def __init__(self, port: FakeCustomElementPort) -> None:
|
|
35
|
+
self._port = port
|
|
36
|
+
|
|
37
|
+
def dispose(self) -> None:
|
|
38
|
+
self._port.disposed_bindings += 1
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class FakeCustomElementPort(CustomElementPort):
|
|
42
|
+
"""Record custom-element registrations and bindings for assertions.
|
|
43
|
+
|
|
44
|
+
Attributes:
|
|
45
|
+
ensure_defined_calls: Recorded ``(name, observed_attributes,
|
|
46
|
+
definition_key)`` definition requests.
|
|
47
|
+
bind_calls: Recorded ``(node, observed_attributes)`` binding
|
|
48
|
+
requests.
|
|
49
|
+
disposed_bindings: Number of bindings disposed so far.
|
|
50
|
+
connected: Connection state returned by
|
|
51
|
+
``is_document_connected``.
|
|
52
|
+
|
|
53
|
+
"""
|
|
54
|
+
|
|
55
|
+
def __init__(self) -> None:
|
|
56
|
+
self.ensure_defined_calls: list[tuple[str, tuple[str, ...], str]] = []
|
|
57
|
+
self.bind_calls: list[tuple[Any, tuple[str, ...]]] = []
|
|
58
|
+
self.disposed_bindings: int = 0
|
|
59
|
+
self.connected: bool = False
|
|
60
|
+
|
|
61
|
+
def ensure_defined(
|
|
62
|
+
self,
|
|
63
|
+
name: str,
|
|
64
|
+
observed_attributes: tuple[str, ...],
|
|
65
|
+
definition_key: str,
|
|
66
|
+
) -> None:
|
|
67
|
+
"""Record a custom-element definition request.
|
|
68
|
+
|
|
69
|
+
Args:
|
|
70
|
+
name: Custom element tag name.
|
|
71
|
+
observed_attributes: Attributes observed by the element.
|
|
72
|
+
definition_key: Deduplication key for the definition.
|
|
73
|
+
|
|
74
|
+
"""
|
|
75
|
+
self.ensure_defined_calls.append((name, observed_attributes, definition_key))
|
|
76
|
+
|
|
77
|
+
def bind(
|
|
78
|
+
self,
|
|
79
|
+
node: Any,
|
|
80
|
+
*,
|
|
81
|
+
observed_attributes: tuple[str, ...],
|
|
82
|
+
on_connected: Any = None,
|
|
83
|
+
on_disconnected: Any = None,
|
|
84
|
+
on_attribute_changed: Any = None,
|
|
85
|
+
) -> CustomElementBinding:
|
|
86
|
+
"""Record a binding and return a disposable handle.
|
|
87
|
+
|
|
88
|
+
Args:
|
|
89
|
+
node: DOM node to bind.
|
|
90
|
+
observed_attributes: Attributes observed by the binding.
|
|
91
|
+
on_connected: Callback invoked when connected.
|
|
92
|
+
on_disconnected: Callback invoked when disconnected.
|
|
93
|
+
on_attribute_changed: Callback invoked on attribute changes.
|
|
94
|
+
|
|
95
|
+
Returns:
|
|
96
|
+
A binding handle whose ``dispose`` increments the counter.
|
|
97
|
+
|
|
98
|
+
"""
|
|
99
|
+
self.bind_calls.append((node, observed_attributes))
|
|
100
|
+
return _FakeCustomElementBinding(self)
|
|
101
|
+
|
|
102
|
+
def is_document_connected(self, node: Any) -> bool:
|
|
103
|
+
"""Report whether a node is considered document-connected.
|
|
104
|
+
|
|
105
|
+
Args:
|
|
106
|
+
node: Node to check.
|
|
107
|
+
|
|
108
|
+
Returns:
|
|
109
|
+
``True`` if the fake is configured as connected or the node reports
|
|
110
|
+
``isConnected``.
|
|
111
|
+
|
|
112
|
+
"""
|
|
113
|
+
return self.connected or bool(getattr(node, "isConnected", False))
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
class FakeMediaQueryPort(MediaQueryPort):
|
|
117
|
+
"""Provide controllable media-query values for tests.
|
|
118
|
+
|
|
119
|
+
Args:
|
|
120
|
+
prefers_dark: Initial value for ``prefers_dark``.
|
|
121
|
+
prefers_reduced_motion: Initial value for ``prefers_reduced_motion``.
|
|
122
|
+
|
|
123
|
+
"""
|
|
124
|
+
|
|
125
|
+
def __init__(
|
|
126
|
+
self,
|
|
127
|
+
*,
|
|
128
|
+
prefers_dark: bool = False,
|
|
129
|
+
prefers_reduced_motion: bool = False,
|
|
130
|
+
) -> None:
|
|
131
|
+
self._prefers_dark = prefers_dark
|
|
132
|
+
self._prefers_reduced_motion = prefers_reduced_motion
|
|
133
|
+
|
|
134
|
+
def prefers_dark(self) -> bool:
|
|
135
|
+
"""Return the configured dark-mode preference.
|
|
136
|
+
|
|
137
|
+
Returns:
|
|
138
|
+
``True`` if dark mode is preferred.
|
|
139
|
+
|
|
140
|
+
"""
|
|
141
|
+
return self._prefers_dark
|
|
142
|
+
|
|
143
|
+
def prefers_reduced_motion(self) -> bool:
|
|
144
|
+
"""Return the configured reduced-motion preference.
|
|
145
|
+
|
|
146
|
+
Returns:
|
|
147
|
+
``True`` if reduced motion is preferred.
|
|
148
|
+
|
|
149
|
+
"""
|
|
150
|
+
return self._prefers_reduced_motion
|
|
151
|
+
|
|
152
|
+
def set_prefers_reduced_motion(self, value: bool) -> None:
|
|
153
|
+
"""Update the reduced-motion preference.
|
|
154
|
+
|
|
155
|
+
Args:
|
|
156
|
+
value: New preference value.
|
|
157
|
+
|
|
158
|
+
"""
|
|
159
|
+
self._prefers_reduced_motion = value
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
class FakeBrowserDOMPort(ServerDOMPort):
|
|
163
|
+
"""Provide an in-memory DOM with synthetic document listeners.
|
|
164
|
+
|
|
165
|
+
Attributes:
|
|
166
|
+
body: Document body node.
|
|
167
|
+
|
|
168
|
+
"""
|
|
169
|
+
|
|
170
|
+
def __init__(self) -> None:
|
|
171
|
+
super().__init__()
|
|
172
|
+
self._html = FakeDOMNode("html")
|
|
173
|
+
self._html.__webcompy_document_root__ = True
|
|
174
|
+
self._head = FakeDOMNode("head")
|
|
175
|
+
self._body = FakeDOMNode("body")
|
|
176
|
+
self._html.appendChild(self._head)
|
|
177
|
+
self._html.appendChild(self._body)
|
|
178
|
+
self._document_listeners: dict[str, list[Any]] = {}
|
|
179
|
+
|
|
180
|
+
@property
|
|
181
|
+
def body(self) -> FakeDOMNode:
|
|
182
|
+
"""Return the document body node."""
|
|
183
|
+
return self._body
|
|
184
|
+
|
|
185
|
+
def create_element(self, tag: str) -> FakeDOMNode:
|
|
186
|
+
"""Create an element node.
|
|
187
|
+
|
|
188
|
+
Args:
|
|
189
|
+
tag: Tag name for the new element.
|
|
190
|
+
|
|
191
|
+
Returns:
|
|
192
|
+
A new ``FakeDOMNode`` with the given tag.
|
|
193
|
+
|
|
194
|
+
"""
|
|
195
|
+
return FakeDOMNode(tag)
|
|
196
|
+
|
|
197
|
+
def create_text_node(self, text: str) -> FakeDOMNode:
|
|
198
|
+
"""Create a text node.
|
|
199
|
+
|
|
200
|
+
Args:
|
|
201
|
+
text: Text content for the node.
|
|
202
|
+
|
|
203
|
+
Returns:
|
|
204
|
+
A new text ``FakeDOMNode``.
|
|
205
|
+
|
|
206
|
+
"""
|
|
207
|
+
return FakeDOMNode("#text", text_content=text)
|
|
208
|
+
|
|
209
|
+
def create_comment(self, data: str) -> FakeDOMNode:
|
|
210
|
+
"""Create a comment node.
|
|
211
|
+
|
|
212
|
+
Args:
|
|
213
|
+
data: Comment text.
|
|
214
|
+
|
|
215
|
+
Returns:
|
|
216
|
+
A new comment ``FakeDOMNode``.
|
|
217
|
+
|
|
218
|
+
"""
|
|
219
|
+
return FakeDOMNode("#comment", text_content=data)
|
|
220
|
+
|
|
221
|
+
def query_selector(self, selector: str) -> FakeDOMNode | None:
|
|
222
|
+
"""Find the first node matching a simple selector.
|
|
223
|
+
|
|
224
|
+
Args:
|
|
225
|
+
selector: CSS selector supporting tag, ``#id``, or
|
|
226
|
+
``tag[attr="value"]``.
|
|
227
|
+
|
|
228
|
+
Returns:
|
|
229
|
+
The first matching node or ``None`` when no match exists.
|
|
230
|
+
|
|
231
|
+
"""
|
|
232
|
+
if ">" in selector:
|
|
233
|
+
return None
|
|
234
|
+
tag_match = re.match(r"([a-zA-Z][a-zA-Z0-9]*)", selector)
|
|
235
|
+
id_match = re.match(r"#([a-zA-Z][a-zA-Z0-9_-]*)", selector)
|
|
236
|
+
attr_match = re.match(r'([a-zA-Z][a-zA-Z0-9]*)\[([a-zA-Z_-]+)="([^"]*)"\]', selector)
|
|
237
|
+
|
|
238
|
+
if id_match:
|
|
239
|
+
return _find_by_id(self._html, id_match.group(1))
|
|
240
|
+
if attr_match:
|
|
241
|
+
return _find_by_tag_attr(self._html, attr_match.group(1), attr_match.group(2), attr_match.group(3))
|
|
242
|
+
if tag_match:
|
|
243
|
+
return _find_by_tag(self._html, tag_match.group(1))
|
|
244
|
+
return None
|
|
245
|
+
|
|
246
|
+
def query_selector_all(
|
|
247
|
+
self,
|
|
248
|
+
selector: str,
|
|
249
|
+
*,
|
|
250
|
+
root: Any | None = None,
|
|
251
|
+
) -> list[FakeDOMNode]:
|
|
252
|
+
"""Find all nodes matching ``selector`` within ``root`` or document.
|
|
253
|
+
|
|
254
|
+
Args:
|
|
255
|
+
selector: CSS selector string. Comma-separated groups and
|
|
256
|
+
``:not()`` are supported for the overlay use case.
|
|
257
|
+
root: Optional subtree root.
|
|
258
|
+
|
|
259
|
+
Returns:
|
|
260
|
+
Matching nodes in document order.
|
|
261
|
+
|
|
262
|
+
"""
|
|
263
|
+
scope = root if root is not None else self._html
|
|
264
|
+
if not isinstance(scope, FakeDOMNode):
|
|
265
|
+
return []
|
|
266
|
+
collected: list[FakeDOMNode] = []
|
|
267
|
+
stack: list[FakeDOMNode] = [scope]
|
|
268
|
+
while stack:
|
|
269
|
+
node = stack.pop()
|
|
270
|
+
if node.nodeType == 1 and _node_matches_fake_selector(node, selector):
|
|
271
|
+
collected.append(node)
|
|
272
|
+
children = node.childNodes
|
|
273
|
+
for index in range(children.length - 1, -1, -1):
|
|
274
|
+
child = children[index]
|
|
275
|
+
if isinstance(child, FakeDOMNode):
|
|
276
|
+
stack.append(child)
|
|
277
|
+
order: list[FakeDOMNode] = []
|
|
278
|
+
s: list[FakeDOMNode] = [scope] # type: ignore[assignment]
|
|
279
|
+
while s:
|
|
280
|
+
cur = s.pop()
|
|
281
|
+
order.append(cur)
|
|
282
|
+
kids = cur.childNodes
|
|
283
|
+
for idx in range(kids.length - 1, -1, -1):
|
|
284
|
+
ch = kids[idx]
|
|
285
|
+
if isinstance(ch, FakeDOMNode):
|
|
286
|
+
s.append(ch)
|
|
287
|
+
index_map = {id(n): i for i, n in enumerate(order)}
|
|
288
|
+
collected.sort(key=lambda n: index_map.get(id(n), len(order)))
|
|
289
|
+
return collected
|
|
290
|
+
|
|
291
|
+
def get_element_by_id(self, element_id: str) -> FakeDOMNode | None:
|
|
292
|
+
"""Return the element with the given identifier.
|
|
293
|
+
|
|
294
|
+
Args:
|
|
295
|
+
element_id: Value of the ``id`` attribute to search for.
|
|
296
|
+
|
|
297
|
+
Returns:
|
|
298
|
+
The matching node or ``None``.
|
|
299
|
+
|
|
300
|
+
"""
|
|
301
|
+
return _find_by_id(self._html, element_id)
|
|
302
|
+
|
|
303
|
+
def add_document_event_listener(
|
|
304
|
+
self, event_type: str, handler: Any, *, capture: bool = False
|
|
305
|
+
) -> Callable[[], None]:
|
|
306
|
+
"""Register a document-level event listener.
|
|
307
|
+
|
|
308
|
+
Args:
|
|
309
|
+
event_type: Event type to listen for.
|
|
310
|
+
handler: Callback invoked when the event is dispatched.
|
|
311
|
+
capture: Accepted for interface parity; the fake dispatches
|
|
312
|
+
to registered handlers regardless of event phase.
|
|
313
|
+
|
|
314
|
+
Returns:
|
|
315
|
+
A callable that removes the listener.
|
|
316
|
+
|
|
317
|
+
"""
|
|
318
|
+
self._document_listeners.setdefault(event_type, []).append(handler)
|
|
319
|
+
|
|
320
|
+
def _remove() -> None:
|
|
321
|
+
listeners = self._document_listeners.get(event_type)
|
|
322
|
+
if listeners is None:
|
|
323
|
+
return
|
|
324
|
+
with contextlib.suppress(ValueError):
|
|
325
|
+
listeners.remove(handler)
|
|
326
|
+
|
|
327
|
+
return _remove
|
|
328
|
+
|
|
329
|
+
def dispatch_document_event(self, event_type: str, event: Any = None) -> None:
|
|
330
|
+
"""Dispatch a synthetic document event.
|
|
331
|
+
|
|
332
|
+
Args:
|
|
333
|
+
event_type: Event type to dispatch.
|
|
334
|
+
event: Payload forwarded to registered handlers.
|
|
335
|
+
|
|
336
|
+
"""
|
|
337
|
+
for handler in list(self._document_listeners.get(event_type, ())):
|
|
338
|
+
if handler in self._document_listeners.get(event_type, ()):
|
|
339
|
+
handler(event)
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def _find_by_tag(node: FakeDOMNode, tag: str) -> FakeDOMNode | None:
|
|
343
|
+
if node.nodeName == tag.upper():
|
|
344
|
+
return node
|
|
345
|
+
for i in range(node.childNodes.length):
|
|
346
|
+
child = node.childNodes[i]
|
|
347
|
+
if isinstance(child, FakeDOMNode):
|
|
348
|
+
result = _find_by_tag(child, tag)
|
|
349
|
+
if result is not None:
|
|
350
|
+
return result
|
|
351
|
+
return None
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
def _find_by_id(node: FakeDOMNode, element_id: str) -> FakeDOMNode | None:
|
|
355
|
+
if node.getAttribute("id") == element_id:
|
|
356
|
+
return node
|
|
357
|
+
for i in range(node.childNodes.length):
|
|
358
|
+
child = node.childNodes[i]
|
|
359
|
+
if isinstance(child, FakeDOMNode):
|
|
360
|
+
result = _find_by_id(child, element_id)
|
|
361
|
+
if result is not None:
|
|
362
|
+
return result
|
|
363
|
+
return None
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
def _find_by_tag_attr(node: FakeDOMNode, tag: str, attr_name: str, attr_value: str) -> FakeDOMNode | None:
|
|
367
|
+
if node.nodeName == tag.upper() and node.getAttribute(attr_name) == attr_value:
|
|
368
|
+
return node
|
|
369
|
+
for i in range(node.childNodes.length):
|
|
370
|
+
child = node.childNodes[i]
|
|
371
|
+
if isinstance(child, FakeDOMNode):
|
|
372
|
+
result = _find_by_tag_attr(child, tag, attr_name, attr_value)
|
|
373
|
+
if result is not None:
|
|
374
|
+
return result
|
|
375
|
+
return None
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
def _node_matches_fake_selector(node: FakeDOMNode, selector: str) -> bool:
|
|
379
|
+
for group in selector.split(","):
|
|
380
|
+
group = group.strip()
|
|
381
|
+
if group and _fake_group_matches(node, group):
|
|
382
|
+
return True
|
|
383
|
+
return False
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
def _fake_group_matches(node: FakeDOMNode, group: str) -> bool:
|
|
387
|
+
if ":not(" in group:
|
|
388
|
+
outer, _, inner = group.partition(":not(")
|
|
389
|
+
inner = inner.rstrip(")")
|
|
390
|
+
outer = outer.strip()
|
|
391
|
+
if not _fake_simple_attr_match(node, outer):
|
|
392
|
+
return False
|
|
393
|
+
return not _fake_simple_attr_match(node, inner.strip())
|
|
394
|
+
return _fake_simple_attr_match(node, group)
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
def _fake_simple_attr_match(node: FakeDOMNode, expr: str) -> bool:
|
|
398
|
+
expr = expr.strip()
|
|
399
|
+
if not expr:
|
|
400
|
+
return False
|
|
401
|
+
if expr == "*":
|
|
402
|
+
return True
|
|
403
|
+
tag: str | None = None
|
|
404
|
+
tag_m = re.match(r"^([a-zA-Z][a-zA-Z0-9]*)", expr)
|
|
405
|
+
rest = expr
|
|
406
|
+
if tag_m:
|
|
407
|
+
tag = tag_m.group(1).lower()
|
|
408
|
+
rest = expr[len(tag_m.group(1)) :]
|
|
409
|
+
if not rest.strip():
|
|
410
|
+
return node.nodeName.lower() == tag
|
|
411
|
+
rest = rest.strip()
|
|
412
|
+
if tag is not None and not rest:
|
|
413
|
+
return node.nodeName.lower() == tag
|
|
414
|
+
attr_re = re.compile(r'^\[([a-zA-Z0-9_-]+)(?:="([^"]*)")?\]')
|
|
415
|
+
has_predicate = False
|
|
416
|
+
while rest:
|
|
417
|
+
rest = rest.strip()
|
|
418
|
+
if not rest:
|
|
419
|
+
break
|
|
420
|
+
m = attr_re.match(rest)
|
|
421
|
+
if m is None:
|
|
422
|
+
return False
|
|
423
|
+
has_predicate = True
|
|
424
|
+
attr_name = m.group(1)
|
|
425
|
+
attr_value = m.group(2)
|
|
426
|
+
actual = node.getAttribute(attr_name)
|
|
427
|
+
if attr_value is None:
|
|
428
|
+
if actual is None:
|
|
429
|
+
return False
|
|
430
|
+
else:
|
|
431
|
+
if actual != attr_value:
|
|
432
|
+
return False
|
|
433
|
+
rest = rest[m.end() :]
|
|
434
|
+
if has_predicate:
|
|
435
|
+
return not (tag is not None and node.nodeName.lower() != tag)
|
|
436
|
+
if tag is not None:
|
|
437
|
+
return node.nodeName.lower() == tag
|
|
438
|
+
return False
|
|
439
|
+
|
|
440
|
+
|
|
441
|
+
class FakeBrowserHostPort(HostPort):
|
|
442
|
+
"""Provide synthetic window events and macro-task scheduling."""
|
|
443
|
+
|
|
444
|
+
def __init__(self, dom_port: FakeBrowserDOMPort | None = None) -> None:
|
|
445
|
+
self._window_listeners: dict[str, list[Any]] = {}
|
|
446
|
+
self._dom_port = dom_port
|
|
447
|
+
|
|
448
|
+
def schedule_macro_task(self, callback: Any) -> None:
|
|
449
|
+
"""Execute a macro task immediately.
|
|
450
|
+
|
|
451
|
+
Args:
|
|
452
|
+
callback: Callable to invoke synchronously.
|
|
453
|
+
|
|
454
|
+
"""
|
|
455
|
+
callback()
|
|
456
|
+
|
|
457
|
+
def add_window_event_listener(self, event_type: str, handler: Any) -> Callable[[], None]:
|
|
458
|
+
"""Register a window-level event listener.
|
|
459
|
+
|
|
460
|
+
Args:
|
|
461
|
+
event_type: Event type to listen for.
|
|
462
|
+
handler: Callback invoked when the event is dispatched.
|
|
463
|
+
|
|
464
|
+
Returns:
|
|
465
|
+
A callable that removes the listener.
|
|
466
|
+
|
|
467
|
+
"""
|
|
468
|
+
self._window_listeners.setdefault(event_type, []).append(handler)
|
|
469
|
+
|
|
470
|
+
def _remove() -> None:
|
|
471
|
+
listeners = self._window_listeners.get(event_type)
|
|
472
|
+
if listeners is None:
|
|
473
|
+
return
|
|
474
|
+
with contextlib.suppress(ValueError):
|
|
475
|
+
listeners.remove(handler)
|
|
476
|
+
|
|
477
|
+
return _remove
|
|
478
|
+
|
|
479
|
+
def dispatch_window_event(self, event_type: str, event: Any = None) -> None:
|
|
480
|
+
"""Dispatch a synthetic window event.
|
|
481
|
+
|
|
482
|
+
Args:
|
|
483
|
+
event_type: Event type to dispatch.
|
|
484
|
+
event: Payload forwarded to registered handlers.
|
|
485
|
+
|
|
486
|
+
"""
|
|
487
|
+
for handler in list(self._window_listeners.get(event_type, ())):
|
|
488
|
+
if handler in self._window_listeners.get(event_type, ()):
|
|
489
|
+
handler(event)
|
|
490
|
+
|
|
491
|
+
def create_js_global_getter(
|
|
492
|
+
self,
|
|
493
|
+
name: str,
|
|
494
|
+
*,
|
|
495
|
+
wrapper: Any = None,
|
|
496
|
+
default: Any = None,
|
|
497
|
+
) -> Any:
|
|
498
|
+
"""Create a getter for a synthetic JavaScript global.
|
|
499
|
+
|
|
500
|
+
Args:
|
|
501
|
+
name: Global name.
|
|
502
|
+
wrapper: Optional wrapper applied to the retrieved value.
|
|
503
|
+
default: Value returned when no wrapper is provided.
|
|
504
|
+
|
|
505
|
+
Returns:
|
|
506
|
+
A zero-argument getter returning the wrapped or default value.
|
|
507
|
+
|
|
508
|
+
"""
|
|
509
|
+
|
|
510
|
+
def _getter() -> Any:
|
|
511
|
+
if self._dom_port is not None and name == "document":
|
|
512
|
+
doc = self._dom_port._html # type: ignore[attr-defined]
|
|
513
|
+
fake_active = getattr(doc, "_fake_active_element", None)
|
|
514
|
+
if wrapper is not None:
|
|
515
|
+
if fake_active is not None:
|
|
516
|
+
fake_doc = type("FakeDoc", (), {"activeElement": fake_active})()
|
|
517
|
+
return wrapper(fake_doc)
|
|
518
|
+
return wrapper(None)
|
|
519
|
+
if wrapper is not None:
|
|
520
|
+
return wrapper(None)
|
|
521
|
+
return default
|
|
522
|
+
|
|
523
|
+
return _getter
|
|
524
|
+
|
|
525
|
+
|
|
526
|
+
class FakeBrowserFFIPort(FFIPort):
|
|
527
|
+
"""Provide ``FFIPort`` behavior without a JavaScript bridge."""
|
|
528
|
+
|
|
529
|
+
def create_proxy(self, func: Any) -> Any:
|
|
530
|
+
"""Create a mock proxy that forwards calls to ``func``.
|
|
531
|
+
|
|
532
|
+
Args:
|
|
533
|
+
func: Callable to wrap.
|
|
534
|
+
|
|
535
|
+
Returns:
|
|
536
|
+
A ``MagicMock`` proxy with a ``destroy`` method.
|
|
537
|
+
|
|
538
|
+
"""
|
|
539
|
+
proxy = MagicMock(side_effect=func)
|
|
540
|
+
proxy.destroy = MagicMock()
|
|
541
|
+
return proxy
|
|
542
|
+
|
|
543
|
+
def destroy_proxy(self, proxy: Any) -> None:
|
|
544
|
+
"""Destroy a proxy created by ``create_proxy``.
|
|
545
|
+
|
|
546
|
+
Args:
|
|
547
|
+
proxy: Proxy to destroy.
|
|
548
|
+
|
|
549
|
+
"""
|
|
550
|
+
if hasattr(proxy, "destroy"):
|
|
551
|
+
proxy.destroy()
|
|
552
|
+
|
|
553
|
+
def is_none(self, value: Any) -> bool:
|
|
554
|
+
"""Check whether a value is ``None``.
|
|
555
|
+
|
|
556
|
+
Args:
|
|
557
|
+
value: Value to test.
|
|
558
|
+
|
|
559
|
+
Returns:
|
|
560
|
+
``True`` when ``value`` is ``None``.
|
|
561
|
+
|
|
562
|
+
"""
|
|
563
|
+
return value is None
|
|
564
|
+
|
|
565
|
+
def to_js(self, value: Any, **kwargs: Any) -> Any:
|
|
566
|
+
"""Return the value unchanged as a JS equivalent.
|
|
567
|
+
|
|
568
|
+
Args:
|
|
569
|
+
value: Value to convert.
|
|
570
|
+
**kwargs: Additional conversion options.
|
|
571
|
+
|
|
572
|
+
Returns:
|
|
573
|
+
``value`` unchanged.
|
|
574
|
+
|
|
575
|
+
"""
|
|
576
|
+
return value
|
|
577
|
+
|
|
578
|
+
def assign(self, target: Any, source: Any) -> None:
|
|
579
|
+
"""Merge ``source`` into ``target``.
|
|
580
|
+
|
|
581
|
+
Args:
|
|
582
|
+
target: Mapping to update.
|
|
583
|
+
source: Mapping whose entries are copied into ``target``.
|
|
584
|
+
|
|
585
|
+
"""
|
|
586
|
+
target.update(source)
|
|
587
|
+
|
|
588
|
+
|
|
589
|
+
class _FakeFetchStream(FetchStream):
|
|
590
|
+
def __init__(
|
|
591
|
+
self,
|
|
592
|
+
chunks: list[str],
|
|
593
|
+
status_code: int,
|
|
594
|
+
headers: dict[str, str],
|
|
595
|
+
ok: bool,
|
|
596
|
+
port: FakeFetchPort,
|
|
597
|
+
key: tuple[str, str],
|
|
598
|
+
) -> None:
|
|
599
|
+
super().__init__(status_code, headers, ok)
|
|
600
|
+
self._chunks = iter(chunks)
|
|
601
|
+
self._port = port
|
|
602
|
+
self._key = key
|
|
603
|
+
self.aborted = False
|
|
604
|
+
|
|
605
|
+
async def __anext__(self) -> str:
|
|
606
|
+
if self._closed:
|
|
607
|
+
raise StopAsyncIteration
|
|
608
|
+
try:
|
|
609
|
+
return next(self._chunks)
|
|
610
|
+
except StopIteration:
|
|
611
|
+
raise StopAsyncIteration from None
|
|
612
|
+
|
|
613
|
+
def close(self) -> None:
|
|
614
|
+
if self._closed:
|
|
615
|
+
return
|
|
616
|
+
super().close()
|
|
617
|
+
self.aborted = True
|
|
618
|
+
self._port.aborted_streams.append(self._key)
|
|
619
|
+
|
|
620
|
+
|
|
621
|
+
@dataclass
|
|
622
|
+
class RecordedRequest:
|
|
623
|
+
"""A fetch request observed by a fake fetch port.
|
|
624
|
+
|
|
625
|
+
Attributes:
|
|
626
|
+
method: HTTP method of the observed request.
|
|
627
|
+
url: Target URL of the observed request.
|
|
628
|
+
headers: Request headers mapping.
|
|
629
|
+
body: Request body (text or bytes), or ``None``.
|
|
630
|
+
|
|
631
|
+
"""
|
|
632
|
+
|
|
633
|
+
method: str
|
|
634
|
+
url: str
|
|
635
|
+
headers: dict[str, str]
|
|
636
|
+
body: str | bytes | None
|
|
637
|
+
|
|
638
|
+
|
|
639
|
+
class FakeFetchPort(FetchPort):
|
|
640
|
+
"""Serve canned fetch responses and streams for assertions.
|
|
641
|
+
|
|
642
|
+
Args:
|
|
643
|
+
responses: Mapping from ``(method, url)`` to canned ``Response``.
|
|
644
|
+
streams: Mapping from ``(method, url)`` to scripted chunk lists.
|
|
645
|
+
|
|
646
|
+
Attributes:
|
|
647
|
+
aborted_streams: Recorded ``(method, url)`` pairs of streams
|
|
648
|
+
closed before completion.
|
|
649
|
+
requests: Recorded requests in arrival order.
|
|
650
|
+
|
|
651
|
+
"""
|
|
652
|
+
|
|
653
|
+
def __init__(
|
|
654
|
+
self,
|
|
655
|
+
responses: dict[tuple[str, str], Response] | None = None,
|
|
656
|
+
streams: dict[tuple[str, str], list[str]] | None = None,
|
|
657
|
+
) -> None:
|
|
658
|
+
self._responses = responses or {}
|
|
659
|
+
self._streams = streams or {}
|
|
660
|
+
self.aborted_streams: list[tuple[str, str]] = []
|
|
661
|
+
self.requests: list[RecordedRequest] = []
|
|
662
|
+
|
|
663
|
+
async def fetch(
|
|
664
|
+
self,
|
|
665
|
+
url: str,
|
|
666
|
+
*,
|
|
667
|
+
method: str = "GET",
|
|
668
|
+
headers: dict[str, str] | None = None,
|
|
669
|
+
body: str | bytes | None = None,
|
|
670
|
+
) -> Response:
|
|
671
|
+
"""Return a canned response for the requested URL.
|
|
672
|
+
|
|
673
|
+
Args:
|
|
674
|
+
url: Target URL.
|
|
675
|
+
method: HTTP method.
|
|
676
|
+
headers: Optional request headers.
|
|
677
|
+
body: Optional request body as text or bytes.
|
|
678
|
+
|
|
679
|
+
Returns:
|
|
680
|
+
The canned ``Response`` for ``(method, url)``.
|
|
681
|
+
|
|
682
|
+
Raises:
|
|
683
|
+
KeyError: If no response is registered for the key.
|
|
684
|
+
|
|
685
|
+
"""
|
|
686
|
+
self.requests.append(
|
|
687
|
+
RecordedRequest(method=method, url=url, headers=dict(headers) if headers else {}, body=body)
|
|
688
|
+
)
|
|
689
|
+
key = (method, url)
|
|
690
|
+
if key in self._responses:
|
|
691
|
+
return self._responses[key]
|
|
692
|
+
raise KeyError(
|
|
693
|
+
f"No canned response registered for {method} {url}. Registered keys: {list(self._responses.keys())}"
|
|
694
|
+
)
|
|
695
|
+
|
|
696
|
+
async def stream(
|
|
697
|
+
self,
|
|
698
|
+
url: str,
|
|
699
|
+
*,
|
|
700
|
+
method: str = "GET",
|
|
701
|
+
headers: dict[str, str] | None = None,
|
|
702
|
+
body: str | bytes | None = None,
|
|
703
|
+
) -> FetchStream:
|
|
704
|
+
"""Return a scripted stream for the requested URL.
|
|
705
|
+
|
|
706
|
+
Args:
|
|
707
|
+
url: Target URL.
|
|
708
|
+
method: HTTP method.
|
|
709
|
+
headers: Optional request headers.
|
|
710
|
+
body: Optional request body as text or bytes.
|
|
711
|
+
|
|
712
|
+
Returns:
|
|
713
|
+
A ``FetchStream`` yielding the scripted chunks.
|
|
714
|
+
|
|
715
|
+
Raises:
|
|
716
|
+
KeyError: If no stream or response is registered for the key.
|
|
717
|
+
|
|
718
|
+
"""
|
|
719
|
+
self.requests.append(
|
|
720
|
+
RecordedRequest(method=method, url=url, headers=dict(headers) if headers else {}, body=body)
|
|
721
|
+
)
|
|
722
|
+
key = (method, url)
|
|
723
|
+
response = self._responses.get(key)
|
|
724
|
+
if key in self._streams:
|
|
725
|
+
if response is not None:
|
|
726
|
+
return _FakeFetchStream(
|
|
727
|
+
list(self._streams[key]), response.status_code, response.headers, response.ok, self, key
|
|
728
|
+
)
|
|
729
|
+
return _FakeFetchStream(
|
|
730
|
+
list(self._streams[key]), 200, {"content-type": "text/event-stream"}, True, self, key
|
|
731
|
+
)
|
|
732
|
+
if response is not None:
|
|
733
|
+
return _FakeFetchStream([response.text], response.status_code, response.headers, response.ok, self, key)
|
|
734
|
+
raise KeyError(
|
|
735
|
+
f"No scripted stream or canned response registered for {method} {url}. "
|
|
736
|
+
f"Registered stream keys: {list(self._streams.keys())}; response keys: {list(self._responses.keys())}"
|
|
737
|
+
)
|
|
738
|
+
|
|
739
|
+
|
|
740
|
+
class FakeHistoryPort(HistoryPort):
|
|
741
|
+
"""Record history navigation calls for assertions.
|
|
742
|
+
|
|
743
|
+
Args:
|
|
744
|
+
mode: Router mode to simulate.
|
|
745
|
+
initial_path: Initial path for the history.
|
|
746
|
+
|
|
747
|
+
Attributes:
|
|
748
|
+
pushed_urls: Recorded ``(path, state)`` pairs passed to
|
|
749
|
+
``push_url``.
|
|
750
|
+
replaced_urls: Recorded ``(path, state)`` pairs passed to
|
|
751
|
+
``replace_url``.
|
|
752
|
+
|
|
753
|
+
"""
|
|
754
|
+
|
|
755
|
+
def __init__(self, *, mode: Literal["hash", "history"] = "history", initial_path: str = "/") -> None:
|
|
756
|
+
super().__init__(initial_path, mode=mode)
|
|
757
|
+
self.pushed_urls: list[tuple[str, dict[str, Any] | None]] = []
|
|
758
|
+
self.replaced_urls: list[tuple[str, dict[str, Any] | None]] = []
|
|
759
|
+
|
|
760
|
+
def push_url(self, path: str, state: dict[str, Any] | None = None) -> None:
|
|
761
|
+
"""Record a push navigation.
|
|
762
|
+
|
|
763
|
+
Args:
|
|
764
|
+
path: Path to push.
|
|
765
|
+
state: Optional navigation state.
|
|
766
|
+
|
|
767
|
+
"""
|
|
768
|
+
self.pushed_urls.append((path, state))
|
|
769
|
+
|
|
770
|
+
def replace_url(self, path: str, state: dict[str, Any] | None = None) -> None:
|
|
771
|
+
"""Record a replace navigation.
|
|
772
|
+
|
|
773
|
+
Args:
|
|
774
|
+
path: Path to replace the current entry with.
|
|
775
|
+
state: Optional navigation state.
|
|
776
|
+
|
|
777
|
+
"""
|
|
778
|
+
self.replaced_urls.append((path, state))
|
|
779
|
+
|
|
780
|
+
def current_search(self) -> str:
|
|
781
|
+
"""Return the current search string.
|
|
782
|
+
|
|
783
|
+
Returns:
|
|
784
|
+
An empty search string in the fake implementation.
|
|
785
|
+
|
|
786
|
+
"""
|
|
787
|
+
return ""
|
|
788
|
+
|
|
789
|
+
def history_state(self) -> object | None:
|
|
790
|
+
"""Return the current history state.
|
|
791
|
+
|
|
792
|
+
Returns:
|
|
793
|
+
The stored navigation state.
|
|
794
|
+
|
|
795
|
+
"""
|
|
796
|
+
return self._state
|
|
797
|
+
|
|
798
|
+
def refresh_from_window(self) -> None:
|
|
799
|
+
"""Synchronize the fake history with the window location."""
|
|
800
|
+
pass
|
|
801
|
+
|
|
802
|
+
|
|
803
|
+
class _PendingTask:
|
|
804
|
+
"""Bookkeeping stand-in for a scheduled coroutine.
|
|
805
|
+
|
|
806
|
+
The fake never runs a scheduled coroutine itself; it only records it for a
|
|
807
|
+
later explicit ``drain()``. The returned stand-in satisfies the small
|
|
808
|
+
``asyncio.Task`` surface that dynamic-element hydration uses (``done``,
|
|
809
|
+
``cancel``, ``cancelled``, ``exception``, ``add_done_callback``) without
|
|
810
|
+
requiring an event loop at ``schedule()`` time, so sync test contexts do not
|
|
811
|
+
leak un-awaited placeholder coroutines. ``drain()``/``await_pending()``
|
|
812
|
+
settle the stand-ins of the coroutines they execute: the stand-in is marked
|
|
813
|
+
done, the executed coroutine's exception (if any) is recorded, and registered
|
|
814
|
+
done callbacks are invoked. Cancelling an un-executed stand-in drops the
|
|
815
|
+
recorded coroutine so a later ``drain()`` does not run it (mirroring real
|
|
816
|
+
task cancellation in the browser scheduler); cancelling an executed
|
|
817
|
+
stand-in returns ``False`` and is a no-op.
|
|
818
|
+
"""
|
|
819
|
+
|
|
820
|
+
def __init__(self, scheduler: FakeAsyncSchedulerPort, coro: Coroutine[Any, Any, Any]) -> None:
|
|
821
|
+
self._scheduler = scheduler
|
|
822
|
+
self._coro = coro
|
|
823
|
+
self._done = False
|
|
824
|
+
self._cancelled = False
|
|
825
|
+
self._exception: BaseException | None = None
|
|
826
|
+
self._callbacks: list[Any] = []
|
|
827
|
+
|
|
828
|
+
def _settle(self, exception: BaseException | None) -> None:
|
|
829
|
+
if self._done:
|
|
830
|
+
return
|
|
831
|
+
self._done = True
|
|
832
|
+
self._exception = exception
|
|
833
|
+
callbacks = self._callbacks
|
|
834
|
+
self._callbacks = []
|
|
835
|
+
for callback in callbacks:
|
|
836
|
+
callback(self)
|
|
837
|
+
|
|
838
|
+
def add_done_callback(self, callback: Any) -> None:
|
|
839
|
+
self._callbacks.append(callback)
|
|
840
|
+
|
|
841
|
+
def remove_done_callback(self, callback: Any) -> None:
|
|
842
|
+
with contextlib.suppress(ValueError):
|
|
843
|
+
self._callbacks.remove(callback)
|
|
844
|
+
|
|
845
|
+
def cancel(self) -> bool:
|
|
846
|
+
if self._done:
|
|
847
|
+
return False
|
|
848
|
+
self._cancelled = True
|
|
849
|
+
self._done = True
|
|
850
|
+
with contextlib.suppress(ValueError):
|
|
851
|
+
self._scheduler._coroutines.remove(self._coro)
|
|
852
|
+
with contextlib.suppress(ValueError):
|
|
853
|
+
self._scheduler._render_coroutines.remove(self._coro)
|
|
854
|
+
return True
|
|
855
|
+
|
|
856
|
+
def cancelled(self) -> bool:
|
|
857
|
+
return self._cancelled
|
|
858
|
+
|
|
859
|
+
def done(self) -> bool:
|
|
860
|
+
return self._done
|
|
861
|
+
|
|
862
|
+
def exception(self) -> BaseException | None:
|
|
863
|
+
return self._exception
|
|
864
|
+
|
|
865
|
+
|
|
866
|
+
class FakeAsyncSchedulerPort(AsyncSchedulerPort):
|
|
867
|
+
"""Queue coroutines and expose a drainable pending-task surface."""
|
|
868
|
+
|
|
869
|
+
def __init__(self) -> None:
|
|
870
|
+
self._coroutines: list[Coroutine[Any, Any, Any]] = []
|
|
871
|
+
self._render_coroutines: list[Coroutine[Any, Any, Any]] = []
|
|
872
|
+
self._tasks: list[_PendingTask] = []
|
|
873
|
+
|
|
874
|
+
def schedule(
|
|
875
|
+
self,
|
|
876
|
+
coro: Coroutine[Any, Any, Any],
|
|
877
|
+
*,
|
|
878
|
+
render: bool = False,
|
|
879
|
+
) -> asyncio.Task[Any]:
|
|
880
|
+
"""Schedule a coroutine without running it.
|
|
881
|
+
|
|
882
|
+
Args:
|
|
883
|
+
coro: Coroutine to queue.
|
|
884
|
+
render: Whether the coroutine is part of the render phase.
|
|
885
|
+
|
|
886
|
+
Returns:
|
|
887
|
+
A pending-task stand-in resembling ``asyncio.Task``.
|
|
888
|
+
|
|
889
|
+
"""
|
|
890
|
+
self._coroutines.append(coro)
|
|
891
|
+
if render:
|
|
892
|
+
self._render_coroutines.append(coro)
|
|
893
|
+
task = _PendingTask(self, coro)
|
|
894
|
+
self._tasks.append(task)
|
|
895
|
+
return task # type: ignore[return-value]
|
|
896
|
+
|
|
897
|
+
async def _execute(self, coros: list[Coroutine[Any, Any, Any]]) -> None:
|
|
898
|
+
results = await asyncio.gather(*coros, return_exceptions=True)
|
|
899
|
+
for coro, result in zip(coros, results, strict=True):
|
|
900
|
+
for task in self._tasks:
|
|
901
|
+
if task._coro is coro:
|
|
902
|
+
task._settle(result if isinstance(result, BaseException) else None)
|
|
903
|
+
break
|
|
904
|
+
|
|
905
|
+
async def drain(self) -> None:
|
|
906
|
+
"""Execute all queued coroutines, including those scheduled recursively."""
|
|
907
|
+
iteration = 0
|
|
908
|
+
while self._coroutines:
|
|
909
|
+
coros = list(self._coroutines)
|
|
910
|
+
self._coroutines = []
|
|
911
|
+
self._render_coroutines = [c for c in self._render_coroutines if c not in coros]
|
|
912
|
+
await self._execute(coros)
|
|
913
|
+
iteration += 1
|
|
914
|
+
if iteration > _MAX_DRAIN_ITERATIONS:
|
|
915
|
+
_logger.warning(
|
|
916
|
+
"FakeAsyncSchedulerPort.drain exceeded %d drain iterations; "
|
|
917
|
+
"possible recursive scheduling bug (%d coroutines still collected)",
|
|
918
|
+
_MAX_DRAIN_ITERATIONS,
|
|
919
|
+
len(self._coroutines),
|
|
920
|
+
)
|
|
921
|
+
break
|
|
922
|
+
|
|
923
|
+
async def await_pending(self, *, only_render: bool = False) -> None:
|
|
924
|
+
"""Await pending coroutines.
|
|
925
|
+
|
|
926
|
+
Args:
|
|
927
|
+
only_render: When ``True``, await only render-phase coroutines;
|
|
928
|
+
otherwise drain all.
|
|
929
|
+
|
|
930
|
+
"""
|
|
931
|
+
if not only_render:
|
|
932
|
+
await self.drain()
|
|
933
|
+
return
|
|
934
|
+
iteration = 0
|
|
935
|
+
while self._render_coroutines:
|
|
936
|
+
coros = list(self._render_coroutines)
|
|
937
|
+
self._render_coroutines = []
|
|
938
|
+
self._coroutines = [c for c in self._coroutines if c not in coros]
|
|
939
|
+
await self._execute(coros)
|
|
940
|
+
iteration += 1
|
|
941
|
+
if iteration > _MAX_DRAIN_ITERATIONS:
|
|
942
|
+
_logger.warning(
|
|
943
|
+
"FakeAsyncSchedulerPort.await_pending exceeded %d drain iterations; "
|
|
944
|
+
"possible recursive scheduling bug (%d render coroutines still collected)",
|
|
945
|
+
_MAX_DRAIN_ITERATIONS,
|
|
946
|
+
len(self._render_coroutines),
|
|
947
|
+
)
|
|
948
|
+
break
|
|
949
|
+
|
|
950
|
+
|
|
951
|
+
class FakeTransitionStyle:
|
|
952
|
+
def __init__(self, values: dict[str, str] | None = None) -> None:
|
|
953
|
+
self._values = dict(values or {})
|
|
954
|
+
|
|
955
|
+
def get_property_value(self, name: str) -> str:
|
|
956
|
+
return self._values.get(name, "")
|
|
957
|
+
|
|
958
|
+
|
|
959
|
+
class FakeTransitionPort(TransitionPort):
|
|
960
|
+
"""Transition port driven by a logical frame queue and virtual clock.
|
|
961
|
+
|
|
962
|
+
``flush_frame()`` executes the callbacks scheduled for the next frame and
|
|
963
|
+
``advance_time(ms)`` moves the virtual clock forward, firing due
|
|
964
|
+
timeouts. Per-node computed styles are registered via ``set_style``.
|
|
965
|
+
|
|
966
|
+
Attributes:
|
|
967
|
+
enabled: Whether transition callbacks run; toggled with
|
|
968
|
+
``set_enabled``.
|
|
969
|
+
|
|
970
|
+
"""
|
|
971
|
+
|
|
972
|
+
def __init__(self) -> None:
|
|
973
|
+
self._enabled = True
|
|
974
|
+
self._frame_callbacks: list[Callable[[], Any]] = []
|
|
975
|
+
self._timeouts: list[tuple[float, int, Callable[[], Any]]] = []
|
|
976
|
+
self._timeout_seq = 0
|
|
977
|
+
self._now = 0.0
|
|
978
|
+
self._styles: dict[int, dict[str, str]] = {}
|
|
979
|
+
|
|
980
|
+
@property
|
|
981
|
+
def enabled(self) -> bool:
|
|
982
|
+
"""Return whether transitions are enabled."""
|
|
983
|
+
return self._enabled
|
|
984
|
+
|
|
985
|
+
def set_enabled(self, value: bool) -> None:
|
|
986
|
+
"""Enable or disable transition callbacks.
|
|
987
|
+
|
|
988
|
+
Args:
|
|
989
|
+
value: ``True`` to enable transitions.
|
|
990
|
+
|
|
991
|
+
"""
|
|
992
|
+
self._enabled = value
|
|
993
|
+
|
|
994
|
+
def schedule_next_frame(self, callback: Callable[[], Any]) -> Callable[[], None]:
|
|
995
|
+
"""Schedule a callback for the next frame.
|
|
996
|
+
|
|
997
|
+
Args:
|
|
998
|
+
callback: Callable invoked on the next flushed frame.
|
|
999
|
+
|
|
1000
|
+
Returns:
|
|
1001
|
+
A callable that cancels the scheduled frame callback.
|
|
1002
|
+
|
|
1003
|
+
"""
|
|
1004
|
+
self._frame_callbacks.append(callback)
|
|
1005
|
+
|
|
1006
|
+
def _cancel() -> None:
|
|
1007
|
+
if callback in self._frame_callbacks:
|
|
1008
|
+
self._frame_callbacks.remove(callback)
|
|
1009
|
+
|
|
1010
|
+
return _cancel
|
|
1011
|
+
|
|
1012
|
+
def schedule_timeout(
|
|
1013
|
+
self,
|
|
1014
|
+
callback: Callable[[], Any],
|
|
1015
|
+
delay_ms: float,
|
|
1016
|
+
) -> Callable[[], None]:
|
|
1017
|
+
"""Schedule a callback after a delay on the virtual clock.
|
|
1018
|
+
|
|
1019
|
+
Args:
|
|
1020
|
+
callback: Callable to invoke when the timeout fires.
|
|
1021
|
+
delay_ms: Delay in milliseconds.
|
|
1022
|
+
|
|
1023
|
+
Returns:
|
|
1024
|
+
A callable that cancels the scheduled timeout.
|
|
1025
|
+
|
|
1026
|
+
"""
|
|
1027
|
+
self._timeout_seq += 1
|
|
1028
|
+
seq = self._timeout_seq
|
|
1029
|
+
self._timeouts.append((self._now + delay_ms, seq, callback))
|
|
1030
|
+
|
|
1031
|
+
def _cancel() -> None:
|
|
1032
|
+
self._timeouts = [entry for entry in self._timeouts if entry[1] != seq]
|
|
1033
|
+
|
|
1034
|
+
return _cancel
|
|
1035
|
+
|
|
1036
|
+
def flush_frame(self) -> None:
|
|
1037
|
+
"""Execute callbacks scheduled for the next frame."""
|
|
1038
|
+
callbacks = list(self._frame_callbacks)
|
|
1039
|
+
self._frame_callbacks.clear()
|
|
1040
|
+
for callback in callbacks:
|
|
1041
|
+
callback()
|
|
1042
|
+
|
|
1043
|
+
def advance_time(self, ms: float) -> None:
|
|
1044
|
+
"""Advance the virtual clock and fire due timeouts.
|
|
1045
|
+
|
|
1046
|
+
Args:
|
|
1047
|
+
ms: Milliseconds to advance.
|
|
1048
|
+
|
|
1049
|
+
"""
|
|
1050
|
+
self._now += ms
|
|
1051
|
+
due = [entry for entry in self._timeouts if entry[0] <= self._now]
|
|
1052
|
+
self._timeouts = [entry for entry in self._timeouts if entry[0] > self._now]
|
|
1053
|
+
for _, _, callback in due:
|
|
1054
|
+
callback()
|
|
1055
|
+
|
|
1056
|
+
def flush_all(self) -> None:
|
|
1057
|
+
"""Flush one frame and advance the clock to fire all timeouts."""
|
|
1058
|
+
self.flush_frame()
|
|
1059
|
+
self.advance_time(10**9)
|
|
1060
|
+
|
|
1061
|
+
def get_computed_style(self, node: DOMNode) -> TransitionStyle:
|
|
1062
|
+
"""Return the fake computed style for a node.
|
|
1063
|
+
|
|
1064
|
+
Args:
|
|
1065
|
+
node: Node whose style is requested.
|
|
1066
|
+
|
|
1067
|
+
Returns:
|
|
1068
|
+
A ``TransitionStyle`` reflecting values set via ``set_style``.
|
|
1069
|
+
|
|
1070
|
+
"""
|
|
1071
|
+
return FakeTransitionStyle(self._styles.get(id(node), {}))
|
|
1072
|
+
|
|
1073
|
+
def set_style(self, node: FakeDOMNode, name: str, value: str) -> None:
|
|
1074
|
+
"""Set a CSS property in the fake computed-style table.
|
|
1075
|
+
|
|
1076
|
+
Args:
|
|
1077
|
+
node: Node to associate the style with.
|
|
1078
|
+
name: CSS property name.
|
|
1079
|
+
value: CSS property value.
|
|
1080
|
+
|
|
1081
|
+
"""
|
|
1082
|
+
self._styles.setdefault(id(node), {})[name] = value
|
|
1083
|
+
|
|
1084
|
+
|
|
1085
|
+
class _FakeEventSourceRegistration:
|
|
1086
|
+
__slots__ = ("events", "on_close", "on_error", "on_message", "on_open", "url")
|
|
1087
|
+
|
|
1088
|
+
def __init__(
|
|
1089
|
+
self,
|
|
1090
|
+
url: str,
|
|
1091
|
+
events: tuple[str, ...],
|
|
1092
|
+
on_open: Any,
|
|
1093
|
+
on_message: Any,
|
|
1094
|
+
on_error: Any,
|
|
1095
|
+
on_close: Any,
|
|
1096
|
+
) -> None:
|
|
1097
|
+
self.url = url
|
|
1098
|
+
self.events = events
|
|
1099
|
+
self.on_open = on_open
|
|
1100
|
+
self.on_message = on_message
|
|
1101
|
+
self.on_error = on_error
|
|
1102
|
+
self.on_close = on_close
|
|
1103
|
+
|
|
1104
|
+
|
|
1105
|
+
class FakeEventSourcePort(EventSourcePort):
|
|
1106
|
+
"""Track server-sent-event subscriptions and allow synthetic events.
|
|
1107
|
+
|
|
1108
|
+
Attributes:
|
|
1109
|
+
open_calls: Recorded ``(url, events)`` subscription requests.
|
|
1110
|
+
open_connections: Currently active ``(url, events)``
|
|
1111
|
+
subscriptions.
|
|
1112
|
+
|
|
1113
|
+
"""
|
|
1114
|
+
|
|
1115
|
+
def __init__(self) -> None:
|
|
1116
|
+
self._registrations: list[_FakeEventSourceRegistration] = []
|
|
1117
|
+
self.open_calls: list[tuple[str, tuple[str, ...]]] = []
|
|
1118
|
+
|
|
1119
|
+
def open(
|
|
1120
|
+
self,
|
|
1121
|
+
url: str,
|
|
1122
|
+
*,
|
|
1123
|
+
events: tuple[str, ...],
|
|
1124
|
+
on_open: Any = None,
|
|
1125
|
+
on_message: Any = None,
|
|
1126
|
+
on_error: Any = None,
|
|
1127
|
+
on_close: Any = None,
|
|
1128
|
+
) -> Callable[[], None]:
|
|
1129
|
+
"""Register a synthetic event-source subscription.
|
|
1130
|
+
|
|
1131
|
+
Args:
|
|
1132
|
+
url: Event source URL.
|
|
1133
|
+
events: Event types to subscribe to.
|
|
1134
|
+
on_open: Callback invoked when the connection opens.
|
|
1135
|
+
on_message: Callback invoked for incoming messages.
|
|
1136
|
+
on_error: Callback invoked on connection error.
|
|
1137
|
+
on_close: Callback invoked when the connection closes.
|
|
1138
|
+
|
|
1139
|
+
Returns:
|
|
1140
|
+
A callable that unregisters the subscription.
|
|
1141
|
+
|
|
1142
|
+
"""
|
|
1143
|
+
reg = _FakeEventSourceRegistration(url, tuple(events), on_open, on_message, on_error, on_close)
|
|
1144
|
+
self._registrations.append(reg)
|
|
1145
|
+
self.open_calls.append((url, tuple(events)))
|
|
1146
|
+
|
|
1147
|
+
def _cleanup() -> None:
|
|
1148
|
+
with contextlib.suppress(ValueError):
|
|
1149
|
+
self._registrations.remove(reg)
|
|
1150
|
+
|
|
1151
|
+
return _cleanup
|
|
1152
|
+
|
|
1153
|
+
@property
|
|
1154
|
+
def open_connections(self) -> list[tuple[str, tuple[str, ...]]]:
|
|
1155
|
+
"""Return active event-source subscriptions."""
|
|
1156
|
+
return [(reg.url, reg.events) for reg in self._registrations]
|
|
1157
|
+
|
|
1158
|
+
def emit_event(self, url: str, event_type: str, data: str, last_event_id: str = "") -> None:
|
|
1159
|
+
"""Emit a message event to matching subscriptions.
|
|
1160
|
+
|
|
1161
|
+
Args:
|
|
1162
|
+
url: Event source URL.
|
|
1163
|
+
event_type: Event type.
|
|
1164
|
+
data: Event payload.
|
|
1165
|
+
last_event_id: Last event identifier.
|
|
1166
|
+
|
|
1167
|
+
"""
|
|
1168
|
+
for reg in list(self._registrations):
|
|
1169
|
+
if reg.url == url and event_type in reg.events:
|
|
1170
|
+
reg.on_message(event_type, data, last_event_id)
|
|
1171
|
+
|
|
1172
|
+
def emit_open(self, url: str) -> None:
|
|
1173
|
+
"""Trigger ``on_open`` for subscriptions to ``url``.
|
|
1174
|
+
|
|
1175
|
+
Args:
|
|
1176
|
+
url: Event source URL.
|
|
1177
|
+
|
|
1178
|
+
"""
|
|
1179
|
+
for reg in list(self._registrations):
|
|
1180
|
+
if reg.url == url:
|
|
1181
|
+
reg.on_open()
|
|
1182
|
+
|
|
1183
|
+
def emit_error(self, url: str) -> None:
|
|
1184
|
+
"""Trigger ``on_error`` for subscriptions to ``url``.
|
|
1185
|
+
|
|
1186
|
+
Args:
|
|
1187
|
+
url: Event source URL.
|
|
1188
|
+
|
|
1189
|
+
"""
|
|
1190
|
+
for reg in list(self._registrations):
|
|
1191
|
+
if reg.url == url:
|
|
1192
|
+
reg.on_error()
|
|
1193
|
+
|
|
1194
|
+
def emit_close(self, url: str) -> None:
|
|
1195
|
+
"""Trigger ``on_close`` for subscriptions to ``url``.
|
|
1196
|
+
|
|
1197
|
+
Args:
|
|
1198
|
+
url: Event source URL.
|
|
1199
|
+
|
|
1200
|
+
"""
|
|
1201
|
+
for reg in list(self._registrations):
|
|
1202
|
+
if reg.url == url:
|
|
1203
|
+
reg.on_close()
|
|
1204
|
+
|
|
1205
|
+
|
|
1206
|
+
class _FakeWebSocketRegistration:
|
|
1207
|
+
__slots__ = (
|
|
1208
|
+
"on_binary",
|
|
1209
|
+
"on_close",
|
|
1210
|
+
"on_error",
|
|
1211
|
+
"on_message",
|
|
1212
|
+
"on_open",
|
|
1213
|
+
"protocols",
|
|
1214
|
+
"sent",
|
|
1215
|
+
"url",
|
|
1216
|
+
)
|
|
1217
|
+
|
|
1218
|
+
def __init__(
|
|
1219
|
+
self,
|
|
1220
|
+
url: str,
|
|
1221
|
+
protocols: tuple[str, ...],
|
|
1222
|
+
on_open: Any,
|
|
1223
|
+
on_message: Any,
|
|
1224
|
+
on_binary: Any,
|
|
1225
|
+
on_error: Any,
|
|
1226
|
+
on_close: Any,
|
|
1227
|
+
) -> None:
|
|
1228
|
+
self.url = url
|
|
1229
|
+
self.protocols = protocols
|
|
1230
|
+
self.on_open = on_open
|
|
1231
|
+
self.on_message = on_message
|
|
1232
|
+
self.on_binary = on_binary
|
|
1233
|
+
self.on_error = on_error
|
|
1234
|
+
self.on_close = on_close
|
|
1235
|
+
self.sent: list[str] = []
|
|
1236
|
+
|
|
1237
|
+
|
|
1238
|
+
class FakeWebSocketConnection(WebSocketConnection):
|
|
1239
|
+
def __init__(self, port: FakeWebSocketPort, reg: _FakeWebSocketRegistration) -> None:
|
|
1240
|
+
self._port = port
|
|
1241
|
+
self._reg = reg
|
|
1242
|
+
self._closed = False
|
|
1243
|
+
|
|
1244
|
+
def send(self, data: str) -> None:
|
|
1245
|
+
self._reg.sent.append(data)
|
|
1246
|
+
|
|
1247
|
+
def close(self) -> None:
|
|
1248
|
+
if self._closed:
|
|
1249
|
+
return
|
|
1250
|
+
self._closed = True
|
|
1251
|
+
with contextlib.suppress(ValueError):
|
|
1252
|
+
self._port._registrations.remove(self._reg)
|
|
1253
|
+
|
|
1254
|
+
|
|
1255
|
+
class FakeWebSocketPort(WebSocketPort):
|
|
1256
|
+
"""Track WebSocket connections and allow synthetic message injection.
|
|
1257
|
+
|
|
1258
|
+
Attributes:
|
|
1259
|
+
open_calls: Recorded ``(url, protocols)`` connection requests.
|
|
1260
|
+
open_connections: Currently active ``(url, protocols)``
|
|
1261
|
+
registrations.
|
|
1262
|
+
|
|
1263
|
+
"""
|
|
1264
|
+
|
|
1265
|
+
def __init__(self) -> None:
|
|
1266
|
+
self._registrations: list[_FakeWebSocketRegistration] = []
|
|
1267
|
+
self.open_calls: list[tuple[str, tuple[str, ...]]] = []
|
|
1268
|
+
|
|
1269
|
+
def open(
|
|
1270
|
+
self,
|
|
1271
|
+
url: str,
|
|
1272
|
+
*,
|
|
1273
|
+
protocols: tuple[str, ...] = (),
|
|
1274
|
+
on_open: Any = None,
|
|
1275
|
+
on_message: Any = None,
|
|
1276
|
+
on_binary: Any = None,
|
|
1277
|
+
on_error: Any = None,
|
|
1278
|
+
on_close: Any = None,
|
|
1279
|
+
) -> WebSocketConnection:
|
|
1280
|
+
"""Register a synthetic WebSocket connection.
|
|
1281
|
+
|
|
1282
|
+
Args:
|
|
1283
|
+
url: WebSocket URL.
|
|
1284
|
+
protocols: Subprotocols requested for the connection.
|
|
1285
|
+
on_open: Callback invoked when the connection opens.
|
|
1286
|
+
on_message: Callback invoked for text messages.
|
|
1287
|
+
on_binary: Callback invoked for binary messages.
|
|
1288
|
+
on_error: Callback invoked on connection error.
|
|
1289
|
+
on_close: Callback invoked when the connection closes.
|
|
1290
|
+
|
|
1291
|
+
Returns:
|
|
1292
|
+
A connection handle that records sent frames.
|
|
1293
|
+
|
|
1294
|
+
"""
|
|
1295
|
+
normalized = tuple(sorted(protocols))
|
|
1296
|
+
reg = _FakeWebSocketRegistration(url, normalized, on_open, on_message, on_binary, on_error, on_close)
|
|
1297
|
+
self._registrations.append(reg)
|
|
1298
|
+
self.open_calls.append((url, normalized))
|
|
1299
|
+
return FakeWebSocketConnection(self, reg)
|
|
1300
|
+
|
|
1301
|
+
@property
|
|
1302
|
+
def open_connections(self) -> list[tuple[str, tuple[str, ...]]]:
|
|
1303
|
+
"""Return active WebSocket registrations."""
|
|
1304
|
+
return [(reg.url, reg.protocols) for reg in self._registrations]
|
|
1305
|
+
|
|
1306
|
+
def _matching(self, url: str, protocols: tuple[str, ...] | None) -> list[_FakeWebSocketRegistration]:
|
|
1307
|
+
if protocols is None:
|
|
1308
|
+
return [reg for reg in self._registrations if reg.url == url]
|
|
1309
|
+
normalized = tuple(sorted(protocols))
|
|
1310
|
+
return [reg for reg in self._registrations if reg.url == url and reg.protocols == normalized]
|
|
1311
|
+
|
|
1312
|
+
def emit_open(self, url: str, protocols: tuple[str, ...] | None = None) -> None:
|
|
1313
|
+
"""Trigger ``on_open`` for matching WebSocket registrations.
|
|
1314
|
+
|
|
1315
|
+
Args:
|
|
1316
|
+
url: WebSocket URL.
|
|
1317
|
+
protocols: Protocols to match or ``None`` for any.
|
|
1318
|
+
|
|
1319
|
+
"""
|
|
1320
|
+
for reg in list(self._matching(url, protocols)):
|
|
1321
|
+
reg.on_open()
|
|
1322
|
+
|
|
1323
|
+
def emit_message(self, url: str, text: str, protocols: tuple[str, ...] | None = None) -> None:
|
|
1324
|
+
"""Deliver a text message to matching registrations.
|
|
1325
|
+
|
|
1326
|
+
Args:
|
|
1327
|
+
url: WebSocket URL.
|
|
1328
|
+
text: Message payload.
|
|
1329
|
+
protocols: Protocols to match or ``None`` for any.
|
|
1330
|
+
|
|
1331
|
+
"""
|
|
1332
|
+
for reg in list(self._matching(url, protocols)):
|
|
1333
|
+
reg.on_message(text)
|
|
1334
|
+
|
|
1335
|
+
def emit_binary(self, url: str, protocols: tuple[str, ...] | None = None) -> None:
|
|
1336
|
+
"""Trigger ``on_binary`` for matching registrations.
|
|
1337
|
+
|
|
1338
|
+
Args:
|
|
1339
|
+
url: WebSocket URL.
|
|
1340
|
+
protocols: Protocols to match or ``None`` for any.
|
|
1341
|
+
|
|
1342
|
+
"""
|
|
1343
|
+
for reg in list(self._matching(url, protocols)):
|
|
1344
|
+
reg.on_binary()
|
|
1345
|
+
|
|
1346
|
+
def emit_error(self, url: str, protocols: tuple[str, ...] | None = None) -> None:
|
|
1347
|
+
"""Trigger ``on_error`` for matching registrations.
|
|
1348
|
+
|
|
1349
|
+
Args:
|
|
1350
|
+
url: WebSocket URL.
|
|
1351
|
+
protocols: Protocols to match or ``None`` for any.
|
|
1352
|
+
|
|
1353
|
+
"""
|
|
1354
|
+
for reg in list(self._matching(url, protocols)):
|
|
1355
|
+
reg.on_error()
|
|
1356
|
+
|
|
1357
|
+
def emit_close(
|
|
1358
|
+
self,
|
|
1359
|
+
url: str,
|
|
1360
|
+
code: int = 1000,
|
|
1361
|
+
reason: str = "",
|
|
1362
|
+
was_clean: bool = True,
|
|
1363
|
+
protocols: tuple[str, ...] | None = None,
|
|
1364
|
+
) -> None:
|
|
1365
|
+
"""Close matching registrations and trigger ``on_close``.
|
|
1366
|
+
|
|
1367
|
+
Args:
|
|
1368
|
+
url: WebSocket URL.
|
|
1369
|
+
code: Close status code.
|
|
1370
|
+
reason: Close reason.
|
|
1371
|
+
was_clean: Whether the close was clean.
|
|
1372
|
+
protocols: Protocols to match or ``None`` for any.
|
|
1373
|
+
|
|
1374
|
+
"""
|
|
1375
|
+
for reg in list(self._matching(url, protocols)):
|
|
1376
|
+
reg.on_close(code, reason, was_clean)
|
|
1377
|
+
with contextlib.suppress(ValueError):
|
|
1378
|
+
self._registrations.remove(reg)
|
|
1379
|
+
|
|
1380
|
+
def sent_frames(self, url: str, protocols: tuple[str, ...] | None = None) -> list[str]:
|
|
1381
|
+
"""Return payloads sent via matching WebSocket registrations.
|
|
1382
|
+
|
|
1383
|
+
Args:
|
|
1384
|
+
url: WebSocket URL.
|
|
1385
|
+
protocols: Protocols to match or ``None`` for any.
|
|
1386
|
+
|
|
1387
|
+
Returns:
|
|
1388
|
+
Concatenated list of sent text frames.
|
|
1389
|
+
|
|
1390
|
+
"""
|
|
1391
|
+
frames: list[str] = []
|
|
1392
|
+
for reg in self._matching(url, protocols):
|
|
1393
|
+
frames.extend(reg.sent)
|
|
1394
|
+
return frames
|