webcompy-cli 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_cli/__init__.py +20 -0
- webcompy_cli/_argparser.py +232 -0
- webcompy_cli/_browser_probes.py +648 -0
- webcompy_cli/_browser_test_harness.py +554 -0
- webcompy_cli/_build.py +425 -0
- webcompy_cli/_console_types.py +15 -0
- webcompy_cli/_dependency_resolver.py +301 -0
- webcompy_cli/_dualrun_pytest_plugin.py +130 -0
- webcompy_cli/_exception.py +9 -0
- webcompy_cli/_generate.py +224 -0
- webcompy_cli/_init_project.py +54 -0
- webcompy_cli/_inspect.py +741 -0
- webcompy_cli/_inspect_pyexec.py +244 -0
- webcompy_cli/_lock.py +82 -0
- webcompy_cli/_lockfile.py +396 -0
- webcompy_cli/_lockfile_sync.py +343 -0
- webcompy_cli/_output.py +150 -0
- webcompy_cli/_prebuild.py +661 -0
- webcompy_cli/_pwa.py +474 -0
- webcompy_cli/_pyodide_downloader.py +113 -0
- webcompy_cli/_pyodide_lock.py +74 -0
- webcompy_cli/_runtime_downloader.py +222 -0
- webcompy_cli/_server.py +568 -0
- webcompy_cli/_static_files.py +27 -0
- webcompy_cli/_utils.py +72 -0
- webcompy_cli/_version_sweep.py +213 -0
- webcompy_cli/_wheel_builder.py +509 -0
- webcompy_cli/config/__init__.py +23 -0
- webcompy_cli/config/_build_config.py +168 -0
- webcompy_cli/config/_pwa_config.py +203 -0
- webcompy_cli/config/_server_config.py +53 -0
- webcompy_cli/py.typed +0 -0
- webcompy_cli/template_data/app/__init__.py +0 -0
- webcompy_cli/template_data/app/app.py +22 -0
- webcompy_cli/template_data/app/components/__init__.py +0 -0
- webcompy_cli/template_data/app/components/fizzbuzz.py +117 -0
- webcompy_cli/template_data/app/components/home.py +15 -0
- webcompy_cli/template_data/app/components/input.py +34 -0
- webcompy_cli/template_data/app/components/navigation.py +36 -0
- webcompy_cli/template_data/app/components/not_found.py +22 -0
- webcompy_cli/template_data/app/components/root.py +16 -0
- webcompy_cli/template_data/app/router.py +17 -0
- webcompy_cli/template_data/webcompy_config.py +12 -0
- webcompy_cli-0.0.14.dist-info/METADATA +53 -0
- webcompy_cli-0.0.14.dist-info/RECORD +47 -0
- webcompy_cli-0.0.14.dist-info/WHEEL +4 -0
- webcompy_cli-0.0.14.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,648 @@
|
|
|
1
|
+
"""AST classifier and dual-run sweep utilities for ``tests/`` modules.
|
|
2
|
+
|
|
3
|
+
The classifier walks test modules without importing them, parses each file's
|
|
4
|
+
AST, and tags a module as dual-run eligible only when its top level is safe to
|
|
5
|
+
execute inside a real PyScript interpreter: browser-only imports (``js``,
|
|
6
|
+
``pyscript``, ``pyodide``), ``webcompy_cli``/``docs_app`` (never mounted
|
|
7
|
+
in-page), ``e2e.*`` imports, and fake-port symbols from ``webcompy_testing``
|
|
8
|
+
are disqualifying, and any module-scope side-effecting call (except the
|
|
9
|
+
registration-style ``pytest.mark.*`` / ``pytest.fixture`` call chains) is
|
|
10
|
+
disqualifying. Imports of ``js``-family symbols inside function bodies do not
|
|
11
|
+
disqualify a module because those imports are only evaluated in-page. Top-level
|
|
12
|
+
imports rooted at ``tests`` are validated against the harness mount inventory:
|
|
13
|
+
only mounted test modules (and package ``__init__.py`` files) resolve in-page,
|
|
14
|
+
so sibling helpers such as ``tests/conftest.py`` disqualify the importer, and
|
|
15
|
+
the validation iterates to a fixpoint so importers of helpers that are
|
|
16
|
+
themselves ineligible drop out too. The eligible-pragma waiver short-circuits
|
|
17
|
+
these mount-inventory checks like any other.
|
|
18
|
+
|
|
19
|
+
A trailing pragma comment on its own line overrides the AST judgment:
|
|
20
|
+
|
|
21
|
+
- ``# browser-dualrun: eligible`` forces an otherwise ineligible module into
|
|
22
|
+
the eligible set.
|
|
23
|
+
- ``# browser-dualrun: skip`` forces an otherwise eligible module out of the
|
|
24
|
+
eligible set.
|
|
25
|
+
|
|
26
|
+
This module intentionally duplicates ``BROWSER_TEST_DIR`` instead of importing
|
|
27
|
+
it from the harness server module so that classification stays importable in
|
|
28
|
+
lightweight lint contexts (no Starlette/uvicorn dependency).
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
from __future__ import annotations
|
|
32
|
+
|
|
33
|
+
import ast
|
|
34
|
+
import json
|
|
35
|
+
import re
|
|
36
|
+
import time
|
|
37
|
+
from collections.abc import Callable
|
|
38
|
+
from dataclasses import dataclass, field
|
|
39
|
+
from pathlib import Path
|
|
40
|
+
from typing import Any
|
|
41
|
+
|
|
42
|
+
BROWSER_TEST_DIR = "tests/browser"
|
|
43
|
+
DUALRUN_BASELINE_DIR = "tests/.dualrun"
|
|
44
|
+
PRAGMA_ELIGIBLE = "browser-dualrun: eligible"
|
|
45
|
+
PRAGMA_SKIP = "browser-dualrun: skip"
|
|
46
|
+
|
|
47
|
+
_BROWSER_ONLY_MODULES = frozenset({"js", "pyscript", "pyodide"})
|
|
48
|
+
_UNMOUNTED_IN_PAGE_MODULES = frozenset({"webcompy_cli", "docs_app"})
|
|
49
|
+
_DISQUALIFYING_IMPORT_ROOTS = _BROWSER_ONLY_MODULES | _UNMOUNTED_IN_PAGE_MODULES
|
|
50
|
+
_FAKE_SOURCE_MODULE = "webcompy_testing"
|
|
51
|
+
_FAKE_SYMBOL_PREFIXES = ("Fake", "_")
|
|
52
|
+
_E2E_PACKAGE_ROOT = "e2e"
|
|
53
|
+
_MOUNTED_PACKAGE_ROOT = "tests"
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@dataclass
|
|
57
|
+
class DualRunClassification:
|
|
58
|
+
"""Result of partitioning ``tests/`` modules for dual-run execution.
|
|
59
|
+
|
|
60
|
+
Attributes:
|
|
61
|
+
eligible: Repo-relative POSIX paths of dual-run-eligible modules,
|
|
62
|
+
sorted ascending.
|
|
63
|
+
ineligible: Mapping of repo-relative POSIX path to the reason the
|
|
64
|
+
module was excluded, sorted by path.
|
|
65
|
+
|
|
66
|
+
"""
|
|
67
|
+
|
|
68
|
+
eligible: list[str] = field(default_factory=list)
|
|
69
|
+
ineligible: dict[str, str] = field(default_factory=dict)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _pragma_of(source: str) -> str | None:
|
|
73
|
+
"""Return the override pragma found in the source, if any.
|
|
74
|
+
|
|
75
|
+
Args:
|
|
76
|
+
source: Full text of the module under classification.
|
|
77
|
+
|
|
78
|
+
Returns:
|
|
79
|
+
``PRAGMA_ELIGIBLE`` or ``PRAGMA_SKIP`` when a matching standalone
|
|
80
|
+
comment line exists, otherwise ``None``.
|
|
81
|
+
|
|
82
|
+
"""
|
|
83
|
+
for line in source.splitlines():
|
|
84
|
+
stripped = line.strip()
|
|
85
|
+
if stripped == f"# {PRAGMA_ELIGIBLE}":
|
|
86
|
+
return PRAGMA_ELIGIBLE
|
|
87
|
+
if stripped == f"# {PRAGMA_SKIP}":
|
|
88
|
+
return PRAGMA_SKIP
|
|
89
|
+
return None
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _call_root_path(call: ast.Call) -> list[str]:
|
|
93
|
+
"""Resolve the dotted attribute chain rooted at a plain name for a call.
|
|
94
|
+
|
|
95
|
+
Args:
|
|
96
|
+
call: The ``ast.Call`` node to resolve.
|
|
97
|
+
|
|
98
|
+
Returns:
|
|
99
|
+
The name/attribute segments from the root name outward (for example
|
|
100
|
+
``["pytest", "mark", "parametrize"]``), or an empty list when the call
|
|
101
|
+
target is not rooted at a plain name.
|
|
102
|
+
|
|
103
|
+
"""
|
|
104
|
+
parts: list[str] = []
|
|
105
|
+
node: ast.AST = call.func
|
|
106
|
+
while isinstance(node, ast.Attribute):
|
|
107
|
+
parts.append(node.attr)
|
|
108
|
+
node = node.value
|
|
109
|
+
if not isinstance(node, ast.Name):
|
|
110
|
+
return []
|
|
111
|
+
parts.append(node.id)
|
|
112
|
+
parts.reverse()
|
|
113
|
+
return parts
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _is_allowed_call(call: ast.Call) -> bool:
|
|
117
|
+
"""Whether a module-scope call is a harmless pytest registration call.
|
|
118
|
+
|
|
119
|
+
Args:
|
|
120
|
+
call: The ``ast.Call`` node to inspect.
|
|
121
|
+
|
|
122
|
+
Returns:
|
|
123
|
+
True for calls whose target resolves through ``pytest.mark.*`` or
|
|
124
|
+
``pytest.fixture``; these only attach metadata and have no runtime
|
|
125
|
+
side effects on either interpreter.
|
|
126
|
+
|
|
127
|
+
"""
|
|
128
|
+
parts = _call_root_path(call)
|
|
129
|
+
return len(parts) >= 2 and parts[0] == "pytest" and parts[1] in ("mark", "fixture")
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _reason_for_statement(stmt: ast.stmt) -> str | None:
|
|
133
|
+
"""Inspect one top-level statement for disqualifying content.
|
|
134
|
+
|
|
135
|
+
Function, async function, and class bodies are not descended into because
|
|
136
|
+
their internals only execute when invoked; their decorators are inspected
|
|
137
|
+
individually. All other statements are walked fully so nested calls (for
|
|
138
|
+
example the right-hand side of an assignment) are caught.
|
|
139
|
+
|
|
140
|
+
Args:
|
|
141
|
+
stmt: A top-level AST statement.
|
|
142
|
+
|
|
143
|
+
Returns:
|
|
144
|
+
A human-readable reason string when the statement disqualifies the
|
|
145
|
+
module, otherwise ``None``.
|
|
146
|
+
|
|
147
|
+
"""
|
|
148
|
+
if isinstance(stmt, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
|
|
149
|
+
for decorator in stmt.decorator_list:
|
|
150
|
+
for node in ast.walk(decorator):
|
|
151
|
+
if isinstance(node, ast.Call) and not _is_allowed_call(node):
|
|
152
|
+
return f"module-scope side-effecting call at line {node.lineno}"
|
|
153
|
+
return None
|
|
154
|
+
for node in ast.walk(stmt):
|
|
155
|
+
if isinstance(node, ast.Call) and not _is_allowed_call(node):
|
|
156
|
+
return f"module-scope side-effecting call at line {node.lineno}"
|
|
157
|
+
return None
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _reason_for_imports(tree: ast.Module) -> str | None:
|
|
161
|
+
"""Scan top-level imports for browser-only, unmounted, e2e, or fake-port symbols.
|
|
162
|
+
|
|
163
|
+
Args:
|
|
164
|
+
tree: Parsed module AST.
|
|
165
|
+
|
|
166
|
+
Returns:
|
|
167
|
+
A human-readable reason string naming the disqualifying import, or
|
|
168
|
+
``None`` when all top-level imports are acceptable.
|
|
169
|
+
|
|
170
|
+
"""
|
|
171
|
+
for stmt in tree.body:
|
|
172
|
+
if isinstance(stmt, ast.Import):
|
|
173
|
+
for alias in stmt.names:
|
|
174
|
+
root = alias.name.split(".")[0]
|
|
175
|
+
if root in _DISQUALIFYING_IMPORT_ROOTS or root == _E2E_PACKAGE_ROOT:
|
|
176
|
+
return f"top-level import of '{alias.name}' at line {stmt.lineno}"
|
|
177
|
+
elif isinstance(stmt, ast.ImportFrom):
|
|
178
|
+
if stmt.level != 0:
|
|
179
|
+
continue
|
|
180
|
+
module = stmt.module or ""
|
|
181
|
+
root = module.split(".")[0]
|
|
182
|
+
if root in _DISQUALIFYING_IMPORT_ROOTS or root == _E2E_PACKAGE_ROOT:
|
|
183
|
+
return f"top-level import from '{module}' at line {stmt.lineno}"
|
|
184
|
+
if root == _FAKE_SOURCE_MODULE:
|
|
185
|
+
for alias in stmt.names:
|
|
186
|
+
if alias.name != "__all__" and alias.name.startswith(_FAKE_SYMBOL_PREFIXES):
|
|
187
|
+
return f"top-level import of '{module}.{alias.name}' at line {stmt.lineno}"
|
|
188
|
+
return None
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _reason_for_unmounted_tests_imports(tree: ast.Module, is_mounted: Callable[[str], bool]) -> str | None:
|
|
192
|
+
"""Check top-level ``tests.*`` imports against a mount-inventory predicate.
|
|
193
|
+
|
|
194
|
+
Only dual-run test modules themselves (plus their ancestor package
|
|
195
|
+
``__init__.py`` files) are mounted in-page, so a top-level import of a
|
|
196
|
+
sibling helper such as ``tests/conftest.py`` cannot resolve inside the
|
|
197
|
+
interpreter and disqualifies the importing module.
|
|
198
|
+
|
|
199
|
+
Args:
|
|
200
|
+
tree: Parsed module AST.
|
|
201
|
+
is_mounted: Predicate answering whether a dotted ``tests.*`` target
|
|
202
|
+
resolves against the in-page mount inventory.
|
|
203
|
+
|
|
204
|
+
Returns:
|
|
205
|
+
A human-readable reason string naming the unmounted import, or
|
|
206
|
+
``None`` when every top-level ``tests.*`` import target is mounted.
|
|
207
|
+
|
|
208
|
+
"""
|
|
209
|
+
for stmt in tree.body:
|
|
210
|
+
if isinstance(stmt, ast.Import):
|
|
211
|
+
targets = [alias.name for alias in stmt.names]
|
|
212
|
+
lineno = stmt.lineno
|
|
213
|
+
elif isinstance(stmt, ast.ImportFrom) and stmt.level == 0 and stmt.module:
|
|
214
|
+
if stmt.module == _MOUNTED_PACKAGE_ROOT:
|
|
215
|
+
targets = [f"{_MOUNTED_PACKAGE_ROOT}.{alias.name}" for alias in stmt.names]
|
|
216
|
+
else:
|
|
217
|
+
targets = [stmt.module]
|
|
218
|
+
lineno = stmt.lineno
|
|
219
|
+
else:
|
|
220
|
+
continue
|
|
221
|
+
for dotted in targets:
|
|
222
|
+
if not dotted.startswith(f"{_MOUNTED_PACKAGE_ROOT}."):
|
|
223
|
+
continue
|
|
224
|
+
if not is_mounted(dotted):
|
|
225
|
+
return f"top-level import of unmounted module '{dotted}' at line {lineno}"
|
|
226
|
+
return None
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def _mounted_predicate(repo_root: Path, eligible: set[str] | None = None) -> Callable[[str], bool]:
|
|
230
|
+
"""Build a mount-inventory predicate for ``tests.*`` import targets.
|
|
231
|
+
|
|
232
|
+
Args:
|
|
233
|
+
repo_root: Repository root used to probe candidate target files.
|
|
234
|
+
eligible: When given, ``test_*.py`` module targets must belong to this
|
|
235
|
+
repo-relative path set (the harness mounts only eligible dual-run
|
|
236
|
+
modules); when ``None``, any existing ``test_*.py`` file counts as
|
|
237
|
+
mounted.
|
|
238
|
+
|
|
239
|
+
Returns:
|
|
240
|
+
A predicate answering whether a dotted ``tests.*`` module resolves
|
|
241
|
+
against the in-page mount inventory.
|
|
242
|
+
|
|
243
|
+
"""
|
|
244
|
+
|
|
245
|
+
def is_mounted(dotted: str) -> bool:
|
|
246
|
+
base = repo_root.joinpath(*dotted.split("."))
|
|
247
|
+
as_module = base.with_suffix(".py")
|
|
248
|
+
if as_module.is_file() and as_module.name.startswith("test_"):
|
|
249
|
+
if eligible is None:
|
|
250
|
+
return True
|
|
251
|
+
return as_module.relative_to(repo_root).as_posix() in eligible
|
|
252
|
+
return (base / "__init__.py").is_file()
|
|
253
|
+
|
|
254
|
+
return is_mounted
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def classify_module(source: str, path: str) -> str | None:
|
|
258
|
+
"""Classify one test module's source text as eligible or ineligible.
|
|
259
|
+
|
|
260
|
+
Parse failures of ``source`` propagate as :class:`SyntaxError`; callers
|
|
261
|
+
should treat them as their own ineligible reason.
|
|
262
|
+
|
|
263
|
+
Args:
|
|
264
|
+
source: Full text of the module under classification.
|
|
265
|
+
path: Repo-relative POSIX path used in reason messages.
|
|
266
|
+
|
|
267
|
+
Returns:
|
|
268
|
+
``None`` when the module is dual-run eligible; otherwise a
|
|
269
|
+
human-readable reason string describing why it was excluded.
|
|
270
|
+
|
|
271
|
+
"""
|
|
272
|
+
tree = ast.parse(source, filename=path)
|
|
273
|
+
pragma = _pragma_of(source)
|
|
274
|
+
if pragma == PRAGMA_SKIP:
|
|
275
|
+
return f"pragma '{PRAGMA_SKIP}'"
|
|
276
|
+
import_reason = _reason_for_imports(tree)
|
|
277
|
+
if import_reason is not None:
|
|
278
|
+
if pragma == PRAGMA_ELIGIBLE:
|
|
279
|
+
return None
|
|
280
|
+
return import_reason
|
|
281
|
+
for stmt in tree.body:
|
|
282
|
+
reason = _reason_for_statement(stmt)
|
|
283
|
+
if reason is not None:
|
|
284
|
+
if pragma == PRAGMA_ELIGIBLE:
|
|
285
|
+
return None
|
|
286
|
+
return reason
|
|
287
|
+
return None
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def classify_tests(repo_root: Path) -> DualRunClassification:
|
|
291
|
+
"""Walk ``tests/**`` and partition every test module into eligibility sets.
|
|
292
|
+
|
|
293
|
+
Modules under the browser tier directory (``tests/browser``) are excluded:
|
|
294
|
+
they already run through the browser harness and never participate in the
|
|
295
|
+
dual-run sweep. Test modules are parsed read-only; none are imported.
|
|
296
|
+
Top-level imports rooted at ``tests`` are validated against the harness
|
|
297
|
+
mount inventory via :func:`_reason_for_unmounted_tests_imports`: first by
|
|
298
|
+
file existence, then iteratively against the eligible set itself until a
|
|
299
|
+
fixpoint is reached, so modules importing helpers that are themselves
|
|
300
|
+
ineligible drop out as well. The pragma waiver short-circuits both checks.
|
|
301
|
+
|
|
302
|
+
Args:
|
|
303
|
+
repo_root: Repository root containing the ``tests/`` tree.
|
|
304
|
+
|
|
305
|
+
Returns:
|
|
306
|
+
A :class:`DualRunClassification` with sorted repo-relative paths.
|
|
307
|
+
|
|
308
|
+
"""
|
|
309
|
+
result = DualRunClassification()
|
|
310
|
+
tests_dir = repo_root / "tests"
|
|
311
|
+
if not tests_dir.is_dir():
|
|
312
|
+
return result
|
|
313
|
+
|
|
314
|
+
sources: dict[str, str] = {}
|
|
315
|
+
trees: dict[str, ast.Module] = {}
|
|
316
|
+
static_reasons: dict[str, str | None] = {}
|
|
317
|
+
for path in sorted(tests_dir.rglob("test_*.py")):
|
|
318
|
+
if not path.is_file():
|
|
319
|
+
continue
|
|
320
|
+
rel = path.relative_to(repo_root).as_posix()
|
|
321
|
+
if rel.startswith(f"{BROWSER_TEST_DIR}/"):
|
|
322
|
+
continue
|
|
323
|
+
try:
|
|
324
|
+
source = path.read_text(encoding="utf-8")
|
|
325
|
+
sources[rel] = source
|
|
326
|
+
trees[rel] = ast.parse(source, filename=rel)
|
|
327
|
+
reason = classify_module(source, rel)
|
|
328
|
+
if reason is None and _pragma_of(source) != PRAGMA_ELIGIBLE:
|
|
329
|
+
reason = _reason_for_unmounted_tests_imports(trees[rel], _mounted_predicate(repo_root))
|
|
330
|
+
static_reasons[rel] = reason
|
|
331
|
+
except SyntaxError as e:
|
|
332
|
+
static_reasons[rel] = f"syntax error at line {e.lineno}"
|
|
333
|
+
except UnicodeDecodeError:
|
|
334
|
+
static_reasons[rel] = "file is not valid UTF-8"
|
|
335
|
+
|
|
336
|
+
# Dropping an unmountable helper can orphan its importers, so refine the
|
|
337
|
+
# eligible set iteratively until it reaches a fixpoint.
|
|
338
|
+
eligible = {rel for rel, reason in static_reasons.items() if reason is None}
|
|
339
|
+
refined_reasons: dict[str, str] = {}
|
|
340
|
+
while True:
|
|
341
|
+
next_eligible: set[str] = set()
|
|
342
|
+
for rel in sorted(eligible):
|
|
343
|
+
if _pragma_of(sources[rel]) == PRAGMA_ELIGIBLE:
|
|
344
|
+
next_eligible.add(rel)
|
|
345
|
+
continue
|
|
346
|
+
reason = _reason_for_unmounted_tests_imports(trees[rel], _mounted_predicate(repo_root, eligible))
|
|
347
|
+
if reason is None:
|
|
348
|
+
next_eligible.add(rel)
|
|
349
|
+
else:
|
|
350
|
+
refined_reasons[rel] = reason
|
|
351
|
+
if next_eligible == eligible:
|
|
352
|
+
break
|
|
353
|
+
eligible = next_eligible
|
|
354
|
+
|
|
355
|
+
for rel in sorted(static_reasons):
|
|
356
|
+
reason = static_reasons[rel]
|
|
357
|
+
if rel in eligible:
|
|
358
|
+
result.eligible.append(rel)
|
|
359
|
+
elif reason is not None:
|
|
360
|
+
result.ineligible[rel] = reason
|
|
361
|
+
else:
|
|
362
|
+
result.ineligible[rel] = refined_reasons[rel]
|
|
363
|
+
return result
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
def write_baseline(result: DualRunClassification, out_dir: Path) -> tuple[Path, Path]:
|
|
367
|
+
"""Persist a classification snapshot as reviewable baseline files.
|
|
368
|
+
|
|
369
|
+
Args:
|
|
370
|
+
result: Classification produced by :func:`classify_tests`.
|
|
371
|
+
out_dir: Destination directory (created when missing).
|
|
372
|
+
|
|
373
|
+
Returns:
|
|
374
|
+
Tuple of the written ``eligible.txt`` and ``ineligible.json`` paths.
|
|
375
|
+
|
|
376
|
+
"""
|
|
377
|
+
out_dir.mkdir(parents=True, exist_ok=True)
|
|
378
|
+
eligible_path = out_dir / "eligible.txt"
|
|
379
|
+
ineligible_path = out_dir / "ineligible.json"
|
|
380
|
+
eligible_path.write_text(
|
|
381
|
+
"".join(f"{path}\n" for path in sorted(result.eligible)),
|
|
382
|
+
encoding="utf-8",
|
|
383
|
+
)
|
|
384
|
+
ineligible_path.write_text(
|
|
385
|
+
json.dumps(dict(sorted(result.ineligible.items())), indent=2, ensure_ascii=False) + "\n",
|
|
386
|
+
encoding="utf-8",
|
|
387
|
+
)
|
|
388
|
+
return eligible_path, ineligible_path
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
def load_baseline(repo_root: Path) -> list[str]:
|
|
392
|
+
"""Read the committed baseline eligible-module inventory.
|
|
393
|
+
|
|
394
|
+
Args:
|
|
395
|
+
repo_root: Repository root containing ``tests/.dualrun/eligible.txt``.
|
|
396
|
+
|
|
397
|
+
Returns:
|
|
398
|
+
Sorted repo-relative eligible paths from the baseline file, or an
|
|
399
|
+
empty list when the baseline does not exist yet.
|
|
400
|
+
|
|
401
|
+
"""
|
|
402
|
+
baseline = repo_root / DUALRUN_BASELINE_DIR / "eligible.txt"
|
|
403
|
+
if not baseline.is_file():
|
|
404
|
+
return []
|
|
405
|
+
return sorted(line.strip() for line in baseline.read_text(encoding="utf-8").splitlines() if line.strip())
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
_DUALRUN_ARTIFACT_NAME = "browser-dualrun.json"
|
|
409
|
+
_DISPLAY_SUFFIX_RE = re.compile(r"\[[^\[\]]*\]$")
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
@dataclass
|
|
413
|
+
class DualRunSweepResult:
|
|
414
|
+
"""Outcome of one CPython-vs-PyScript dual-run sweep.
|
|
415
|
+
|
|
416
|
+
Attributes:
|
|
417
|
+
eligible_count: Number of eligible modules the sweep attempted.
|
|
418
|
+
buckets: Bucketed test ids keyed ``both-pass``, ``CPython-only-fail``,
|
|
419
|
+
``PyScript-only-fail``, and ``both-fail``.
|
|
420
|
+
cpython_map: Mapping of CPython node id to raw outcome
|
|
421
|
+
(``passed`` / ``failed`` / ``skipped``).
|
|
422
|
+
pyscript_map: Same-shaped mapping collected in-page, keyed by the
|
|
423
|
+
original CPython node id.
|
|
424
|
+
duration_ms: Total sweep wall time in milliseconds.
|
|
425
|
+
error: Infrastructure error message when the CPython side could not
|
|
426
|
+
produce a report; ``None`` on a structurally complete sweep.
|
|
427
|
+
|
|
428
|
+
"""
|
|
429
|
+
|
|
430
|
+
eligible_count: int
|
|
431
|
+
buckets: dict[str, list[str]] = field(default_factory=dict)
|
|
432
|
+
cpython_map: dict[str, str] = field(default_factory=dict)
|
|
433
|
+
pyscript_map: dict[str, str] = field(default_factory=dict)
|
|
434
|
+
duration_ms: float = 0.0
|
|
435
|
+
error: str | None = None
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
def convert_cpython_id(nodeid: str, param_indices: dict[str, int]) -> str:
|
|
439
|
+
"""Convert a CPython pytest node id into an in-page runner test id.
|
|
440
|
+
|
|
441
|
+
The trailing display suffix (``[param value]``) is stripped and replaced
|
|
442
|
+
with the machine-readable index form (``[p<index>]``) expected by the
|
|
443
|
+
in-page runner.
|
|
444
|
+
|
|
445
|
+
Args:
|
|
446
|
+
nodeid: CPython pytest node id, optionally carrying a display
|
|
447
|
+
parametrize suffix.
|
|
448
|
+
param_indices: Mapping of suffix-stripped node id to its parametrize
|
|
449
|
+
index within the declared values list.
|
|
450
|
+
|
|
451
|
+
Returns:
|
|
452
|
+
The equivalent in-page test id.
|
|
453
|
+
|
|
454
|
+
"""
|
|
455
|
+
match = _DISPLAY_SUFFIX_RE.search(nodeid)
|
|
456
|
+
stripped = nodeid[: match.start()] if match else nodeid
|
|
457
|
+
index = param_indices.get(stripped)
|
|
458
|
+
if index is not None:
|
|
459
|
+
return f"{stripped}[p{index}]"
|
|
460
|
+
return stripped
|
|
461
|
+
|
|
462
|
+
|
|
463
|
+
def diff_outcomes(cpython_map: dict[str, str], pyscript_map: dict[str, str]) -> dict[str, list[str]]:
|
|
464
|
+
"""Bucket paired outcomes from both interpreters into a divergence diff.
|
|
465
|
+
|
|
466
|
+
Test ids whose outcome is ``skipped`` on either side are excluded from the
|
|
467
|
+
buckets but remain present in the raw maps written to the artifact.
|
|
468
|
+
|
|
469
|
+
Args:
|
|
470
|
+
cpython_map: Node-id-to-outcome mapping collected under CPython.
|
|
471
|
+
pyscript_map: Same-shaped mapping collected inside the harness page.
|
|
472
|
+
|
|
473
|
+
Returns:
|
|
474
|
+
Buckets keyed ``both-pass``, ``CPython-only-fail``,
|
|
475
|
+
``PyScript-only-fail``, and ``both-fail`` with sorted test ids.
|
|
476
|
+
|
|
477
|
+
"""
|
|
478
|
+
buckets: dict[str, list[str]] = {
|
|
479
|
+
"both-pass": [],
|
|
480
|
+
"CPython-only-fail": [],
|
|
481
|
+
"PyScript-only-fail": [],
|
|
482
|
+
"both-fail": [],
|
|
483
|
+
}
|
|
484
|
+
for test_id in sorted(set(cpython_map) & set(pyscript_map)):
|
|
485
|
+
cpython = cpython_map[test_id]
|
|
486
|
+
pyscript = pyscript_map[test_id]
|
|
487
|
+
if cpython == "skipped" or pyscript == "skipped":
|
|
488
|
+
continue
|
|
489
|
+
if cpython == "passed" and pyscript == "passed":
|
|
490
|
+
buckets["both-pass"].append(test_id)
|
|
491
|
+
elif cpython == "passed":
|
|
492
|
+
buckets["PyScript-only-fail"].append(test_id)
|
|
493
|
+
elif pyscript == "passed":
|
|
494
|
+
buckets["CPython-only-fail"].append(test_id)
|
|
495
|
+
else:
|
|
496
|
+
buckets["both-fail"].append(test_id)
|
|
497
|
+
return buckets
|
|
498
|
+
|
|
499
|
+
|
|
500
|
+
def write_dualrun_artifact(result: DualRunSweepResult, artifacts_dir: Path) -> Path:
|
|
501
|
+
"""Write the bucketed dual-run diff artifact for one sweep invocation.
|
|
502
|
+
|
|
503
|
+
Args:
|
|
504
|
+
result: Sweep outcome to serialize.
|
|
505
|
+
artifacts_dir: Destination directory (created when missing).
|
|
506
|
+
|
|
507
|
+
Returns:
|
|
508
|
+
The path of the written ``browser-dualrun.json`` artifact.
|
|
509
|
+
|
|
510
|
+
"""
|
|
511
|
+
artifacts_dir.mkdir(parents=True, exist_ok=True)
|
|
512
|
+
path = artifacts_dir / _DUALRUN_ARTIFACT_NAME
|
|
513
|
+
payload = {
|
|
514
|
+
"eligible_count": result.eligible_count,
|
|
515
|
+
"buckets": {name: sorted(ids) for name, ids in result.buckets.items()},
|
|
516
|
+
"cpython_map": dict(sorted(result.cpython_map.items())),
|
|
517
|
+
"pyscript_map": dict(sorted(result.pyscript_map.items())),
|
|
518
|
+
"duration_ms": round(result.duration_ms, 3),
|
|
519
|
+
}
|
|
520
|
+
if result.error is not None:
|
|
521
|
+
payload["error"] = result.error
|
|
522
|
+
path.write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
|
|
523
|
+
return path
|
|
524
|
+
|
|
525
|
+
|
|
526
|
+
def run_dualrun_sweep(
|
|
527
|
+
*,
|
|
528
|
+
repo_root: Path,
|
|
529
|
+
driver: Any,
|
|
530
|
+
artifacts_dir: Path | None = None,
|
|
531
|
+
report_path: Path | None = None,
|
|
532
|
+
) -> DualRunSweepResult:
|
|
533
|
+
"""Execute the eligible subset under both interpreters and diff results.
|
|
534
|
+
|
|
535
|
+
The CPython side runs a subprocess pytest over the classified eligible
|
|
536
|
+
modules using the dual-run report plugin; the PyScript side dispatches the
|
|
537
|
+
same test ids through the live harness driver. The sweep is informational:
|
|
538
|
+
infrastructure failures are recorded in :attr:`DualRunSweepResult.error`
|
|
539
|
+
instead of raising, so callers never need to fail a session because of it.
|
|
540
|
+
|
|
541
|
+
Args:
|
|
542
|
+
repo_root: Repository root containing the ``tests/`` tree.
|
|
543
|
+
driver: Live browser harness driver exposing ``run_one(test_id)``
|
|
544
|
+
returning the in-page JSON result string.
|
|
545
|
+
artifacts_dir: Directory for ``browser-dualrun.json``; defaults to
|
|
546
|
+
``<repo_root>/artifacts``.
|
|
547
|
+
report_path: Where the CPython plugin writes its outcome JSON;
|
|
548
|
+
defaults to a scratch file under ``<repo_root>/.tmp``.
|
|
549
|
+
|
|
550
|
+
Returns:
|
|
551
|
+
A :class:`DualRunSweepResult` describing the paired outcomes.
|
|
552
|
+
|
|
553
|
+
"""
|
|
554
|
+
started = time.perf_counter()
|
|
555
|
+
destination = artifacts_dir or repo_root / "artifacts"
|
|
556
|
+
scratch = report_path or repo_root / ".tmp" / "dualrun-cpython.json"
|
|
557
|
+
classification = classify_tests(repo_root)
|
|
558
|
+
result = DualRunSweepResult(eligible_count=len(classification.eligible))
|
|
559
|
+
if not classification.eligible:
|
|
560
|
+
result.duration_ms = (time.perf_counter() - started) * 1000
|
|
561
|
+
write_dualrun_artifact(result, destination)
|
|
562
|
+
return result
|
|
563
|
+
|
|
564
|
+
outcomes, indices = _collect_cpython_outcomes(repo_root, classification.eligible, scratch)
|
|
565
|
+
if outcomes is None:
|
|
566
|
+
result.error = f"CPython collection failed; see {scratch} diagnostics in the subprocess log"
|
|
567
|
+
result.duration_ms = (time.perf_counter() - started) * 1000
|
|
568
|
+
write_dualrun_artifact(result, destination)
|
|
569
|
+
return result
|
|
570
|
+
|
|
571
|
+
result.cpython_map = outcomes
|
|
572
|
+
total = len(outcomes)
|
|
573
|
+
for progress, nodeid in enumerate(sorted(outcomes), start=1):
|
|
574
|
+
converted = convert_cpython_id(nodeid, indices)
|
|
575
|
+
try:
|
|
576
|
+
payload = driver.run_one(converted)
|
|
577
|
+
if isinstance(payload, (str, bytes)):
|
|
578
|
+
payload = json.loads(payload)
|
|
579
|
+
status = str(payload.get("status", "failed"))
|
|
580
|
+
except RuntimeError as e:
|
|
581
|
+
if "worker thread" in str(e):
|
|
582
|
+
# Driver is dead; nothing further can execute in-page.
|
|
583
|
+
for remaining in sorted(outcomes)[progress - 1 :]:
|
|
584
|
+
result.pyscript_map[remaining] = "skipped"
|
|
585
|
+
break
|
|
586
|
+
status = "failed"
|
|
587
|
+
except Exception:
|
|
588
|
+
status = "failed"
|
|
589
|
+
result.pyscript_map[nodeid] = status
|
|
590
|
+
if progress % 25 == 0 or progress == total:
|
|
591
|
+
print(f"[browser-dualrun] in-page progress {progress}/{total}", flush=True)
|
|
592
|
+
|
|
593
|
+
result.buckets = diff_outcomes(result.cpython_map, result.pyscript_map)
|
|
594
|
+
result.duration_ms = (time.perf_counter() - started) * 1000
|
|
595
|
+
write_dualrun_artifact(result, destination)
|
|
596
|
+
return result
|
|
597
|
+
|
|
598
|
+
|
|
599
|
+
def _collect_cpython_outcomes(
|
|
600
|
+
repo_root: Path,
|
|
601
|
+
eligible: list[str],
|
|
602
|
+
report_path: Path,
|
|
603
|
+
) -> tuple[dict[str, str] | None, dict[str, int]]:
|
|
604
|
+
"""Collect CPython outcomes for the eligible modules via a pytest subprocess.
|
|
605
|
+
|
|
606
|
+
A nonzero pytest exit code caused by failing tests is expected and not an
|
|
607
|
+
infrastructure failure; only a missing or malformed report is.
|
|
608
|
+
|
|
609
|
+
Args:
|
|
610
|
+
repo_root: Repository root used as the pytest working directory.
|
|
611
|
+
eligible: Repo-relative eligible module paths to run.
|
|
612
|
+
report_path: Destination of the dual-run plugin's JSON report.
|
|
613
|
+
|
|
614
|
+
Returns:
|
|
615
|
+
Tuple of the outcome map (or ``None`` on infrastructure failure) and
|
|
616
|
+
the nodeid-to-parametrize-index map.
|
|
617
|
+
|
|
618
|
+
"""
|
|
619
|
+
import os
|
|
620
|
+
import subprocess
|
|
621
|
+
import sys
|
|
622
|
+
|
|
623
|
+
report_path.parent.mkdir(parents=True, exist_ok=True)
|
|
624
|
+
env = {**os.environ, "WEBCOMPY_DUALRUN_REPORT": str(report_path)}
|
|
625
|
+
command = [
|
|
626
|
+
sys.executable,
|
|
627
|
+
"-m",
|
|
628
|
+
"pytest",
|
|
629
|
+
*sorted(eligible),
|
|
630
|
+
"-p",
|
|
631
|
+
"webcompy_cli._dualrun_pytest_plugin",
|
|
632
|
+
"-q",
|
|
633
|
+
"--tb=no",
|
|
634
|
+
"--no-header",
|
|
635
|
+
]
|
|
636
|
+
completed = subprocess.run(command, cwd=repo_root, env=env, capture_output=True, check=False)
|
|
637
|
+
try:
|
|
638
|
+
data = json.loads(report_path.read_text(encoding="utf-8"))
|
|
639
|
+
outcomes = {str(k): str(v) for k, v in data.get("outcomes", {}).items()}
|
|
640
|
+
indices = {str(k): int(v) for k, v in data.get("param_indices", {}).items()}
|
|
641
|
+
except (OSError, json.JSONDecodeError):
|
|
642
|
+
print(
|
|
643
|
+
"[browser-dualrun] warning: CPython subprocess produced no usable report "
|
|
644
|
+
f"(exit={completed.returncode}); stderr tail:\n{completed.stderr.decode(errors='replace')[-2000:]}",
|
|
645
|
+
flush=True,
|
|
646
|
+
)
|
|
647
|
+
return None, {}
|
|
648
|
+
return outcomes, indices
|