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,480 @@
|
|
|
1
|
+
"""In-page test runner executing browser test functions inside a real PyScript runtime."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import importlib
|
|
6
|
+
import importlib.util
|
|
7
|
+
import inspect
|
|
8
|
+
import io
|
|
9
|
+
import json
|
|
10
|
+
import re
|
|
11
|
+
import sys
|
|
12
|
+
import time
|
|
13
|
+
import traceback
|
|
14
|
+
from contextlib import redirect_stderr, redirect_stdout, suppress
|
|
15
|
+
from dataclasses import dataclass
|
|
16
|
+
from types import ModuleType
|
|
17
|
+
from typing import Any, cast
|
|
18
|
+
|
|
19
|
+
from webcompy.app import WebComPyApp, WebComPyAppConfig
|
|
20
|
+
from webcompy.components import define_component
|
|
21
|
+
from webcompy.di import inject
|
|
22
|
+
from webcompy.ports._browser._ffi import BrowserFFIPort
|
|
23
|
+
from webcompy.ports._keys import ASYNC_SCHEDULER_PORT_KEY, FFI_PORT_KEY
|
|
24
|
+
from webcompy.utils import ENVIRONMENT
|
|
25
|
+
|
|
26
|
+
_MANIFEST_URL = "/_webcompy-test/manifest.json"
|
|
27
|
+
_PARAM_SUFFIX_RE = re.compile(r"\[p(\d+)\]$")
|
|
28
|
+
_DISPLAY_ID_SUFFIX_RE = re.compile(r"\[[^\[\]]*\]$")
|
|
29
|
+
_FIXTURE_NAMES = ("app", "dom_root")
|
|
30
|
+
_TESTS_MOUNT_ROOT = "/home/pyodide/tests/browser/"
|
|
31
|
+
_WC_SRC_MOUNT_ROOT = "/home/pyodide/_wc_src/"
|
|
32
|
+
_TB_REWRITES: tuple[tuple[str, str], ...] = (
|
|
33
|
+
(_TESTS_MOUNT_ROOT, "tests/browser/"),
|
|
34
|
+
(f"{_WC_SRC_MOUNT_ROOT}webcompy/", "packages/webcompy/src/webcompy/"),
|
|
35
|
+
(
|
|
36
|
+
f"{_WC_SRC_MOUNT_ROOT}webcompy_testing/",
|
|
37
|
+
"packages/webcompy-testing/src/webcompy_testing/",
|
|
38
|
+
),
|
|
39
|
+
(
|
|
40
|
+
f"{_WC_SRC_MOUNT_ROOT}webcompy_server/",
|
|
41
|
+
"packages/webcompy-server/src/webcompy_server/",
|
|
42
|
+
),
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class UnknownFixtureError(NameError):
|
|
47
|
+
"""Raised when a browser test declares a parameter outside the fixture registry."""
|
|
48
|
+
|
|
49
|
+
def __init__(self, name: str) -> None:
|
|
50
|
+
super().__init__(f"unknown fixture '{name}'; available fixtures: {', '.join(_FIXTURE_NAMES)}")
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class _Skipped(Exception):
|
|
54
|
+
pass
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@dataclass
|
|
58
|
+
class _ShimMark:
|
|
59
|
+
name: str
|
|
60
|
+
args: tuple[Any, ...]
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _shim_parametrize(argnames: Any, values: list[Any]):
|
|
64
|
+
def decorate(func):
|
|
65
|
+
existing = getattr(func, "pytestmark", [])
|
|
66
|
+
func.pytestmark = [*existing, _ShimMark("parametrize", (argnames, values))]
|
|
67
|
+
return func
|
|
68
|
+
|
|
69
|
+
return decorate
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _shim_skip(reason: str = "") -> None:
|
|
73
|
+
raise _Skipped(reason or "skipped")
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _shim_fail(message: str = "") -> None:
|
|
77
|
+
raise AssertionError(message)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _build_pytest_shim() -> ModuleType:
|
|
81
|
+
mark = ModuleType("pytest.mark")
|
|
82
|
+
mark.parametrize = _shim_parametrize # type: ignore[attr-defined]
|
|
83
|
+
shim = ModuleType("pytest")
|
|
84
|
+
shim.mark = mark # type: ignore[attr-defined]
|
|
85
|
+
shim.skip = _shim_skip # type: ignore[attr-defined]
|
|
86
|
+
shim.fail = _shim_fail # type: ignore[attr-defined]
|
|
87
|
+
return shim
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _ensure_pytest_shim() -> None:
|
|
91
|
+
if ENVIRONMENT != "pyscript":
|
|
92
|
+
return
|
|
93
|
+
if "pytest" in sys.modules or importlib.util.find_spec("pytest") is not None:
|
|
94
|
+
return
|
|
95
|
+
sys.modules["pytest"] = _build_pytest_shim()
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
@define_component()
|
|
99
|
+
def BrowserTestDefaultRoot(context):
|
|
100
|
+
from webcompy.elements import html
|
|
101
|
+
|
|
102
|
+
return html.DIV({})
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _make_default_app() -> WebComPyApp:
|
|
106
|
+
"""Create a fresh application instance for tests without a ``get_app`` hook.
|
|
107
|
+
|
|
108
|
+
A new ``WebComPyApp`` per test keeps app-owned state (RPC procedure
|
|
109
|
+
registry, deferred operations, plugin manager) from leaking between
|
|
110
|
+
test executions sharing the harness interpreter.
|
|
111
|
+
"""
|
|
112
|
+
return WebComPyApp(
|
|
113
|
+
root_component=BrowserTestDefaultRoot,
|
|
114
|
+
config=WebComPyAppConfig(),
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
class _TrackingFFIPort(BrowserFFIPort):
|
|
119
|
+
def __init__(self) -> None:
|
|
120
|
+
super().__init__()
|
|
121
|
+
self._proxies: list[Any] = []
|
|
122
|
+
|
|
123
|
+
def create_proxy(self, obj: Any) -> Any:
|
|
124
|
+
proxy = super().create_proxy(obj)
|
|
125
|
+
self._proxies.append(proxy)
|
|
126
|
+
return proxy
|
|
127
|
+
|
|
128
|
+
def destroy_all(self) -> None:
|
|
129
|
+
for proxy in self._proxies:
|
|
130
|
+
with suppress(Exception):
|
|
131
|
+
self.destroy_proxy(proxy)
|
|
132
|
+
self._proxies.clear()
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
_console_start_index = 0
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def bootstrap() -> None:
|
|
139
|
+
"""Expose ``run_one`` / ``evaluate`` on ``window`` and mark the harness page ready."""
|
|
140
|
+
global _console_start_index
|
|
141
|
+
_ensure_pytest_shim()
|
|
142
|
+
ffi = importlib.import_module("pyscript").ffi
|
|
143
|
+
js = importlib.import_module("js")
|
|
144
|
+
js.window.__webcompy_test__ = ffi.create_proxy({"run_one": run_one, "evaluate": evaluate})
|
|
145
|
+
js.document.documentElement.setAttribute("data-webcompy-test-ready", "1")
|
|
146
|
+
_console_start_index = js.window.__webcompy_test_console__.length
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def skip(reason: str = "skipped") -> None:
|
|
150
|
+
"""Raise a skip signal that maps to a skipped pytest outcome."""
|
|
151
|
+
raise _Skipped(reason)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def parse_test_id(test_id: str) -> tuple[str, str, int | None]:
|
|
155
|
+
"""Split a dispatched test id into module name, qualname, and param index."""
|
|
156
|
+
match = _PARAM_SUFFIX_RE.search(test_id)
|
|
157
|
+
param_index = int(match.group(1)) if match else None
|
|
158
|
+
node_id = test_id[: match.start()] if match else test_id
|
|
159
|
+
module_path, sep, qualname = node_id.partition("::")
|
|
160
|
+
if not sep or not qualname:
|
|
161
|
+
raise ValueError(f"malformed test id: {test_id!r}")
|
|
162
|
+
display_group = _DISPLAY_ID_SUFFIX_RE.search(qualname)
|
|
163
|
+
if display_group is not None:
|
|
164
|
+
qualname = qualname[: display_group.start()]
|
|
165
|
+
module_name = module_path.removesuffix(".py").replace("/", ".")
|
|
166
|
+
return module_name, qualname, param_index
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def normalize_traceback(text: str) -> str:
|
|
170
|
+
"""Rewrite Emscripten FS source paths back to repo-relative paths."""
|
|
171
|
+
for mounted, repo_relative in _TB_REWRITES:
|
|
172
|
+
text = text.replace(mounted, repo_relative)
|
|
173
|
+
return text
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def resolve_parametrize_payload(func: Any, param_index: int | None) -> dict[str, Any]:
|
|
177
|
+
"""Resolve ``@pytest.mark.parametrize`` values for the given index."""
|
|
178
|
+
marks = [mark for mark in getattr(func, "pytestmark", []) if getattr(mark, "name", "") == "parametrize"]
|
|
179
|
+
if not marks:
|
|
180
|
+
if param_index is not None:
|
|
181
|
+
raise ValueError(
|
|
182
|
+
f"test id carries parametrize index [{param_index}] but the function has no parametrize mark"
|
|
183
|
+
)
|
|
184
|
+
return {}
|
|
185
|
+
if len(marks) > 1:
|
|
186
|
+
raise ValueError(
|
|
187
|
+
"stacked @pytest.mark.parametrize marks are not supported in the browser test tier; use a single mark"
|
|
188
|
+
)
|
|
189
|
+
raw_names, values = marks[0].args
|
|
190
|
+
if isinstance(raw_names, str):
|
|
191
|
+
names = [name.strip() for name in raw_names.split(",")]
|
|
192
|
+
else:
|
|
193
|
+
names = [str(name) for name in raw_names]
|
|
194
|
+
if param_index is None:
|
|
195
|
+
raise ValueError("parametrized browser test dispatched without a [p<index>] suffix")
|
|
196
|
+
payload = values[param_index]
|
|
197
|
+
if len(names) == 1:
|
|
198
|
+
return {names[0]: payload}
|
|
199
|
+
return dict(zip(names, payload, strict=True))
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
async def _fetch_manifest_modules() -> list[str]:
|
|
203
|
+
try:
|
|
204
|
+
pyfetch = importlib.import_module("pyodide.http").pyfetch
|
|
205
|
+
response = await pyfetch(_MANIFEST_URL)
|
|
206
|
+
data = await response.json()
|
|
207
|
+
return list(data.get("modules", []))
|
|
208
|
+
except Exception:
|
|
209
|
+
return []
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
async def _load_function(module_name: str, qualname: str) -> Any:
|
|
213
|
+
sys.modules.pop(module_name, None)
|
|
214
|
+
try:
|
|
215
|
+
module = importlib.import_module(module_name)
|
|
216
|
+
except ModuleNotFoundError:
|
|
217
|
+
manifest = await _fetch_manifest_modules()
|
|
218
|
+
if module_name in manifest:
|
|
219
|
+
sys.modules.pop(module_name, None)
|
|
220
|
+
module = importlib.import_module(module_name)
|
|
221
|
+
else:
|
|
222
|
+
raise
|
|
223
|
+
return resolve_qualname_target(module, qualname)
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def resolve_qualname_target(container: Any, qualname: str) -> Any:
|
|
227
|
+
"""Resolve a ``::``-separated qualname to a callable, binding methods.
|
|
228
|
+
|
|
229
|
+
When the qualname path addresses a method through a class (for example
|
|
230
|
+
``TestDIScope::test_class_type_key``), the class is instantiated with no
|
|
231
|
+
arguments and the attribute is fetched from the instance so the returned
|
|
232
|
+
callable is a bound method. This mirrors pytest's auto-instantiation of
|
|
233
|
+
test classes and keeps ``self`` out of the fixture-argument resolution.
|
|
234
|
+
|
|
235
|
+
Args:
|
|
236
|
+
container: The module (or any object) in which to resolve.
|
|
237
|
+
qualname: The ``::``-separated attribute path.
|
|
238
|
+
|
|
239
|
+
Returns:
|
|
240
|
+
The resolved callable.
|
|
241
|
+
|
|
242
|
+
Raises:
|
|
243
|
+
TypeError: If the resolved target is not callable.
|
|
244
|
+
|
|
245
|
+
"""
|
|
246
|
+
parts = qualname.split("::")
|
|
247
|
+
target: Any = container
|
|
248
|
+
for part in parts[:-1]:
|
|
249
|
+
target = getattr(target, part)
|
|
250
|
+
last = parts[-1]
|
|
251
|
+
raw = getattr(target, last)
|
|
252
|
+
if isinstance(target, type) and inspect.isfunction(raw):
|
|
253
|
+
first_params = list(inspect.signature(raw).parameters)
|
|
254
|
+
if first_params and first_params[0] == "self":
|
|
255
|
+
owner = target()
|
|
256
|
+
bound = getattr(owner, last)
|
|
257
|
+
if callable(bound):
|
|
258
|
+
return bound
|
|
259
|
+
if not callable(raw):
|
|
260
|
+
raise TypeError(f"'{qualname}' resolved to a non-callable object")
|
|
261
|
+
return raw
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
_SWEEP_CHROME_NODE_NAMES = frozenset({"SCRIPT"})
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def _sweep_dom_roots() -> None:
|
|
268
|
+
js = importlib.import_module("js")
|
|
269
|
+
children = [child for child in js.document.body.childNodes]
|
|
270
|
+
for child in children:
|
|
271
|
+
if child.nodeName == "DIV" and child.getAttribute("id") == "webcompy-app":
|
|
272
|
+
continue
|
|
273
|
+
if child.nodeName in _SWEEP_CHROME_NODE_NAMES:
|
|
274
|
+
continue
|
|
275
|
+
child.remove()
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def _make_dom_root() -> Any:
|
|
279
|
+
js = importlib.import_module("js")
|
|
280
|
+
dom_root = js.document.createElement("div")
|
|
281
|
+
dom_root.setAttribute("data-webcompy-test-root", "")
|
|
282
|
+
js.document.body.appendChild(dom_root)
|
|
283
|
+
return dom_root
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def _make_test_context(module: ModuleType) -> tuple[WebComPyApp, Any, _TrackingFFIPort]:
|
|
287
|
+
factory = getattr(module, "get_app", None)
|
|
288
|
+
app: WebComPyApp = cast("WebComPyApp", factory()) if callable(factory) else _make_default_app()
|
|
289
|
+
ctx: Any = app.create_render_context()
|
|
290
|
+
tracking_port = _TrackingFFIPort()
|
|
291
|
+
ctx.di_scope.provide(FFI_PORT_KEY, tracking_port)
|
|
292
|
+
return app, ctx, tracking_port
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def _fixture_kwargs(func: Any, app: WebComPyApp, dom_root: Any, exclude: set[str]) -> dict[str, Any]:
|
|
296
|
+
registry: dict[str, Any] = {"app": app, "dom_root": dom_root}
|
|
297
|
+
kwargs: dict[str, Any] = {}
|
|
298
|
+
for name in inspect.signature(func).parameters:
|
|
299
|
+
if name in exclude:
|
|
300
|
+
continue
|
|
301
|
+
if name not in registry:
|
|
302
|
+
raise UnknownFixtureError(name)
|
|
303
|
+
kwargs[name] = registry[name]
|
|
304
|
+
return kwargs
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def _console_error_texts(buffer: Any, start: int) -> list[str]:
|
|
308
|
+
entries = buffer.slice(start)
|
|
309
|
+
return [str(entries[index].text) for index in range(entries.length)]
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def _dump_result(
|
|
313
|
+
status: str,
|
|
314
|
+
started: float,
|
|
315
|
+
exc_type: str | None,
|
|
316
|
+
tb: str,
|
|
317
|
+
stdout: str,
|
|
318
|
+
stderr: str,
|
|
319
|
+
console_errors: list[str],
|
|
320
|
+
) -> str:
|
|
321
|
+
return json.dumps(
|
|
322
|
+
{
|
|
323
|
+
"status": status,
|
|
324
|
+
"duration_ms": round((time.perf_counter() - started) * 1000, 3),
|
|
325
|
+
"exc_type": exc_type,
|
|
326
|
+
"traceback": tb,
|
|
327
|
+
"stdout": stdout,
|
|
328
|
+
"stderr": stderr,
|
|
329
|
+
"console_error_delta": console_errors,
|
|
330
|
+
}
|
|
331
|
+
)
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
async def run_one(test_id: str) -> str:
|
|
335
|
+
"""Execute one browser test function and return its result as a JSON string."""
|
|
336
|
+
global _console_start_index
|
|
337
|
+
js = importlib.import_module("js")
|
|
338
|
+
console_buffer = js.window.__webcompy_test_console__
|
|
339
|
+
console_start = _console_start_index
|
|
340
|
+
started = time.perf_counter()
|
|
341
|
+
stdout_io = io.StringIO()
|
|
342
|
+
stderr_io = io.StringIO()
|
|
343
|
+
module_name = ""
|
|
344
|
+
ctx: Any = None
|
|
345
|
+
tracking_port: _TrackingFFIPort | None = None
|
|
346
|
+
dom_root: Any = None
|
|
347
|
+
try:
|
|
348
|
+
module_name, qualname, param_index = parse_test_id(test_id)
|
|
349
|
+
func = await _load_function(module_name, qualname)
|
|
350
|
+
_sweep_dom_roots()
|
|
351
|
+
app, ctx, tracking_port = _make_test_context(sys.modules[module_name])
|
|
352
|
+
dom_root = _make_dom_root()
|
|
353
|
+
kwargs = resolve_parametrize_payload(func, param_index)
|
|
354
|
+
kwargs.update(_fixture_kwargs(func, app, dom_root, exclude=set(kwargs)))
|
|
355
|
+
with redirect_stdout(stdout_io), redirect_stderr(stderr_io):
|
|
356
|
+
outcome = func(**kwargs)
|
|
357
|
+
if inspect.iscoroutine(outcome):
|
|
358
|
+
await outcome
|
|
359
|
+
return _dump_result(
|
|
360
|
+
"passed",
|
|
361
|
+
started,
|
|
362
|
+
None,
|
|
363
|
+
"",
|
|
364
|
+
stdout_io.getvalue(),
|
|
365
|
+
stderr_io.getvalue(),
|
|
366
|
+
_console_error_texts(console_buffer, console_start),
|
|
367
|
+
)
|
|
368
|
+
except _Skipped as e:
|
|
369
|
+
return _dump_result(
|
|
370
|
+
"skipped",
|
|
371
|
+
started,
|
|
372
|
+
"Skipped",
|
|
373
|
+
str(e),
|
|
374
|
+
stdout_io.getvalue(),
|
|
375
|
+
stderr_io.getvalue(),
|
|
376
|
+
_console_error_texts(console_buffer, console_start),
|
|
377
|
+
)
|
|
378
|
+
except Exception as e:
|
|
379
|
+
formatted = "".join(traceback.format_exception(type(e), e, e.__traceback__))
|
|
380
|
+
return _dump_result(
|
|
381
|
+
"failed",
|
|
382
|
+
started,
|
|
383
|
+
type(e).__name__,
|
|
384
|
+
normalize_traceback(formatted),
|
|
385
|
+
stdout_io.getvalue(),
|
|
386
|
+
stderr_io.getvalue(),
|
|
387
|
+
_console_error_texts(console_buffer, console_start),
|
|
388
|
+
)
|
|
389
|
+
finally:
|
|
390
|
+
try:
|
|
391
|
+
if ctx is not None:
|
|
392
|
+
try:
|
|
393
|
+
scheduler = inject(ASYNC_SCHEDULER_PORT_KEY)
|
|
394
|
+
await scheduler.await_pending()
|
|
395
|
+
except Exception:
|
|
396
|
+
pass
|
|
397
|
+
ctx.dispose()
|
|
398
|
+
finally:
|
|
399
|
+
if dom_root is not None:
|
|
400
|
+
with suppress(Exception):
|
|
401
|
+
dom_root.remove()
|
|
402
|
+
_sweep_dom_roots()
|
|
403
|
+
if tracking_port is not None:
|
|
404
|
+
tracking_port.destroy_all()
|
|
405
|
+
if module_name:
|
|
406
|
+
sys.modules.pop(module_name, None)
|
|
407
|
+
_console_start_index = console_buffer.length
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
_EVAL_GLOBALS: dict[str, Any] | None = None
|
|
411
|
+
|
|
412
|
+
|
|
413
|
+
def _eval_globals() -> dict[str, Any]:
|
|
414
|
+
"""Return the persistent globals dict shared by ``evaluate`` calls.
|
|
415
|
+
|
|
416
|
+
Keeping one dict across invocations preserves interpreter state between
|
|
417
|
+
REPL turns; single-shot evaluations simply start from an empty namespace.
|
|
418
|
+
|
|
419
|
+
"""
|
|
420
|
+
global _EVAL_GLOBALS
|
|
421
|
+
if _EVAL_GLOBALS is None:
|
|
422
|
+
_EVAL_GLOBALS = {"__name__": "__main__"}
|
|
423
|
+
return _EVAL_GLOBALS
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
async def evaluate(code: str) -> str:
|
|
427
|
+
"""Evaluate Python code inside the harness interpreter.
|
|
428
|
+
|
|
429
|
+
The last expression's value is returned as its ``repr`` (``None`` for
|
|
430
|
+
statement-only code), mirroring a REPL. State persists across calls via
|
|
431
|
+
the shared globals dict. Unlike :func:`run_one`, the console error delta
|
|
432
|
+
is emitted as structured ``{"type", "text"}`` objects.
|
|
433
|
+
|
|
434
|
+
Args:
|
|
435
|
+
code: Python source to evaluate; may span multiple lines and use
|
|
436
|
+
top-level ``await``.
|
|
437
|
+
|
|
438
|
+
Returns:
|
|
439
|
+
JSON string of shape ``{"stdout", "stderr", "result_repr",
|
|
440
|
+
"console_error_delta", "exc_type", "traceback"}``. Evaluation
|
|
441
|
+
failures are reported in the payload instead of raising.
|
|
442
|
+
|
|
443
|
+
"""
|
|
444
|
+
global _console_start_index
|
|
445
|
+
js = importlib.import_module("js")
|
|
446
|
+
console_buffer = js.window.__webcompy_test_console__
|
|
447
|
+
console_start = _console_start_index
|
|
448
|
+
stdout_io = io.StringIO()
|
|
449
|
+
stderr_io = io.StringIO()
|
|
450
|
+
result_repr: str | None = None
|
|
451
|
+
exc_type: str | None = None
|
|
452
|
+
tb = ""
|
|
453
|
+
try:
|
|
454
|
+
from pyodide.code import eval_code_async
|
|
455
|
+
|
|
456
|
+
with redirect_stdout(stdout_io), redirect_stderr(stderr_io):
|
|
457
|
+
result = await eval_code_async(code, globals=_eval_globals())
|
|
458
|
+
if result is not None:
|
|
459
|
+
try:
|
|
460
|
+
result_repr = repr(result)
|
|
461
|
+
except Exception:
|
|
462
|
+
result_repr = f"<unrepresentable {type(result).__name__}>"
|
|
463
|
+
except Exception as e:
|
|
464
|
+
exc_type = type(e).__name__
|
|
465
|
+
tb = normalize_traceback("".join(traceback.format_exception(type(e), e, e.__traceback__)))
|
|
466
|
+
payload = json.dumps(
|
|
467
|
+
{
|
|
468
|
+
"stdout": stdout_io.getvalue(),
|
|
469
|
+
"stderr": stderr_io.getvalue(),
|
|
470
|
+
"result_repr": result_repr,
|
|
471
|
+
"console_error_delta": [
|
|
472
|
+
{"type": str(console_buffer[i].type), "text": str(console_buffer[i].text)}
|
|
473
|
+
for i in range(console_start, console_buffer.length)
|
|
474
|
+
],
|
|
475
|
+
"exc_type": exc_type,
|
|
476
|
+
"traceback": tb,
|
|
477
|
+
}
|
|
478
|
+
)
|
|
479
|
+
_console_start_index = console_buffer.length
|
|
480
|
+
return payload
|
|
File without changes
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: webcompy-testing
|
|
3
|
+
Version: 0.0.14
|
|
4
|
+
Summary: WebComPy testing utilities (TestRenderer, fake ports, ASGI test client)
|
|
5
|
+
Project-URL: Homepage, https://github.com/kniwase/WebComPy
|
|
6
|
+
Project-URL: Documentation, https://webcompy.net/documents/
|
|
7
|
+
Project-URL: LLM Docs, https://webcompy.net/llms.txt
|
|
8
|
+
Author-email: Kento Niwase <kento.niwase@gmail.com>
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: browser,frontend,testing
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
16
|
+
Requires-Python: >=3.12
|
|
17
|
+
Requires-Dist: beautifulsoup4
|
|
18
|
+
Requires-Dist: starlette
|
|
19
|
+
Requires-Dist: webcompy-server==0.0.14
|
|
20
|
+
Requires-Dist: webcompy==0.0.14
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
|
|
23
|
+
# webcompy-testing
|
|
24
|
+
|
|
25
|
+
Headless component testing, fake browser/network ports, ASGI test client helpers, and in-browser PyScript test runner utilities for [WebComPy](https://github.com/kniwase/WebComPy).
|
|
26
|
+
|
|
27
|
+
Key utilities exported from `webcompy_testing`:
|
|
28
|
+
|
|
29
|
+
- `TestRenderer` — Mount and interact with WebComPy components in standard Python without a browser
|
|
30
|
+
- Fake port implementations (`FakeBrowserDOMPort`, `FakeFetchPort`, `FakeEventSourcePort`, `FakeWebSocketPort`, `FakeAsyncSchedulerPort`, and more)
|
|
31
|
+
- `create_test_asgi_app` and `render_app_html` — Server-side rendering and ASGI endpoint testing helpers
|
|
32
|
+
- DI scope helpers and browser runner support (`webcompy_testing.browser_runner`)
|
|
33
|
+
|
|
34
|
+
This distribution is versioned in lockstep with `webcompy` and `webcompy-server`.
|
|
35
|
+
|
|
36
|
+
## Documentation & Resources
|
|
37
|
+
|
|
38
|
+
- [Documentation](https://webcompy.net/documents/)
|
|
39
|
+
- [Testing Guide](https://webcompy.net/documents/server/testing/)
|
|
40
|
+
- [LLM Documentation Index (`llms.txt`)](https://webcompy.net/llms.txt) — bundles: [`llms-small.txt`](https://webcompy.net/llms-small.txt) / [`llms-full.txt`](https://webcompy.net/llms-full.txt)
|
|
41
|
+
- [Source Code & Discussions](https://github.com/kniwase/WebComPy)
|
|
42
|
+
|
|
43
|
+
## License
|
|
44
|
+
|
|
45
|
+
MIT License — see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
webcompy_testing/__init__.py,sha256=SBle-3D6Y_PbCAQYk-NIokLydfTJSD3DtDzzDQPfNvM,1686
|
|
2
|
+
webcompy_testing/_app.py,sha256=3l3tEQuaticphTM2wbUni508KCCZAJo3rjIsq5UUBj8,878
|
|
3
|
+
webcompy_testing/_asgi.py,sha256=GJdb6j_VJkmzI0CwbcENWaB3dOVhTriqKmF2aVWoRgo,3228
|
|
4
|
+
webcompy_testing/_dom.py,sha256=jtJ_rAwZN00u4r63AXzWUyJpMODIUqtWLyX1SAH__Iw,5464
|
|
5
|
+
webcompy_testing/_ports.py,sha256=Mzt5-bA5Q2FYy3sqyidUkuqgkmU-Dd-DcX13HoyPtms,44071
|
|
6
|
+
webcompy_testing/_renderer.py,sha256=9VRfQUnopd7xMQvxg4VPToxDZBMUSAXbgina1Fi_2dk,11986
|
|
7
|
+
webcompy_testing/_restore.py,sha256=_PltOAA7_vhbFcn-fmk4V0bb7hFV42LCh5qmb1Eru_g,2041
|
|
8
|
+
webcompy_testing/_scope.py,sha256=WC2VA1PjwJt-x9vg6blWKNyzlaX-0xNIji9DgOsr6hE,1104
|
|
9
|
+
webcompy_testing/_utils.py,sha256=6XoQhst-z9mH7R7ytCvJWdI2iCicyDm2psFlxMNLToE,761
|
|
10
|
+
webcompy_testing/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
11
|
+
webcompy_testing/browser_runner/__init__.py,sha256=CclNKMFUQSg9Idfi1B2LNIrN033UFDTnKUjre5B3cas,538
|
|
12
|
+
webcompy_testing/browser_runner/_runner.py,sha256=zc2nncKZnSA_41oHHT53-y2ceaXjAsX0DXnou07L04o,16228
|
|
13
|
+
webcompy_testing-0.0.14.dist-info/METADATA,sha256=C7xqjEvlLZRt5NODeDzTYSBadcnNBpijBBc-sWI-zZY,2076
|
|
14
|
+
webcompy_testing-0.0.14.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
15
|
+
webcompy_testing-0.0.14.dist-info/licenses/LICENSE,sha256=endi3iQMQFbLs2ZrHgpdhZB7G0qTxwHw_DcSn6PjQrM,1069
|
|
16
|
+
webcompy_testing-0.0.14.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2022 Kento NIWASE
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|