Repository Public MIT Research preview
1#!/usr/bin/env python32"""Validate demos and labs: they run, tests pass, solutions do not leak, instructions are safe.34 validate_labs.py [--session S01] [--demo-only] [--tests-only]5Used by `make demo`, `make test`, `make demos`, `make tests`.6"""7from __future__ import annotations89import argparse10import re11import subprocess12import sys1314from atlaslib import ROOT, Report, load_course, select_sessions, session_dir1516DANGEROUS = {17 "recursive delete": r"\brm\s+-[a-zA-Z]*r[a-zA-Z]*f|\brm\s+-[a-zA-Z]*f[a-zA-Z]*r",18 "pipe remote script to a shell": r"(curl|wget)[^\n|]*\|\s*(sudo\s+)?(ba|z)?sh",19 "sudo": r"\bsudo\b",20 "force push": r"git\s+push\s+[^\n]*--force",21 "disk format": r"\bmkfs\b|\bdd\s+if=",22}23NETWORK_IMPORTS = re.compile(r"^\s*(import|from)\s+(requests|urllib|http\.client|socket|httpx|aiohttp)\b", re.M)242526def demo_entry(d):27 hits = sorted((d / "demos" / "src").rglob("demo.py"))28 return hits[0] if hits else None293031def main() -> int:32 ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)33 ap.add_argument("--session")34 ap.add_argument("--demo-only", action="store_true")35 ap.add_argument("--tests-only", action="store_true")36 ap.add_argument("--show", action="store_true", help="print the demo output")37 args = ap.parse_args()38 rep = Report("labs")39 for s in select_sessions(load_course(), args.session):40 d, sid = session_dir(s), s["id"]41 entry = demo_entry(d)42 if not args.tests_only:43 if not entry:44 rep.error(f"{sid}: no demos/src/**/demo.py")45 else:46 r = subprocess.run([sys.executable, str(entry)], capture_output=True, text=True, timeout=120)47 if args.show:48 print(r.stdout)49 if r.returncode != 0:50 rep.error(f"{sid}: demo failed\n{r.stderr[-800:]}")51 else:52 rep.note(f"{sid}: demo ran ({len(r.stdout.splitlines())} lines of output)")53 readme = (d / "demos" / "README.md").read_text(encoding="utf-8")54 if r.stdout.strip() not in readme:55 rep.error(f"{sid}: demos/README.md 'expected output' differs from the real demo output")56 if not args.demo_only:57 tests = d / "demos" / "tests"58 r = subprocess.run([sys.executable, "-m", "pytest", "-q", str(tests)], capture_output=True, text=True, cwd=ROOT)59 last = (r.stdout.strip().splitlines() or ["no output"])[-1]60 (rep.note if r.returncode == 0 else rep.error)(f"{sid}: pytest — {last}")61 if r.returncode != 0:62 print(r.stdout[-2500:], file=sys.stderr)63 if args.demo_only or args.tests_only:64 continue65 for sub in ("starter", "solution"):66 if not any((d / "labs" / sub).glob("*.py")):67 rep.error(f"{sid}: labs/{sub}/ has no Python file")68 instructions = (d / "labs" / "instructions.md").read_text(encoding="utf-8")69 if "solution/" in instructions and "enseignant" not in instructions:70 rep.error(f"{sid}: lab instructions point learners to the solution")71 for label, pat in DANGEROUS.items():72 for f in [d / "labs" / "instructions.md", d / "demos" / "README.md"]:73 if re.search(pat, f.read_text(encoding="utf-8")):74 rep.error(f"{sid}: {f.name} contains a dangerous command pattern ({label})")75 for py in list((d / "labs").rglob("*.py")) + list((d / "demos" / "src").rglob("*.py")):76 if NETWORK_IMPORTS.search(py.read_text(encoding="utf-8")):77 rep.error(f"{sid}: {py.relative_to(d)} imports a network library; labs must run offline (mock APIs)")78 req = (d / "demos" / "requirements.txt").read_text(encoding="utf-8")79 for line in req.splitlines():80 if line.strip() and not line.startswith("#") and "==" not in line:81 rep.error(f"{sid}: unpinned dependency in demos/requirements.txt: {line}")82 for needle in ("Windows", "Python 3"):83 if needle not in instructions + (d / "demos" / "README.md").read_text(encoding="utf-8"):84 rep.error(f"{sid}: demo/lab docs must mention {needle!r} (cross-platform prerequisites)")85 if "sans code" not in instructions.lower() or "défi" not in instructions.lower():86 rep.error(f"{sid}: lab needs a no-code path and an advanced challenge")87 return rep.finish()888990if __name__ == "__main__":91 sys.exit(main())92