File size: 1,916 Bytes
ac3dba3 | 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 | """Parse every fenced code block in guides/*.md; run the self-contained python ones.
json blocks: json.loads. bash blocks: bash -n (syntax only, nothing is executed).
python blocks: ast.parse, then executed unless they need a running server.
Run with the project virtual environment: .venv/bin/python tests/check_code_blocks.py
"""
import ast
import json
import os
import re
import subprocess
import sys
from pathlib import Path
root = Path(__file__).resolve().parent.parent
fence = re.compile(r"^```(\w*)\n(.*?)^```", re.S | re.M)
fails, counts = [], {"json": 0, "bash": 0, "python": 0, "python_run": 0}
env = dict(os.environ, PYTHONPATH=str(root / "examples"))
for md in sorted((root / "guides").glob("*.md")):
for m in fence.finditer(md.read_text()):
lang, body = m.group(1), m.group(2)
label = f"{md.name}: {body.strip().splitlines()[0][:50] if body.strip() else ''}"
try:
if lang == "json":
json.loads(body); counts["json"] += 1
elif lang == "bash":
r = subprocess.run(["bash", "-n"], input=body, text=True, capture_output=True)
if r.returncode: raise SyntaxError(r.stderr)
counts["bash"] += 1
elif lang == "python":
ast.parse(body); counts["python"] += 1
if "127.0.0.1:8000" in body or "mcp.run(" in body:
continue # needs a running server / is a server entry point
r = subprocess.run([sys.executable, "-"], input=body, text=True, capture_output=True,
cwd=root / "examples", env=env, timeout=120)
if r.returncode: raise RuntimeError(r.stderr[-400:])
counts["python_run"] += 1
except Exception as e: # noqa: BLE001
fails.append(f"{label} -> {e}")
print(counts)
for f in fails: print("FAIL", f)
sys.exit(1 if fails else 0)
|