-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathexample_test_kit.py
More file actions
executable file
·1721 lines (1558 loc) · 57.6 KB
/
Copy pathexample_test_kit.py
File metadata and controls
executable file
·1721 lines (1558 loc) · 57.6 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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Cross-interpreter example smoke test harness.
From repo root:
python tools/example_test_kit.py
python tools/example_test_kit.py --order interpreters
python tools/example_test_kit.py --only-example calculator --only-interpreter micropython
python tools/example_test_kit.py --only-interpreter circuitpython python.exe
"""
from __future__ import annotations
import argparse
from concurrent.futures import ThreadPoolExecutor, as_completed
import json
import os
from pathlib import Path
import re
import shutil
import subprocess
import sys
import tempfile
import time
import urllib.error
import urllib.request
from sibling_repos import apply_sibling_env
import tomllib
def _ensure_user_micropy_lib(env: dict) -> None:
"""Preserve MicroPython defaults when ``MICROPYPATH`` is overridden.
A shell ``MICROPYPATH=.:lib:utils`` *replaces* the interpreter default path,
which drops both ``.frozen`` (lvgl / ``display_driver``) and
``~/.micropython/lib`` (``board_config`` from pydevices-desktop / mip).
Append those entries when missing so subprocess interpreters still resolve them
after the working-tree ``lib/`` prefix.
"""
cur = env.get("MICROPYPATH")
if not cur:
return
parts = cur.split(os.pathsep)
extras: list[str] = []
if ".frozen" not in parts:
extras.append(".frozen")
user_lib = Path.home() / ".micropython" / "lib"
if user_lib.is_dir():
lib = str(user_lib)
if lib not in parts:
extras.append(lib)
if extras:
env["MICROPYPATH"] = cur + os.pathsep + os.pathsep.join(extras)
REPO = Path(__file__).resolve().parent.parent
TOOLS = REPO / "tools"
SRC = REPO / "lib"
INTERPRETERS_TOML = TOOLS / "example_interpreters.toml"
MANIFEST_TOML = TOOLS / "example_test_manifest.toml"
WRAPPER = TOOLS / "example_test_wrapper.py"
SERVE = TOOLS / "serve.py"
RESULT_RE = re.compile(r"^EXAMPLE_RESULT=(.+)$", re.MULTILINE)
# Android logcat may carry either wrapper EXAMPLE_RESULT or lv_test_timer KIT_RESULT.
ANDROID_RESULT_RE = re.compile(r"^(?:.*\s)?(?:EXAMPLE_RESULT|KIT_RESULT)=(.+)$", re.MULTILINE)
ANDROID_PACKAGE_ID = os.environ.get("PACKAGE_ID", "org.pydevices.launcher")
def _find_android_runner() -> Path:
"""Locate android.py, the host tool that stages a script onto the Runner APK.
The older android-runner/scripts/android.sh was retired in August
2026 once android.py covered every one of its flags; ANDROID_SH is still
honored as an environment override for anyone with it in their shell profile.
"""
env_runner = os.environ.get("ANDROID_RUNNER") or os.environ.get("ANDROID_SH")
if env_runner:
return Path(env_runner)
which_py = shutil.which("android.py")
if which_py:
return Path(which_py)
return REPO.parent / "pydevices" / "bin" / "android.py"
ANDROID_RUNNER = _find_android_runner()
# Retained alias: this name is used throughout the module and in call sites below.
ANDROID_SH = ANDROID_RUNNER
# Short wall clocks: enough for inject/poll quit; override via --duration-s / --timeout-s.
DEFAULT_DURATION = 2
DEFAULT_TIMEOUT = 15
DEFAULT_ONESHOT_TIMEOUT = 10
# Android emulator paint is slow (splash + first EGL presents). Oneshot hold runs
# in-app after android.py returns; observe window must cover that hold.
ANDROID_ONESHOT_HOLD_S = 20
ANDROID_OBSERVE_S = 20
ANDROID_STAGE_TIMEOUT_S = 120
PYSCRIPT_PORT = 8000
SUBPROCESS_INTERPRETER_KIND = "subprocess"
INTERPRETER_TIMING_KEYS = ("duration_s", "timeout_s", "oneshot_timeout_s")
# Desktop SDL subprocesses — preferred sync matrix (skip async-only hosts).
SYNC_INTERPRETERS = (
"micropython",
"micropython.exe",
"circuitpython",
"cpython-venv",
"python.exe",
)
# Full preferred async matrix (includes pyscript + jupyter).
ASYNC_INTERPRETERS = (*SYNC_INTERPRETERS, "pyscript", "jupyter")
def _temp_dir() -> Path:
return Path(
os.environ.get("TEMP")
or os.environ.get("TMPDIR")
or os.environ.get("TMP")
or tempfile.gettempdir()
)
def load_toml(path: Path) -> dict:
return tomllib.loads(path.read_text(encoding="utf-8"))
def _split_list(values: list[str] | None) -> list[str] | None:
if not values:
return None
out: list[str] = []
for item in values:
for part in item.split(","):
part = part.strip()
if part:
out.append(part)
return out or None
def load_interpreters() -> dict[str, dict]:
data = load_toml(INTERPRETERS_TOML)
return data.get("interpreters", {})
def load_manifest() -> tuple[dict, dict]:
data = load_toml(MANIFEST_TOML)
defaults = data.get("defaults", {})
examples = data.get("examples", {})
return defaults, examples
def _display_exclusion_label(meta: dict) -> str | None:
"""Label for examples shown in the matrix but not run by default."""
if meta.get("kind") == "harness":
return None
parts: list[str] = []
if meta.get("matrix") is False:
parts.append("matrix=false")
if meta.get("kind") == "legacy" and meta.get("quit") == "pending":
parts.append("legacy/pending")
return ", ".join(parts) if parts else None
def matrix_examples(
examples: dict[str, dict],
only: list[str] | None,
*,
all_except_harness: bool = False,
) -> dict[str, dict]:
"""Examples to execute. Harnesses are always excluded."""
out = {}
for name, meta in examples.items():
if meta.get("kind") == "harness":
continue
if only and name not in only:
continue
if not all_except_harness and _display_exclusion_label(meta):
continue
out[name] = meta
return out
def display_only_examples(
examples: dict[str, dict],
only: list[str] | None,
*,
all_except_harness: bool,
) -> dict[str, str]:
"""Examples listed in the matrix output but not executed (default mode only)."""
if all_except_harness:
return {}
out: dict[str, str] = {}
for name, meta in examples.items():
if meta.get("kind") == "harness":
continue
if only and name not in only:
continue
label = _display_exclusion_label(meta)
if label:
out[name] = label
return out
def append_display_rows(
rows: list[dict],
display_only: dict[str, str],
interpreters: dict[str, dict],
all_examples: dict[str, dict],
) -> list[dict]:
"""Add one row per (example, interpreter) for manifest entries not run by default."""
for example_id, label in sorted(display_only.items()):
example_meta = all_examples[example_id]
for interpreter_id in sorted(interpreters):
if not example_allowed_on_interpreter(example_meta, interpreter_id):
continue
rows.append(
{
"example": example_id,
"interpreter": interpreter_id,
"summary": label,
"display_only": True,
"returncode": 0,
"timed_out": False,
"result": {"status": "display_only", "label": label},
"stdout_tail": "",
"stderr_tail": "",
}
)
return rows
def _expand_user(path: str) -> str:
return os.path.expanduser(path)
def resolve_interpreter_exe(interpreter_id: str, meta: dict) -> str | None:
kind = meta.get("kind", SUBPROCESS_INTERPRETER_KIND)
if kind != SUBPROCESS_INTERPRETER_KIND:
return interpreter_id
command = meta.get("command", [])
if not command:
return None
raw = command[0]
if raw.startswith("repo:"):
rel = raw.split(":", 1)[1]
candidate = REPO / rel
return str(candidate) if candidate.exists() else None
if raw == ".venv/bin/python":
candidate = REPO / ".venv" / "bin" / "python"
return str(candidate) if candidate.exists() else None
expanded = _expand_user(raw)
if Path(expanded).exists():
return expanded
for rule in meta.get("resolve", []):
if rule == "PATH":
found = shutil.which(Path(raw).name)
if found:
return found
elif rule.startswith("~/"):
candidate = _expand_user(rule)
if Path(candidate).exists():
return candidate
elif rule.startswith("repo:"):
candidate = REPO / rule.split(":", 1)[1]
if candidate.exists():
return str(candidate)
return shutil.which(Path(raw).name)
def _pick_adb_bin() -> str | None:
override = os.environ.get("ADB")
if override:
return override
if shutil.which("adb.exe"):
return "adb.exe"
if shutil.which("adb"):
return "adb"
return None
def _adb_base_cmd(adb_bin: str) -> list[str]:
cmd = [adb_bin]
serial = os.environ.get("ANDROID_SERIAL")
if serial:
cmd.extend(["-s", serial])
return cmd
def android_interpreter_available() -> bool:
"""True when android.py, adb, a device, and the launcher APK are present."""
if not ANDROID_SH.is_file():
return False
adb_bin = _pick_adb_bin()
if adb_bin is None:
return False
try:
proc = subprocess.run(
[*_adb_base_cmd(adb_bin), "devices"],
capture_output=True,
text=True,
timeout=15,
check=False,
)
except (OSError, subprocess.TimeoutExpired):
return False
devices = [
line.split()[0]
for line in (proc.stdout or "").replace("\r", "").splitlines()[1:]
if line.strip().endswith("\tdevice")
or (len(line.split()) >= 2 and line.split()[1] == "device")
]
if not devices:
return False
try:
path_proc = subprocess.run(
[*_adb_base_cmd(adb_bin), "shell", "pm", "path", ANDROID_PACKAGE_ID],
capture_output=True,
text=True,
timeout=15,
check=False,
)
except (OSError, subprocess.TimeoutExpired):
return False
return bool((path_proc.stdout or "").strip())
def interpreter_available(interpreter_id: str, meta: dict) -> bool:
kind = meta.get("kind", SUBPROCESS_INTERPRETER_KIND)
if kind == SUBPROCESS_INTERPRETER_KIND:
return resolve_interpreter_exe(interpreter_id, meta) is not None
if kind == "pyscript":
return SERVE.exists()
if kind == "jupyter":
jupyter = REPO / ".venv" / "bin" / "jupyter"
return jupyter.exists()
if kind == "android":
return android_interpreter_available()
return False
def example_allowed_on_interpreter(example_meta: dict, interpreter_id: str) -> bool:
skip = example_meta.get("skip_interpreters", [])
if interpreter_id in skip:
return False
allowed = example_meta.get("interpreters")
return not (allowed and interpreter_id not in allowed and "*" not in allowed)
def parse_result(stdout: str) -> dict | None:
for match in RESULT_RE.finditer(stdout):
try:
return json.loads(match.group(1))
except json.JSONDecodeError:
continue
return None
def summarize(result: dict | None, returncode: int, timed_out: bool) -> str:
if timed_out:
return "hang"
if result is None:
return "no_result" if returncode == 0 else f"exit_{returncode}"
status = result.get("status", "?")
if status == "skip":
return "skip"
if status == "ok":
backend = result.get("backend", "?")
if backend == "headless":
return "ok"
return f"{backend}, ok"
if status == "error":
err = result.get("error", "error")
return f"error: {err}"
return status
def interpreter_timing_defaults(global_defaults: dict, interpreter_meta: dict) -> dict:
"""Merge per-interpreter timing overrides from example_interpreters.toml."""
merged = dict(global_defaults)
for key in INTERPRETER_TIMING_KEYS:
if key in interpreter_meta:
merged[key] = interpreter_meta[key]
return merged
def example_timing(
example_meta: dict, manifest_defaults: dict, interpreter_defaults: dict
) -> tuple[float, float]:
kind = example_meta.get("kind", "loop")
duration = float(
example_meta.get(
"duration_s",
interpreter_defaults.get(
"duration_s",
manifest_defaults.get("duration_s", DEFAULT_DURATION),
),
)
)
if kind == "oneshot":
timeout = float(
example_meta.get(
"oneshot_timeout_s",
example_meta.get(
"timeout_s",
interpreter_defaults.get(
"oneshot_timeout_s",
manifest_defaults.get("oneshot_timeout_s", DEFAULT_ONESHOT_TIMEOUT),
),
),
)
)
else:
timeout = float(
example_meta.get(
"timeout_s",
interpreter_defaults.get(
"timeout_s",
manifest_defaults.get("timeout_s", DEFAULT_TIMEOUT),
),
)
)
return duration, timeout
def run_unit_tests() -> int:
print("Running unit tests (python -m unittest discover -s tests)...", file=sys.stderr)
proc = subprocess.run(
[sys.executable, "-m", "unittest", "discover", "-s", "tests"],
cwd=str(REPO),
check=False,
)
return proc.returncode
def run_subprocess_case(
interpreter_id: str,
exe: str,
example_id: str,
example_meta: dict,
duration: float,
timeout: float,
) -> dict:
wrapper_rel = os.path.relpath(WRAPPER, SRC)
script = example_meta.get("script", f"examples/{example_id}.py")
kind = example_meta.get("kind", "loop")
quit_mode = example_meta.get("quit", "poll")
bootstrap = example_meta.get("bootstrap", "full")
cmd = [exe]
if interpreter_id == "micropython.exe":
cmd.extend(["-X", "heapsize=64M"])
cmd.extend(
[
wrapper_rel,
example_id,
"--script",
script,
"--kind",
kind,
"--quit",
quit_mode,
"--bootstrap",
bootstrap,
"--duration",
str(duration),
"--timeout",
str(timeout),
]
)
env = os.environ.copy()
apply_sibling_env(env, repo_root=str(REPO))
_ensure_user_micropy_lib(env)
# Windows PE under WSL cannot read Linux-exported env; pass via argv + env_set.
timer_async = env.get("PYDEVICES_TIMER_ASYNC")
if timer_async is not None:
cmd.extend(["--timer-async", str(timer_async)])
multimer_backend = env.get("MULTIMER_BACKEND")
if multimer_backend:
cmd.extend(["--multimer-backend", str(multimer_backend)])
# Do not forward SDL_* to Windows PE. WSL-exported env is invisible to
# .exe children (so unix stays headless via the shell export), and PE
# should keep a real Windows video driver — dummy there hides the brief
# window that confirms the cell is running.
#
# PE also cannot see PYTHONUNBUFFERED from the WSL shell; pass it so
# CPython .exe flushes EXAMPLE_RESULT / init lines before a timeout kill.
if interpreter_id.endswith(".exe"):
cmd.extend(["--env", "PYTHONUNBUFFERED=1"])
#
# PE stdout via pipes is often empty after a timeout kill (process was
# still usable; quit just did not end it). Write PE output to temp files
# so tails survive TimeoutExpired.
is_pe = interpreter_id.endswith(".exe")
out_path = err_path = None
out_f = err_f = None
timed_out = False
returncode = -1
stdout = ""
stderr = ""
try:
if is_pe:
with tempfile.NamedTemporaryFile(
"w+", encoding="utf-8", delete=False, suffix=".stdout"
) as out_f, tempfile.NamedTemporaryFile(
"w+", encoding="utf-8", delete=False, suffix=".stderr"
) as err_f:
out_path, err_path = out_f.name, err_f.name
try:
proc = subprocess.run(
cmd,
cwd=str(SRC),
stdout=out_f,
stderr=err_f,
timeout=timeout + 5,
env=env,
stdin=subprocess.DEVNULL,
check=False,
)
timed_out = False
returncode = proc.returncode
except subprocess.TimeoutExpired:
timed_out = True
returncode = -1
stdout = Path(out_path).read_text(encoding="utf-8", errors="replace")
stderr = Path(err_path).read_text(encoding="utf-8", errors="replace")
else:
try:
proc = subprocess.run(
cmd,
cwd=str(SRC),
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=timeout + 5,
env=env,
stdin=subprocess.DEVNULL,
check=False,
)
timed_out = False
returncode = proc.returncode
stdout = proc.stdout or ""
stderr = proc.stderr or ""
except subprocess.TimeoutExpired as exc:
timed_out = True
returncode = -1
stdout = (exc.stdout or "") if isinstance(exc.stdout, str) else ""
stderr = (exc.stderr or "") if isinstance(exc.stderr, str) else ""
finally:
for path in (out_path, err_path):
if path:
try:
Path(path).unlink(missing_ok=True)
except OSError:
pass
result = parse_result(stdout)
summary = summarize(result, returncode, timed_out)
return {
"example": example_id,
"interpreter": interpreter_id,
"summary": summary,
"returncode": returncode,
"timed_out": timed_out,
"duration_s": duration,
"timeout_s": timeout,
"result": result,
"stdout_tail": stdout[-2000:] if stdout else "",
"stderr_tail": stderr[-1000:] if stderr else "",
}
_server_pid: int | None = None
def _server_ready(port: int = PYSCRIPT_PORT) -> bool:
try:
with urllib.request.urlopen(
f"http://127.0.0.1:{port}/.site/pyscript/harness.html", timeout=2
) as resp:
return resp.status == 200
except (urllib.error.URLError, TimeoutError, OSError, ConnectionError):
return False
PACKAGES_DIR = REPO / "packages"
def _pyscript_header_lists(script_path: Path) -> tuple[list[str], list[str], list[str]]:
"""Read ``# modules:`` / ``# manifests:`` / ``# deps:`` from an example (first 10 lines)."""
modules: list[str] = []
manifests: list[str] = []
deps: list[str] = []
if not script_path.is_file():
return modules, manifests, deps
try:
with open(script_path, encoding="utf-8") as fh:
for i, line in enumerate(fh):
if i >= 10:
break
s = line.strip()
if s.startswith("# modules:"):
body = s.split(":", 1)[1].strip()
modules = [p.strip() for p in body.split(",") if p.strip()]
elif s.startswith("# manifests:"):
body = s.split(":", 1)[1].strip()
manifests = [p.strip() for p in body.split(",") if p.strip()]
elif s.startswith("# deps:"):
body = s.split(":", 1)[1].strip()
deps = [p.strip() for p in body.split(",") if p.strip()]
except OSError:
pass
return modules, manifests, deps
def _pyscript_gallery_value(script_path: Path) -> str | None:
"""Return ``featured`` / ``skip`` / ``binaries`` from ``# gallery:``, or None."""
if not script_path.is_file():
return None
try:
with open(script_path, encoding="utf-8") as fh:
for i, line in enumerate(fh):
if i >= 10:
break
s = line.strip()
if s.startswith("# gallery:"):
body = s.split(":", 1)[1].strip().lower()
token = body.split(",")[0].strip()
return token or None
except OSError:
pass
return None
def pyscript_skips_binaries(example_id: str, example_meta: dict) -> bool:
"""True when the example opts out of PyScript because mip cannot install binaries."""
script = example_meta.get("script", f"examples/{example_id}.py")
return _pyscript_gallery_value(SRC / script) == "binaries"
def pyscript_harness_query(example_id: str, example_meta: dict) -> str:
"""Build loader query via ``url_maker`` (modules/manifests/deps) for harness.html."""
scripts_dir = str(REPO / "scripts")
if scripts_dir not in sys.path:
sys.path.insert(0, scripts_dir)
from url_maker import urls_from_deps
script = example_meta.get("script", f"examples/{example_id}.py")
script_path = SRC / script
extra_modules, extra_manifests, deps = _pyscript_header_lists(script_path)
modules: list[str] = []
manifests: list[str] = []
if (PACKAGES_DIR / f"{example_id}.json").is_file() and (
SRC / "examples" / example_id
).is_dir():
manifests = [example_id]
elif script_path.is_file() and script_path.parent != SRC / "examples":
pkg = script_path.parent.name
if (PACKAGES_DIR / f"{pkg}.json").is_file() and (SRC / "examples" / pkg).is_dir():
manifests = [pkg]
# Entry must be the example stem (e.g. roku_lvgl), not a sibling
# listed in ``# modules:`` — those live inside the package and are
# provided via sys.path after manifest install (see ps_loader).
if example_id != pkg:
modules = [example_id]
# Drop extras that are files inside the package directory.
extra_modules = [
m
for m in extra_modules
if m != example_id and not (script_path.parent / f"{m}.py").is_file()
]
else:
modules = [example_id]
else:
modules = [example_id] + [m for m in extra_modules if m != example_id]
for name in extra_modules:
if name not in modules:
modules.append(name)
for name in extra_manifests:
if name not in manifests:
manifests.append(name)
return urls_from_deps(
modules=modules,
manifests=manifests,
deps=deps,
interpreter="micropython",
).lstrip("?")
def _kill_pyscript_port(port: int = PYSCRIPT_PORT) -> None:
"""Free ``port`` when a prior serve.py is wedged (listening but not HTTP-ready)."""
global _server_pid
if _server_pid is not None:
try:
os.kill(_server_pid, 9)
except OSError:
pass
_server_pid = None
# Best-effort: anything still bound to the port (stale kit / manual serve).
subprocess.run(
["fuser", "-k", f"{port}/tcp"],
check=False,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
time.sleep(0.2)
def ensure_pyscript_server(port: int = PYSCRIPT_PORT) -> None:
global _server_pid
if _server_ready(port):
return
# Port may still be held by a dead/hung serve.py from an earlier case.
_kill_pyscript_port(port)
print(f"Starting {SERVE} on port {port}...", file=sys.stderr)
# Access logs go to stderr; an unread PIPE fills (~64KiB) and deadlocks
# ThreadingHTTPServer mid-matrix (HTML loads, MicroPython never starts).
serve_log = _temp_dir() / "pyscript_serve_kit.log"
serve_log.parent.mkdir(parents=True, exist_ok=True)
with open(serve_log, "ab") as log_fh:
proc = subprocess.Popen(
[sys.executable, str(SERVE), "-p", str(port)],
cwd=str(REPO),
stdout=subprocess.DEVNULL,
stderr=log_fh,
)
_server_pid = proc.pid
for _ in range(100):
if _server_ready(port):
return
if proc.poll() is not None:
try:
err_tail = serve_log.read_bytes()[-500:].decode("utf-8", "replace")
except OSError:
err_tail = ""
raise RuntimeError(
f"PyScript server exited before ready on port {port}: {err_tail[-500:]}"
)
time.sleep(0.1)
raise RuntimeError(f"PyScript server did not become ready on port {port}")
def run_pyscript_case(
example_id: str,
example_meta: dict,
duration: float,
timeout: float,
port: int = PYSCRIPT_PORT,
) -> dict:
if pyscript_skips_binaries(example_id, example_meta):
result = {
"interpreter": "pyscript",
"status": "skip",
"example": example_id,
"error": "skip: binaries (browser mip cannot install binary assets)",
}
return {
"example": example_id,
"interpreter": "pyscript",
"summary": "skip",
"returncode": 0,
"timed_out": False,
"duration_s": duration,
"timeout_s": timeout,
"result": result,
"stdout_tail": "EXAMPLE_RESULT=" + json.dumps(result, separators=(",", ":")),
"stderr_tail": "",
}
ensure_pyscript_server(port)
query = pyscript_harness_query(example_id, example_meta)
url = (
f"http://127.0.0.1:{port}/pydevices-examples/pyscript/harness.html?{query}"
f"&autotest=1&duration={int(duration)}&timeout={int(timeout)}"
)
try:
from pyscript_autotest import run_autotest
except ImportError:
tools = str(TOOLS)
if tools not in sys.path:
sys.path.insert(0, tools)
from pyscript_autotest import run_autotest
try:
result = run_autotest(url, duration_s=duration, timeout_s=timeout)
except Exception as exc:
return {
"example": example_id,
"interpreter": "pyscript",
"summary": f"error: {exc}",
"returncode": 1,
"timed_out": False,
"duration_s": duration,
"timeout_s": timeout,
"result": {"status": "error", "error": str(exc)},
"stdout_tail": "",
"stderr_tail": str(exc),
}
if result.get("status") == "skip" or result.get("error", "").startswith(
"playwright not installed"
):
return {
"example": example_id,
"interpreter": "pyscript",
"summary": "needs_playwright",
"returncode": -1,
"timed_out": False,
"duration_s": duration,
"timeout_s": timeout,
"result": result,
"stdout_tail": "",
"stderr_tail": "",
}
summary = summarize(result, 0, False)
line = "EXAMPLE_RESULT=" + json.dumps(result, separators=(",", ":"))
return {
"example": example_id,
"interpreter": "pyscript",
"summary": summary,
"returncode": 0 if result.get("status") == "ok" else 1,
"timed_out": result.get("smoke") == "js_timeout",
"duration_s": duration,
"timeout_s": timeout,
"result": result,
"stdout_tail": line[-2000:],
"stderr_tail": "\n".join((result.get("console_errors") or [])[:5])[-1000:],
}
def _write_jupyter_notebook(example_id: str, example_meta: dict, duration_s: float) -> Path:
# Prefer dotted examples imports (cwd=lib, ``.`` on PYTHONPATH). Always
# ``import utils.path`` so sibling ``utils/`` (keypins, mip, …) matches the
# subprocess wrapper. Scripts outside ``lib/examples/`` (such as the
# sibling core timer probe) are loaded by path.
script = example_meta.get("script", f"examples/{example_id}.py")
script_path = (SRC / script).resolve()
try:
under_examples = script_path.is_relative_to(SRC / "examples")
except AttributeError:
under_examples = str(script_path).startswith(str((SRC / "examples").resolve()))
if under_examples:
raw_import = example_meta.get("import", example_id)
if raw_import.startswith("examples."):
import_line = f"import {raw_import}"
elif "." in raw_import:
import_line = f"import examples.{raw_import}"
else:
import_line = f"from examples import {raw_import}"
else:
import_line = "import runpy\nrunpy.run_path(%r, run_name=__name__)" % (str(script_path),)
tools_rel = os.path.relpath(TOOLS, SRC)
test_mode_source = "\n".join(
[
"import sys",
f"sys.path.insert(0, {tools_rel!r})",
"import utils.path # noqa: F401",
"import pydevices_test_mode",
"pydevices_test_mode.ENABLED = True",
f"pydevices_test_mode.DURATION_S = {duration_s}",
"pydevices_test_mode.install_deadline_hook()",
"",
]
)
cells = [
{
"cell_type": "code",
"metadata": {},
"execution_count": None,
"outputs": [],
"source": [test_mode_source],
},
{
"cell_type": "code",
"metadata": {},
"execution_count": None,
"outputs": [],
"source": [f"{import_line}\n"],
},
]
nb = {
"nbformat": 4,
"nbformat_minor": 5,
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3",
},
"language_info": {"name": "python"},
},
"cells": cells,
}
# Unique path so concurrent matrix workers (interpreter x timer_async) do not clobber.
mode = os.environ.get("PYDEVICES_TIMER_ASYNC", "x")
out = SRC / f"run-{example_id}-async{mode}-{os.getpid()}.ipynb"
out.write_text(json.dumps(nb, indent=1) + "\n", encoding="utf-8")
return out
def run_jupyter_case(
example_id: str,
example_meta: dict,
duration: float,
timeout: float,
) -> dict:
venv_python = REPO / ".venv" / "bin" / "python"
jupyter = REPO / ".venv" / "bin" / "jupyter"
if not venv_python.exists() or not jupyter.exists():
return {
"example": example_id,
"interpreter": "jupyter",
"summary": "missing",
"returncode": -1,
"timed_out": False,
"duration_s": duration,
"timeout_s": timeout,
"result": None,
"stdout_tail": "",
"stderr_tail": "Jupyter venv not found",
}
nb_path = _write_jupyter_notebook(example_id, example_meta, duration)
nbconvert_out = nb_path.with_name(f"{nb_path.stem}.nbconvert.ipynb")
cmd = [
str(jupyter),
"nbconvert",
"--execute",
"--to",
"notebook",
"--ExecutePreprocessor.timeout={}".format(int(timeout)),
"--ExecutePreprocessor.kernel_name=python3",
str(nb_path),
]
env = os.environ.copy()
apply_sibling_env(env, repo_root=str(REPO), prepend_paths=[str(SRC)])
_ensure_user_micropy_lib(env)
try:
try:
proc = subprocess.run(
cmd,
cwd=str(SRC),
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=timeout + 30,
env=env,
check=False,
)
timed_out = False
stdout = proc.stdout or ""
stderr = proc.stderr or ""
returncode = proc.returncode
except subprocess.TimeoutExpired as exc:
timed_out = True
returncode = -1
stdout = (exc.stdout or "") if isinstance(exc.stdout, str) else ""
stderr = (exc.stderr or "") if isinstance(exc.stderr, str) else ""
finally:
nbconvert_out.unlink(missing_ok=True)
nb_path.unlink(missing_ok=True)
ok = returncode == 0 and not timed_out
result = {
"example": example_id,
"status": "ok" if ok else "error",
"backend": "JNDisplay",
"duration_s": duration,
}
if not ok:
result["error"] = stderr[-200:] if stderr else f"exit_{returncode}"
summary = summarize(result, returncode, timed_out)
return {
"example": example_id,
"interpreter": "jupyter",
"summary": summary,
"returncode": returncode,
"timed_out": timed_out,
"duration_s": duration,
"timeout_s": timeout,
"result": result,
"stdout_tail": stdout[-2000:] if stdout else "",
"stderr_tail": stderr[-1000:] if stderr else "",
}