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.
@@ -0,0 +1,359 @@
1
+ """Test renderer for mounting WebComPy components in a fake DOM."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import contextvars
6
+ from typing import TYPE_CHECKING
7
+
8
+ from webcompy import logging
9
+ from webcompy.di._scope import DIScope, _active_di_scope
10
+ from webcompy.ports._keys import (
11
+ ASYNC_SCHEDULER_PORT_KEY,
12
+ CUSTOM_ELEMENT_PORT_KEY,
13
+ DOM_PORT_KEY,
14
+ EVENT_SOURCE_PORT_KEY,
15
+ FFI_PORT_KEY,
16
+ HOST_PORT_KEY,
17
+ MEDIA_QUERY_PORT_KEY,
18
+ TRANSITION_PORT_KEY,
19
+ WEBSOCKET_PORT_KEY,
20
+ )
21
+ from webcompy_server.ports import VirtualDOMNode
22
+ from webcompy_testing._asgi import format_html
23
+ from webcompy_testing._ports import (
24
+ FakeAsyncSchedulerPort,
25
+ FakeBrowserDOMPort,
26
+ FakeBrowserFFIPort,
27
+ FakeBrowserHostPort,
28
+ FakeCustomElementPort,
29
+ FakeEventSourcePort,
30
+ FakeMediaQueryPort,
31
+ FakeTransitionPort,
32
+ FakeWebSocketPort,
33
+ )
34
+ from webcompy_testing._utils import run_sync
35
+
36
+ if TYPE_CHECKING:
37
+ from webcompy.components._generator import ComponentGenerator
38
+
39
+
40
+ class TestRendererResult:
41
+ """Hold the rendered component tree and its DI scope.
42
+
43
+ Provides query helpers and accessors for fake ports installed during
44
+ rendering.
45
+
46
+ Args:
47
+ component: Component generator that was rendered.
48
+ instance: Root component instance.
49
+ parent_node: Virtual DOM parent node containing the mounted tree.
50
+ scope: DI scope used for the render.
51
+ di_token: Token for resetting the active DI scope, or ``None``.
52
+
53
+ Attributes:
54
+ body_node: Fake document body node, or ``None`` when no fake DOM
55
+ port is installed.
56
+ transition_port: ``FakeTransitionPort`` installed for the render,
57
+ or ``None``.
58
+ media_query_port: ``FakeMediaQueryPort`` installed for the
59
+ render, or ``None``.
60
+ event_source_port: ``FakeEventSourcePort`` installed for the
61
+ render, or ``None``.
62
+ websocket_port: ``FakeWebSocketPort`` installed for the render,
63
+ or ``None``.
64
+
65
+ """
66
+
67
+ __slots__ = ("_component", "_di_token", "_instance", "_parent_node", "_scope")
68
+
69
+ def __init__(
70
+ self,
71
+ component: ComponentGenerator,
72
+ instance: object,
73
+ parent_node: VirtualDOMNode,
74
+ scope: DIScope,
75
+ di_token: contextvars.Token | None = None,
76
+ ) -> None:
77
+ self._component = component
78
+ self._instance = instance
79
+ self._parent_node = parent_node
80
+ self._scope = scope
81
+ self._di_token = di_token
82
+
83
+ @property
84
+ def _root_node(self) -> VirtualDOMNode:
85
+ return self._parent_node.childNodes[0] if self._parent_node.childNodes.length > 0 else self._parent_node # type: ignore[return-value]
86
+
87
+ def query_selector(self, tag: str) -> VirtualDOMNode | None:
88
+ """Return the first node with the given tag.
89
+
90
+ Args:
91
+ tag: Tag name to search for.
92
+
93
+ Returns:
94
+ The first matching node or ``None``.
95
+
96
+ """
97
+ return _dfs_first(self._root_node, tag)
98
+
99
+ def query_selector_all(self, tag: str) -> list[VirtualDOMNode]:
100
+ """Return all nodes with the given tag.
101
+
102
+ Args:
103
+ tag: Tag name to search for.
104
+
105
+ Returns:
106
+ List of matching nodes.
107
+
108
+ """
109
+ return _dfs_all(self._root_node, tag)
110
+
111
+ def find_by_text(self, text: str) -> VirtualDOMNode | None:
112
+ """Find a node by exact text content.
113
+
114
+ Args:
115
+ text: Text to match against ``textContent``.
116
+
117
+ Returns:
118
+ The first matching node or ``None``.
119
+
120
+ """
121
+ return _dfs_text(self._root_node, text)
122
+
123
+ def find_by_attribute(self, name: str, value: str) -> VirtualDOMNode | None:
124
+ """Find a node by attribute value.
125
+
126
+ Args:
127
+ name: Attribute name.
128
+ value: Expected attribute value.
129
+
130
+ Returns:
131
+ The first matching node or ``None``.
132
+
133
+ """
134
+ return _dfs_attr(self._root_node, name, value)
135
+
136
+ def to_html(self, *, pretty: bool = False) -> str:
137
+ """Render the mounted tree to an HTML string.
138
+
139
+ Args:
140
+ pretty: Whether to pretty-print the HTML.
141
+
142
+ Returns:
143
+ HTML string for the mounted component tree.
144
+
145
+ """
146
+ from webcompy_server.ports._dom import ServerDOMPort
147
+
148
+ server_port = ServerDOMPort()
149
+ html = server_port.render_html(self._root_node)
150
+ if pretty:
151
+ return format_html(html)
152
+ return html
153
+
154
+ def assert_element_count(self, tag: str, count: int) -> None:
155
+ """Assert that ``count`` elements with ``tag`` exist.
156
+
157
+ Args:
158
+ tag: Tag name to count.
159
+ count: Expected number of elements.
160
+
161
+ """
162
+ actual = len(self.query_selector_all(tag))
163
+ assert actual == count, f"Expected {count} <{tag}> elements, found {actual}"
164
+
165
+ def assert_has_class(self, cls: str) -> None:
166
+ """Assert that the root element contains a CSS class.
167
+
168
+ Args:
169
+ cls: Class name expected on the root element.
170
+
171
+ """
172
+ class_attr = self._root_node.getAttribute("class")
173
+ assert class_attr is not None and cls in class_attr.split(), f"Root element does not have class '{cls}'"
174
+
175
+ def __enter__(self) -> TestRendererResult:
176
+ return self
177
+
178
+ def __exit__(self, *args: object) -> None:
179
+ self.close()
180
+
181
+ def close(self) -> None:
182
+ """Dispose the DI scope and reset the active scope token."""
183
+ self._scope.dispose()
184
+ if self._di_token is not None:
185
+ try:
186
+ _active_di_scope.reset(self._di_token)
187
+ except (ValueError, LookupError) as err:
188
+ logging.warning(
189
+ "TestRendererResult.close() called from a different context "
190
+ "than render(); DI scope token cannot be reset: %s",
191
+ err,
192
+ )
193
+
194
+ @property
195
+ def body_node(self) -> VirtualDOMNode | None:
196
+ """Return the fake document body node."""
197
+ dom = self._scope.inject(DOM_PORT_KEY, default=None)
198
+ if isinstance(dom, FakeBrowserDOMPort):
199
+ return dom.body
200
+ return None
201
+
202
+ @property
203
+ def transition_port(self) -> FakeTransitionPort | None:
204
+ """Return the ``FakeTransitionPort`` installed for the render."""
205
+ return self._scope.inject(TRANSITION_PORT_KEY, default=None)
206
+
207
+ @property
208
+ def media_query_port(self) -> FakeMediaQueryPort | None:
209
+ """Return the ``FakeMediaQueryPort`` installed for the render."""
210
+ return self._scope.inject(MEDIA_QUERY_PORT_KEY, default=None)
211
+
212
+ @property
213
+ def event_source_port(self) -> FakeEventSourcePort | None:
214
+ """Return the ``FakeEventSourcePort`` installed for the render."""
215
+ return self._scope.inject(EVENT_SOURCE_PORT_KEY, default=None)
216
+
217
+ @property
218
+ def websocket_port(self) -> FakeWebSocketPort | None:
219
+ """Return the ``FakeWebSocketPort`` installed for the render."""
220
+ return self._scope.inject(WEBSOCKET_PORT_KEY, default=None)
221
+
222
+
223
+ class TestRenderer:
224
+ """Mount WebComPy components into a fake DOM for assertions.
225
+
226
+ See https://webcompy.net/llms.txt for LLM-readable testing docs.
227
+ """
228
+
229
+ @staticmethod
230
+ def render(
231
+ component: ComponentGenerator,
232
+ *,
233
+ parent_scope: DIScope | None = None,
234
+ ) -> TestRendererResult:
235
+ """Render a component into an isolated fake DOM.
236
+
237
+ Args:
238
+ component: Component generator to mount.
239
+ parent_scope: Optional parent DI scope for the render.
240
+
241
+ Returns:
242
+ A ``TestRendererResult`` holding the mounted tree and scopes.
243
+
244
+ """
245
+
246
+ async def _render_async() -> tuple[object, VirtualDOMNode, DIScope]:
247
+ from webcompy.components._component import HeadPropsStore
248
+ from webcompy.components._generator import (
249
+ ComponentStore,
250
+ _register_deferred_components,
251
+ )
252
+ from webcompy.di._keys import (
253
+ _COMPONENT_STORE_KEY,
254
+ _HEAD_PROPS_KEY,
255
+ _TELEPORT_REGISTRY_KEY,
256
+ )
257
+ from webcompy.elements.types._teleport import _TeleportTargetRegistry
258
+
259
+ scope = DIScope(parent=parent_scope)
260
+ fake_scheduler = FakeAsyncSchedulerPort()
261
+ scope.provide(ASYNC_SCHEDULER_PORT_KEY, fake_scheduler)
262
+ dom_port = FakeBrowserDOMPort()
263
+ scope.provide(DOM_PORT_KEY, dom_port)
264
+ scope.provide(HOST_PORT_KEY, FakeBrowserHostPort(dom_port))
265
+ scope.provide(FFI_PORT_KEY, FakeBrowserFFIPort())
266
+ scope.provide(CUSTOM_ELEMENT_PORT_KEY, FakeCustomElementPort())
267
+ scope.provide(EVENT_SOURCE_PORT_KEY, FakeEventSourcePort())
268
+ scope.provide(TRANSITION_PORT_KEY, FakeTransitionPort())
269
+ scope.provide(MEDIA_QUERY_PORT_KEY, FakeMediaQueryPort())
270
+ scope.provide(WEBSOCKET_PORT_KEY, FakeWebSocketPort())
271
+ scope.provide(_HEAD_PROPS_KEY, HeadPropsStore())
272
+ scope.provide(_COMPONENT_STORE_KEY, ComponentStore())
273
+ scope.provide(_TELEPORT_REGISTRY_KEY, _TeleportTargetRegistry())
274
+
275
+ _active_di_scope.set(scope)
276
+ _register_deferred_components()
277
+
278
+ root_node = VirtualDOMNode("div")
279
+ root_node.__webcompy_node__ = False
280
+ root_node.__webcompy_prerendered_node__ = True
281
+ dom_port._body.appendChild(root_node)
282
+
283
+ class _DummyParent:
284
+ def __init__(self, node):
285
+ self._node = node
286
+
287
+ def _get_node(self):
288
+ return self._node
289
+
290
+ def _get_belonging_component(self):
291
+ return ""
292
+
293
+ def _get_belonging_components(self):
294
+ return ()
295
+
296
+ def _re_index_children(self, recursive):
297
+ pass
298
+
299
+ instance = component(None)
300
+ instance._parent = _DummyParent(root_node) # type: ignore[assignment]
301
+ instance._node_idx = 0
302
+ await instance._render()
303
+ await fake_scheduler.await_pending()
304
+
305
+ return instance, root_node, scope
306
+
307
+ ctx = contextvars.copy_context()
308
+ instance, root_node, scope = ctx.run(run_sync, _render_async())
309
+ di_token = _active_di_scope.set(scope)
310
+ return TestRendererResult(component, instance, root_node, scope, di_token)
311
+
312
+
313
+ def _dfs_first(node: VirtualDOMNode, tag: str) -> VirtualDOMNode | None:
314
+ tag_upper = tag.upper()
315
+ if node.nodeName == tag_upper:
316
+ return node
317
+ for i in range(node.childNodes.length):
318
+ child = node.childNodes[i]
319
+ if isinstance(child, VirtualDOMNode):
320
+ result = _dfs_first(child, tag)
321
+ if result is not None:
322
+ return result
323
+ return None
324
+
325
+
326
+ def _dfs_all(node: VirtualDOMNode, tag: str) -> list[VirtualDOMNode]:
327
+ results: list[VirtualDOMNode] = []
328
+ tag_upper = tag.upper()
329
+ if node.nodeName == tag_upper:
330
+ results.append(node)
331
+ for i in range(node.childNodes.length):
332
+ child = node.childNodes[i]
333
+ if isinstance(child, VirtualDOMNode):
334
+ results.extend(_dfs_all(child, tag))
335
+ return results
336
+
337
+
338
+ def _dfs_text(node: VirtualDOMNode, text: str) -> VirtualDOMNode | None:
339
+ if node.nodeType != 8 and node.textContent == text:
340
+ return node
341
+ for i in range(node.childNodes.length):
342
+ child = node.childNodes[i]
343
+ if isinstance(child, VirtualDOMNode):
344
+ result = _dfs_text(child, text)
345
+ if result is not None:
346
+ return result
347
+ return None
348
+
349
+
350
+ def _dfs_attr(node: VirtualDOMNode, name: str, value: str) -> VirtualDOMNode | None:
351
+ if node.getAttribute(name) == value:
352
+ return node
353
+ for i in range(node.childNodes.length):
354
+ child = node.childNodes[i]
355
+ if isinstance(child, VirtualDOMNode):
356
+ result = _dfs_attr(child, name, value)
357
+ if result is not None:
358
+ return result
359
+ return None
@@ -0,0 +1,62 @@
1
+ """Signal value restoration helpers for hydration testing."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from logging import getLogger
6
+ from typing import Any
7
+
8
+ _logger = getLogger(__name__)
9
+
10
+
11
+ def _get_component_id(component: Any) -> str:
12
+ prop = getattr(component, "_property", None)
13
+ if isinstance(prop, dict):
14
+ return str(prop.get("component_id", ""))
15
+ return ""
16
+
17
+
18
+ def restore_signal_values(
19
+ component: Any,
20
+ signals_data: dict[str, Any] | None,
21
+ ) -> None:
22
+ """Restore signal values for testing round-trip scenarios.
23
+
24
+ Directly assigns each value to ``signal._value`` without re-decoding
25
+ or triggering reactive notifications. Intended for use in test code
26
+ that manually constructs signal members and hydration data; not part
27
+ of the production hydration pipeline (which uses factory-skip via
28
+ ``use_state()`` / ``use_reactive_list()`` / ``use_reactive_dict()``).
29
+
30
+ Callers that construct signals_data by hand should run ``decode()``
31
+ on each value before passing it in.
32
+
33
+ Args:
34
+ component: Component instance exposing ``__signal_members__``;
35
+ values are assigned to the signals found there.
36
+ signals_data: Mapping of signal attribute names to already-decoded
37
+ values. ``None`` or empty skips restoration entirely.
38
+
39
+ """
40
+ if not signals_data:
41
+ return
42
+ members = getattr(component, "__signal_members__", None)
43
+ if not members:
44
+ return
45
+ component_id = _get_component_id(component)
46
+ for attr_name, value in signals_data.items():
47
+ signal = members.get(attr_name)
48
+ if signal is None:
49
+ _logger.debug(
50
+ "Skipping signal restore for %s.%s: not in __signal_members__",
51
+ component_id,
52
+ attr_name,
53
+ )
54
+ continue
55
+ try:
56
+ signal._value = value
57
+ except Exception:
58
+ _logger.exception(
59
+ "Failed to restore signal value for %s.%s",
60
+ component_id,
61
+ attr_name,
62
+ )
@@ -0,0 +1,35 @@
1
+ """Test application factory for WebComPy components."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING, Any
6
+
7
+ from webcompy.app._app import WebComPyApp
8
+ from webcompy.app._config import WebComPyAppConfig
9
+ from webcompy_server import configure_server_context
10
+
11
+ if TYPE_CHECKING:
12
+ from webcompy.components._generator import ComponentGenerator
13
+
14
+
15
+ def create_test_app(
16
+ *,
17
+ root_component: ComponentGenerator,
18
+ **config_overrides: Any,
19
+ ) -> WebComPyApp:
20
+ """Create a ``WebComPyApp`` configured for testing.
21
+
22
+ Args:
23
+ root_component: Root component for the test app.
24
+ **config_overrides: Fields forwarded to ``WebComPyAppConfig``.
25
+
26
+ Returns:
27
+ A configured ``WebComPyApp`` ready for server-side rendering.
28
+
29
+ """
30
+ valid_fields = set(WebComPyAppConfig.__dataclass_fields__.keys())
31
+ config_kwargs: dict[str, Any] = {k: v for k, v in config_overrides.items() if k in valid_fields}
32
+ config = WebComPyAppConfig(**config_kwargs)
33
+ app = WebComPyApp(root_component=root_component, config=config)
34
+ configure_server_context(app)
35
+ return app
@@ -0,0 +1,30 @@
1
+ """Async execution helpers for synchronous test contexts."""
2
+
3
+ import asyncio
4
+ from collections.abc import Coroutine
5
+ from typing import Any, TypeVar
6
+
7
+ T = TypeVar("T")
8
+
9
+
10
+ def run_sync(coro: Coroutine[Any, Any, T]) -> T:
11
+ """Run a coroutine, handling nested event loops from pytest-asyncio.
12
+
13
+ Args:
14
+ coro: Coroutine to execute.
15
+
16
+ Returns:
17
+ The coroutine's result.
18
+
19
+ """
20
+ try:
21
+ loop = asyncio.get_running_loop()
22
+ except RuntimeError:
23
+ return asyncio.run(coro)
24
+ else:
25
+ import nest_asyncio2
26
+
27
+ if not getattr(loop, "_nest_asyncio_patched", False):
28
+ nest_asyncio2.apply(loop)
29
+ loop._nest_asyncio_patched = True # type: ignore[attr-defined]
30
+ return loop.run_until_complete(coro)
@@ -0,0 +1,25 @@
1
+ """Browser-side test runner package executed inside the harness PyScript page."""
2
+
3
+ from webcompy_testing.browser_runner._runner import (
4
+ UnknownFixtureError,
5
+ bootstrap,
6
+ evaluate,
7
+ normalize_traceback,
8
+ parse_test_id,
9
+ resolve_parametrize_payload,
10
+ resolve_qualname_target,
11
+ run_one,
12
+ skip,
13
+ )
14
+
15
+ __all__ = [
16
+ "UnknownFixtureError",
17
+ "bootstrap",
18
+ "evaluate",
19
+ "normalize_traceback",
20
+ "parse_test_id",
21
+ "resolve_parametrize_payload",
22
+ "resolve_qualname_target",
23
+ "run_one",
24
+ "skip",
25
+ ]