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,62 @@
1
+ """Testing utilities for WebComPy applications.
2
+
3
+ LLM-friendly documentation is published at https://webcompy.net/llms.txt
4
+ (compact: https://webcompy.net/llms-small.txt, full: https://webcompy.net/llms-full.txt).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from webcompy_server.ports import VirtualDOMEvent
10
+ from webcompy_testing._app import mock_app_run
11
+ from webcompy_testing._asgi import (
12
+ create_test_asgi_app,
13
+ format_html,
14
+ )
15
+ from webcompy_testing._asgi import (
16
+ render_app_html_sync as render_app_html,
17
+ )
18
+ from webcompy_testing._dom import FakeDOMNode
19
+ from webcompy_testing._ports import (
20
+ FakeAsyncSchedulerPort,
21
+ FakeBrowserDOMPort,
22
+ FakeBrowserFFIPort,
23
+ FakeBrowserHostPort,
24
+ FakeCustomElementPort,
25
+ FakeEventSourcePort,
26
+ FakeFetchPort,
27
+ FakeHistoryPort,
28
+ FakeMediaQueryPort,
29
+ FakeTransitionPort,
30
+ FakeWebSocketPort,
31
+ RecordedRequest,
32
+ )
33
+ from webcompy_testing._renderer import TestRenderer, TestRendererResult
34
+ from webcompy_testing._restore import restore_signal_values
35
+ from webcompy_testing._scope import create_test_app
36
+ from webcompy_testing._utils import run_sync
37
+
38
+ __all__ = [
39
+ "FakeAsyncSchedulerPort",
40
+ "FakeBrowserDOMPort",
41
+ "FakeBrowserFFIPort",
42
+ "FakeBrowserHostPort",
43
+ "FakeCustomElementPort",
44
+ "FakeDOMNode",
45
+ "FakeEventSourcePort",
46
+ "FakeFetchPort",
47
+ "FakeHistoryPort",
48
+ "FakeMediaQueryPort",
49
+ "FakeTransitionPort",
50
+ "FakeWebSocketPort",
51
+ "RecordedRequest",
52
+ "TestRenderer",
53
+ "TestRendererResult",
54
+ "VirtualDOMEvent",
55
+ "create_test_app",
56
+ "create_test_asgi_app",
57
+ "format_html",
58
+ "mock_app_run",
59
+ "render_app_html",
60
+ "restore_signal_values",
61
+ "run_sync",
62
+ ]
@@ -0,0 +1,34 @@
1
+ """Context manager for mocking ``WebComPyApp.run`` in tests."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterator
6
+ from contextlib import contextmanager
7
+ from typing import TYPE_CHECKING
8
+
9
+ from webcompy.app._app import WebComPyApp
10
+
11
+ if TYPE_CHECKING:
12
+ from collections.abc import Callable
13
+ from typing import Any
14
+
15
+
16
+ @contextmanager
17
+ def mock_app_run() -> Iterator[None]:
18
+ """Suppress ``WebComPyApp.run`` inside the context.
19
+
20
+ Yields:
21
+ None: Control to the caller while ``WebComPyApp.run`` is replaced
22
+ with a no-op; the original method is restored on exit.
23
+
24
+ """
25
+ original: Callable[..., Any] = WebComPyApp.run
26
+
27
+ def _noop(self: object) -> None:
28
+ pass
29
+
30
+ WebComPyApp.run = _noop # type: ignore[method-assign]
31
+ try:
32
+ yield
33
+ finally:
34
+ WebComPyApp.run = original # type: ignore[method-assign]
@@ -0,0 +1,109 @@
1
+ """ASGI test helpers for rendering WebComPy apps to HTML."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING, Any
6
+
7
+ from starlette.applications import Starlette
8
+ from starlette.responses import HTMLResponse
9
+ from starlette.routing import Route
10
+
11
+ from webcompy.di import inject
12
+ from webcompy.ports._keys import ASYNC_SCHEDULER_PORT_KEY
13
+ from webcompy_server import configure_server_context
14
+ from webcompy_server._html import _HtmlElement
15
+ from webcompy_testing._utils import run_sync
16
+
17
+ if TYPE_CHECKING:
18
+ from starlette.requests import Request
19
+ from starlette.types import ASGIApp
20
+
21
+ from webcompy.app._app import WebComPyApp
22
+
23
+
24
+ def format_html(html: str) -> str:
25
+ """Format raw HTML for readable output.
26
+
27
+ Args:
28
+ html: Raw HTML string to format.
29
+
30
+ Returns:
31
+ Pretty-printed HTML string produced by BeautifulSoup.
32
+
33
+ """
34
+ from bs4 import BeautifulSoup
35
+
36
+ soup = BeautifulSoup(html, "html.parser")
37
+ return str(soup)
38
+
39
+
40
+ async def render_app_html(app: WebComPyApp, path: str = "/", **kwargs: Any) -> str:
41
+ from webcompy_server._html import generate_html
42
+
43
+ configure_server_context(app)
44
+ ctx = app.create_render_context(path)
45
+ try:
46
+ scheduler = inject(ASYNC_SCHEDULER_PORT_KEY)
47
+ await scheduler.await_pending()
48
+ return await generate_html(ctx, **kwargs)
49
+ finally:
50
+ ctx.dispose()
51
+
52
+
53
+ def render_app_html_sync(app: WebComPyApp, path: str = "/", **kwargs: Any) -> str:
54
+ """Render an app to an HTML string synchronously.
55
+
56
+ Args:
57
+ app: Application to render.
58
+ path: Route path to render.
59
+ **kwargs: Additional options forwarded to ``generate_html``.
60
+
61
+ Returns:
62
+ Rendered HTML string for the requested path.
63
+
64
+ """
65
+ return run_sync(render_app_html(app, path, **kwargs))
66
+
67
+
68
+ def create_test_asgi_app(app: WebComPyApp) -> ASGIApp:
69
+ """Create a Starlette ASGI app that renders the WebComPy app.
70
+
71
+ Args:
72
+ app: Application to serve via the test ASGI app.
73
+
74
+ Returns:
75
+ An ``ASGIApp`` that renders the WebComPy app for incoming requests.
76
+
77
+ """
78
+
79
+ configure_server_context(app)
80
+
81
+ if app.router_mode == "history" and app.routes:
82
+
83
+ async def _send_html(request: Request) -> HTMLResponse:
84
+ path: str = request.path_params.get("path", "")
85
+ ctx = app.create_render_context(path.strip("/"))
86
+ try:
87
+ scheduler = inject(ASYNC_SCHEDULER_PORT_KEY)
88
+ await scheduler.await_pending()
89
+ html = await _HtmlElement("div", {}, ctx._root).render_html()
90
+ return HTMLResponse(html)
91
+ finally:
92
+ ctx.dispose()
93
+
94
+ html_route = Route("/{path:path}", _send_html)
95
+ else:
96
+
97
+ async def _send_html_static(_: Request) -> HTMLResponse:
98
+ ctx = app.create_render_context("/")
99
+ try:
100
+ scheduler = inject(ASYNC_SCHEDULER_PORT_KEY)
101
+ await scheduler.await_pending()
102
+ html = await _HtmlElement("div", {}, ctx._root).render_html()
103
+ return HTMLResponse(html)
104
+ finally:
105
+ ctx.dispose()
106
+
107
+ html_route = Route("/", _send_html_static)
108
+
109
+ return Starlette(routes=[html_route])
@@ -0,0 +1,149 @@
1
+ """Fake DOM node for browserless component testing."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from webcompy.elements.types._base import _utf16_length
6
+ from webcompy_server.ports import VirtualDOMNode
7
+
8
+
9
+ class FakeDOMNode(VirtualDOMNode):
10
+ """Provide a test double for ``VirtualDOMNode`` with write tracking.
11
+
12
+ Args:
13
+ tag: Tag name for the node.
14
+ text_content: Initial text content for text/comment nodes.
15
+ node_type: Explicit DOM node type override.
16
+
17
+ Attributes:
18
+ textContent_write_count: Number of times ``textContent`` was
19
+ written on this node.
20
+ setAttribute_count: Number of times ``setAttribute`` was called
21
+ on this node.
22
+
23
+ """
24
+
25
+ def __init__(self, tag: str = "div", text_content: str | None = None, *, node_type: int | None = None) -> None:
26
+ if node_type is None:
27
+ node_type = 8 if tag.startswith("#comment") else (3 if tag.startswith("#text") else 1)
28
+ super().__init__(tag, node_type=node_type, text_content=text_content)
29
+ self.__webcompy_prerendered_node__: bool = False
30
+ self.textContent_write_count: int = 0
31
+ self.setAttribute_count: int = 0
32
+
33
+ def setAttribute(self, name: str, value: str | None) -> None:
34
+ """Assign an attribute and increment the write counter.
35
+
36
+ Args:
37
+ name: Attribute name.
38
+ value: Attribute value or ``None`` to remove the attribute.
39
+
40
+ """
41
+ super().setAttribute(name, value)
42
+ self.setAttribute_count += 1
43
+
44
+ def splitText(self, offset: int) -> FakeDOMNode:
45
+ """Split a text node at a UTF-16 offset and insert the remainder.
46
+
47
+ Args:
48
+ offset: UTF-16 code-unit offset at which to split.
49
+
50
+ Returns:
51
+ The newly created sibling text node containing the tail.
52
+
53
+ Raises:
54
+ TypeError: If the node is not a text node.
55
+ IndexError: If ``offset`` is out of range.
56
+
57
+ """
58
+ if self._node_type != 3:
59
+ raise TypeError("splitText is only valid on text nodes")
60
+ text = self._text_content or ""
61
+ length = _utf16_length(text)
62
+ if not 0 <= offset <= length:
63
+ raise IndexError(f"splitText offset {offset} out of range for text of length {length}")
64
+ encoded = text.encode("utf-16-le", "surrogatepass")
65
+ boundary = offset * 2
66
+ new_node = FakeDOMNode(
67
+ "#text",
68
+ text_content=encoded[boundary:].decode("utf-16-le", "surrogatepass"),
69
+ )
70
+ self._text_content = encoded[:boundary].decode("utf-16-le", "surrogatepass")
71
+ parent = self._parent
72
+ if parent is not None:
73
+ siblings = parent._children
74
+ idx = siblings.index(self)
75
+ if idx + 1 < len(siblings):
76
+ parent.insertBefore(new_node, siblings[idx + 1])
77
+ else:
78
+ parent.appendChild(new_node)
79
+ return new_node
80
+
81
+ @VirtualDOMNode.textContent.setter # type: ignore[attr-defined]
82
+ def textContent(self, value: str | None) -> None:
83
+ VirtualDOMNode.textContent.fset(self, value) # type: ignore[misc]
84
+ self.textContent_write_count += 1
85
+
86
+ def __setattr__(self, name: str, value: object) -> None:
87
+ if name == "__webcompy_prerendered_node__" and value:
88
+ object.__setattr__(self, "_webcompy_node", False)
89
+ if name == "innerHTML":
90
+ VirtualDOMNode.__setattr__(self, name, value)
91
+ return
92
+ if (
93
+ name.startswith("_VirtualDOMNode__")
94
+ or name in ("__webcompy_node__", "__webcompy_prerendered_node__")
95
+ or name in ("textContent_write_count", "setAttribute_count")
96
+ or name
97
+ in {
98
+ "nodeName",
99
+ "nodeType",
100
+ "textContent",
101
+ "childNodes",
102
+ "firstChild",
103
+ "lastChild",
104
+ "parentNode",
105
+ "attributes",
106
+ "innerHTML",
107
+ "outerHTML",
108
+ }
109
+ or name.startswith("_")
110
+ ):
111
+ object.__setattr__(self, name, value)
112
+ else:
113
+ super().__setattr__(name, value)
114
+
115
+ def __getattribute__(self, name: str) -> object:
116
+ if name == "innerHTML":
117
+ try:
118
+ return object.__getattribute__(self, "_innerHTML")
119
+ except AttributeError:
120
+ return None
121
+ return object.__getattribute__(self, name)
122
+
123
+ def focus(self) -> None:
124
+ """Simulate focusing this node by updating the containing document's active element.
125
+
126
+ The active element is tracked on the nearest ancestor that holds
127
+ ``__webcompy_document_root__`` (the fake document).
128
+
129
+ """
130
+ node: object | None = self
131
+ while node is not None:
132
+ if isinstance(node, VirtualDOMNode):
133
+ parent = node.parentNode
134
+ if getattr(node, "__webcompy_document_root__", False):
135
+ object.__setattr__(node, "_fake_active_element", self)
136
+ return
137
+ node = parent
138
+ else:
139
+ break
140
+
141
+ def __getattr__(self, name: str) -> object:
142
+ if name.startswith("_VirtualDOMNode__"):
143
+ raise AttributeError(name)
144
+ if name == "isConnected":
145
+ return self.isConnected
146
+ try:
147
+ return self._dom_properties[name]
148
+ except KeyError:
149
+ return object.__getattribute__(self, name)