-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathrun_all_tests.py
More file actions
381 lines (300 loc) · 12 KB
/
run_all_tests.py
File metadata and controls
381 lines (300 loc) · 12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
#!/usr/bin/env python3
"""Run frontend and backend test suites with a concise summary."""
from __future__ import annotations
import os
import re
import shlex
import subprocess
import sys
import time
import argparse
from dataclasses import dataclass
from pathlib import Path
from typing import List, Optional, Sequence, Tuple
from urllib.error import URLError
from urllib.parse import urlparse
from urllib.request import urlopen
@dataclass
class TestJob:
name: str
commands: List[Sequence[str]]
cwd: Path
@dataclass
class JobResult:
job: TestJob
exit_code: int
tests: Optional[int]
coverage: Optional[str]
rerun_commands: list[str]
def stream_command(command: Sequence[str], cwd: Path) -> Tuple[int, List[str]]:
"""Execute a command, streaming combined output to stdout."""
env = os.environ.copy()
try:
process = subprocess.Popen(
command,
cwd=cwd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
bufsize=1,
env=env,
)
except FileNotFoundError as exc:
print(f"Command not found: {command[0]}")
print(exc)
return 127, []
assert process.stdout is not None # for type checkers
output_lines: List[str] = []
for line in process.stdout:
print(line, end="")
output_lines.append(line)
return process.wait(), output_lines
def print_header(title: str) -> None:
bar = "=" * len(title)
print(f"\n{title}\n{bar}")
def parse_args(argv: Optional[Sequence[str]] = None) -> argparse.Namespace:
parser = argparse.ArgumentParser(description="Run Rawbit test suites with summary output.")
parser.add_argument(
"--e2e-browsers",
choices=["chromium", "all"],
default="chromium",
help=(
"Select which Playwright projects to run when no custom E2E command is provided. "
"Use 'chromium' for the fast default run or 'all' for chromium, firefox, and webkit sequentially."
),
)
return parser.parse_args(argv)
def main(argv: Optional[Sequence[str]] = None) -> None:
args = parse_args(argv)
repo_root = Path(__file__).resolve().parent
# Keep the local gate truly local unless callers override explicitly.
# Playwright reads PLAYWRIGHT_* and the frontend respects VITE_* envs, so
# we set localhost defaults here while still allowing env overrides above.
os.environ.setdefault(
"PLAYWRIGHT_BASE_URL", os.getenv("RUN_ALL_TESTS_BASE_URL", "http://127.0.0.1:3041")
)
os.environ.setdefault(
"PLAYWRIGHT_API_URL", os.getenv("RUN_ALL_TESTS_API_URL", "http://localhost:5007")
)
os.environ.setdefault("VITE_API_BASE_URL", os.environ["PLAYWRIGHT_API_URL"])
backend_proc = None
try:
try:
backend_proc = maybe_start_local_backend(repo_root)
except RuntimeError as exc:
print(f"Failed to start local backend: {exc}")
sys.exit(1)
lint_cmd = os.environ.get("RUN_ALL_TESTS_LINT_CMD")
typecheck_cmd = os.environ.get("RUN_ALL_TESTS_TYPECHECK_CMD")
frontend_cmd = os.environ.get("RUN_ALL_TESTS_FRONTEND_CMD")
e2e_cmd = os.environ.get("RUN_ALL_TESTS_E2E_CMD")
backend_cmd = os.environ.get("RUN_ALL_TESTS_BACKEND_CMD")
def resolve_backend_command() -> Tuple[Sequence[str], Path]:
backend_dir = repo_root / "backend"
if backend_cmd:
return shlex.split(backend_cmd), backend_dir
venv_pytest = repo_root / ".myenv" / "bin" / "pytest"
if venv_pytest.exists():
return [str(venv_pytest), "backend/tests"], repo_root
return [sys.executable, "-m", "pytest"], backend_dir
backend_command, backend_cwd = resolve_backend_command()
def resolve_e2e_commands() -> List[Sequence[str]]:
if e2e_cmd:
return [shlex.split(e2e_cmd)]
if args.e2e_browsers == "all":
return [
["npm", "run", "test:e2e", "--", "--project=chromium", "--workers=2"],
["npm", "run", "test:e2e", "--", "--project=firefox", "--workers=2"],
["npm", "run", "test:e2e", "--", "--project=webkit", "--workers=2"],
]
return [["npm", "run", "test:e2e", "--", "--project=chromium"]]
jobs = [
TestJob(
name="Lint",
commands=[shlex.split(lint_cmd)] if lint_cmd else [["npm", "run", "lint"]],
cwd=repo_root,
),
TestJob(
name="Typecheck",
commands=[shlex.split(typecheck_cmd)] if typecheck_cmd else [["npm", "run", "typecheck"]],
cwd=repo_root,
),
TestJob(
name="Frontend",
commands=[shlex.split(frontend_cmd) if frontend_cmd else ["npm", "run", "test"]],
cwd=repo_root,
),
TestJob(
name="E2E",
commands=resolve_e2e_commands(),
cwd=repo_root,
),
TestJob(name="Backend", commands=[backend_command], cwd=backend_cwd),
]
results: list[JobResult] = []
for job in jobs:
title = f"Running {job.name} Tests"
print_header(title)
accumulated_output: List[str] = []
exit_code = 0
for index, command in enumerate(job.commands, start=1):
prefix = f" ({index}/{len(job.commands)})" if len(job.commands) > 1 else ""
print(f"Command{prefix}: {shlex.join(command)}")
exit_code, output_lines = stream_command(command, job.cwd)
accumulated_output.extend(output_lines)
if exit_code != 0:
if index < len(job.commands):
print("Command failed; skipping remaining commands for job.")
break
tests_count, coverage, reruns = parse_job_output(job.name, accumulated_output)
results.append(JobResult(job, exit_code, tests_count, coverage, reruns))
status = "PASS" if exit_code == 0 else "FAIL"
print(f"\n{job.name} result: {status}\n")
print_header("Test Summary")
any_failures = False
rerun_suggestions: list[str] = []
for result in results:
status = "PASS" if result.exit_code == 0 else "FAIL"
detail_parts = []
if result.tests is not None:
detail_parts.append(f"tests: {result.tests}")
if result.coverage is not None:
detail_parts.append(f"coverage: {result.coverage}")
details = f" ({', '.join(detail_parts)})" if detail_parts else ""
print(f"{result.job.name:9s}: {status}{details}")
if result.exit_code != 0:
any_failures = True
rerun_suggestions.extend(result.rerun_commands)
if rerun_suggestions:
print("\nSuggested rerun commands:")
for command in rerun_suggestions:
print(f" {command}")
if backend_is_local():
print(" (start the local backend first, e.g. '.myenv/bin/python backend/routes.py')")
if any_failures:
sys.exit(1)
finally:
if backend_proc:
stop_process(backend_proc)
def parse_job_output(job_name: str, lines: Sequence[str]) -> Tuple[Optional[int], Optional[str], list[str]]:
if job_name == "Frontend":
tests, coverage = parse_frontend_output(lines)
return tests, coverage, []
if job_name == "E2E":
return parse_e2e_output(lines)
if job_name == "Backend":
tests, coverage = parse_backend_output(lines)
return tests, coverage, []
return None, None, []
def parse_frontend_output(lines: Sequence[str]) -> Tuple[Optional[int], Optional[str]]:
tests: Optional[int] = None
coverage: Optional[str] = None
for line in lines:
match = re.search(r"Tests\s+(\d+)\s+passed", line)
if match:
tests = int(match.group(1))
coverage = extract_coverage_percentage(lines)
return tests, coverage
def parse_backend_output(lines: Sequence[str]) -> Tuple[Optional[int], Optional[str]]:
tests: Optional[int] = None
for line in reversed(lines):
match = re.search(r"(\d+)\s+passed\s+in\s", line)
if match:
tests = int(match.group(1))
break
if tests is None:
for line in reversed(lines):
match = re.search(r"collected\s+(\d+)\s+items", line)
if match:
tests = int(match.group(1))
break
coverage = extract_coverage_percentage(lines)
return tests, coverage
def parse_e2e_output(lines: Sequence[str]) -> Tuple[Optional[int], Optional[str], list[str]]:
tests_total = 0
for line in lines:
for match in re.finditer(r"Running\s+(\d+)\s+tests", line):
tests_total += int(match.group(1))
if tests_total == 0:
for line in lines:
for match in re.finditer(r"(\d+)\s+(?:tests?\s+)?passed", line):
tests_total += int(match.group(1))
reruns: list[str] = []
failure_pattern = re.compile(r"[✘×]\s+\d+\s+\[([^\]]+)\]\s+›\s+([^\s:]+)")
seen: set[tuple[str, str]] = set()
for line in lines:
match = failure_pattern.search(line)
if not match:
continue
project = match.group(1).strip()
spec = match.group(2).strip().split(":", 1)[0]
key = (project, spec)
if key in seen:
continue
seen.add(key)
reruns.append(f"npm run test:e2e -- --project={project} {spec}")
tests_value = tests_total if tests_total else None
return tests_value, None, reruns
def extract_coverage_percentage(lines: Sequence[str]) -> Optional[str]:
for line in reversed(lines):
match = re.search(r"Total coverage:\s*([0-9]+(?:\.[0-9]+)?)%", line)
if match:
return f"{match.group(1)}%"
for line in reversed(lines):
match = re.search(r"TOTAL.*?([0-9]+(?:\.[0-9]+)?)%", line)
if match:
return f"{match.group(1)}%"
return None
def backend_health_url() -> str:
base = os.environ.get("PLAYWRIGHT_API_URL", "http://localhost:5007").rstrip('/')
return f"{base}/healthz"
def backend_is_local() -> bool:
parsed = urlparse(os.environ.get("PLAYWRIGHT_API_URL", "http://localhost:5007"))
return parsed.hostname in {"localhost", "127.0.0.1"}
def wait_for_backend(url: str, timeout: float = 20.0) -> None:
deadline = time.time() + timeout
while time.time() < deadline:
try:
with urlopen(url, timeout=2) as resp: # nosec B310
if resp.status == 200:
return
except URLError:
time.sleep(0.5)
raise RuntimeError(f"Backend did not become healthy at {url} within {timeout:.0f}s")
def maybe_start_local_backend(repo_root: Path):
if not backend_is_local():
return None
health_url = backend_health_url()
try:
wait_for_backend(health_url, timeout=0.01)
return None
except RuntimeError:
pass
if os.environ.get("RUN_ALL_TESTS_SKIP_BACKEND") in {"1", "true", "TRUE"}:
raise RuntimeError("Local backend not running and autostart disabled (RUN_ALL_TESTS_SKIP_BACKEND)")
cmd = [select_backend_python(repo_root), "backend/routes.py"]
proc = subprocess.Popen(
cmd,
cwd=repo_root,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
try:
wait_for_backend(health_url)
return proc
except RuntimeError:
stop_process(proc)
raise
def stop_process(proc: subprocess.Popen) -> None:
proc.terminate()
try:
proc.wait(timeout=5)
except subprocess.TimeoutExpired:
proc.kill()
def select_backend_python(repo_root: Path) -> str:
candidate = repo_root / '.myenv' / 'bin' / 'python'
if candidate.exists():
return str(candidate)
return sys.executable
if __name__ == "__main__":
main()