freestream / tests /smoke.py
LoveLogicAI's picture
Smoke test: verifies pushed repo artifacts (CLI exit codes, event chain, MCP handshake)
88a5802 verified
Raw History Blame Contribute Delete
7.52 kB
"""FREESTREAM scaffold smoke test β€” runs against the files pushed to the Hub.
Downloads every file from LoveLogicAI/freestream, byte-compiles the Python
package, then exercises CLI exit codes, the event-log hash chain, and the
MCP stdio handshake. Stdlib only. Exits 0 iff every check passes.
"""
import json
import py_compile
import subprocess
import sys
import urllib.request
from pathlib import Path
ROOT = Path("/tmp/freestream")
REPO = "https://huggingface.co/datasets/LoveLogicAI/freestream/resolve/main"
FILES = [
"README.md", "SKILL.md", "LICENSE", "requirements.txt",
"scripts/freestream.py",
"freestream/__init__.py", "freestream/events.py", "freestream/presence.py",
"freestream/persona.py", "freestream/mcp_server.py",
"docs/SPEC-DRIVERS.md", "docs/SPEC-EVENTS.md", "docs/PLATFORMS.md",
"docs/LATENCY.md", "docs/CONSENT.md",
]
results = []
def check(name, ok, detail=""):
results.append((name, ok, detail))
print(f"{'PASS' if ok else 'FAIL'} {name}" + (f" β€” {detail}" if detail else ""))
def fetch(path: str) -> bytes:
with urllib.request.urlopen(f"{REPO}/{path}", timeout=30) as r:
return r.read()
def run_cli(*args, cwd=ROOT / "scripts"):
return subprocess.run(
[sys.executable, str(ROOT / "scripts/freestream.py"), *args],
cwd=cwd, capture_output=True, text=True, timeout=60,
)
# 1. fetch everything -------------------------------------------------------
missing = []
for f in FILES:
dest = ROOT / f
dest.parent.mkdir(parents=True, exist_ok=True)
try:
dest.write_bytes(fetch(f))
except Exception as e:
missing.append((f, str(e)))
check("fetch 15 files from Hub", not missing, str(missing[:2]))
if missing:
sys.exit(1)
# 2. byte-compile ------------------------------------------------------------
for f in FILES:
if f.endswith(".py"):
try:
py_compile.compile(str(ROOT / f), doraise=True)
check(f"compile {f}", True)
except py_compile.PyCompileError as e:
check(f"compile {f}", False, str(e)[:200])
# 3. CLI: probe β†’ 0 ----------------------------------------------------------
r = run_cli("probe")
probe_ok = r.returncode == 0
try:
probe = json.loads(r.stdout)
except ValueError:
probe = {}
check("probe exits 0", probe_ok, r.stderr[:900] if not probe_ok else "")
check("probe output shape", probe_ok and {"platform", "drivers", "fidelity_rung"} <= set(probe),
f"drivers={probe.get('drivers')}")
check("probe lists 3 drivers", probe_ok and probe.get("drivers") == ["browser", "livekit", "sip"])
check("probe fidelity_rung is VISEME_STILL on cpu-basic", probe_ok and probe.get("fidelity_rung") == "VISEME_STILL",
str(probe.get("fidelity_rung")))
# 4. CLI: join validation β†’ 2 ------------------------------------------------
r = run_cli("join", "--meet-url", "not-a-url", "--bot-name", "Smoke")
check("join bad URL exits 2", r.returncode == 2, f"got {r.returncode}")
r = run_cli("join", "--meet-url", "https://meet.google.com/abc", "--bot-name", "Smoke")
check("join missing avatar exits 2", r.returncode == 2, f"got {r.returncode}: {r.stderr[:120]}")
# 5. CLI: join capability shortfall β†’ 6 (no playwright / no livekit) ---------
avatar = ROOT / "docs" / "PLATFORMS.md" # >1KB stand-in image
r = run_cli("join", "--meet-url", "https://meet.google.com/abc", "--bot-name", "Smoke",
"--image", str(avatar))
out6 = {}
try:
out6 = json.loads(r.stdout.strip().splitlines()[-1])
except (ValueError, IndexError):
pass
check("join no-deps exits 6", r.returncode == 6, f"got {r.returncode}: {r.stderr[:120]}")
check("exit-6 JSON has capability+remediation", "capability" in out6 and "remediation" in out6, str(out6)[:120])
r = run_cli("join", "--meet-url", "https://meet.example/abc", "--platform", "livekit",
"--driver", "livekit", "--bot-name", "Smoke", "--image", str(avatar))
check("join livekit no-deps exits 6", r.returncode == 6, f"got {r.returncode}")
# 6. CLI: generate-avatar without backend β†’ 6 --------------------------------
r = run_cli("generate-avatar", "--output", "/tmp/avatar.png")
out = {}
try:
out = json.loads(r.stdout.strip().splitlines()[-1])
except (ValueError, IndexError):
pass
check("generate-avatar no-backend exits 6", r.returncode == 6, f"got {r.returncode}")
check("generate-avatar remediation present", "remediation" in out)
# 7. leave on stub driver β†’ clean exit, no traceback -------------------------
r = run_cli("leave", "--session-id", "nonexistent")
check("leave stub exits clean (0)", r.returncode == 0 and "Traceback" not in r.stderr, f"got {r.returncode}")
# 8. event-log hash chain round-trip -----------------------------------------
probe_py = """
import sys, os, json
sys.path.insert(0, '/tmp/freestream')
from freestream.events import EventLog
os.chdir('/tmp')
log = EventLog('/tmp/ev.jsonl')
log.append('a', x=1); log.append('b', y=2); log.append('c', z=3)
ok1, bad1 = EventLog('/tmp/ev.jsonl').verify()
lines = open('/tmp/ev.jsonl').readlines()
t = json.loads(lines[1]); t['payload']['y'] = 999
lines[1] = json.dumps(t, sort_keys=True) + chr(10)
open('/tmp/ev.jsonl', 'w').writelines(lines)
# A tampered log must refuse to load (raise ValueError) β€” that refusal IS the check.
ok2, bad2 = False, None
try:
EventLog('/tmp/ev.jsonl')
except ValueError:
ok2, bad2 = False, 2
print(json.dumps({'ok1': ok1, 'bad1': bad1, 'ok2': ok2, 'bad2': bad2}))
"""
r = subprocess.run([sys.executable, "-c", probe_py],
capture_output=True, text=True, timeout=30)
try:
ev = json.loads(r.stdout.strip())
except ValueError:
ev = {}
check("event log verifies when intact", ev.get("ok1") is True and ev.get("bad1") is None, r.stdout[:120] + r.stderr[:200])
check("event log catches tampering", ev.get("ok2") is False and ev.get("bad2") == 2, str(ev))
# 9. MCP stdio handshake ------------------------------------------------------
reqs = "\n".join([
json.dumps({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}}),
json.dumps({"jsonrpc": "2.0", "id": 2, "method": "tools/list"}),
json.dumps({"jsonrpc": "2.0", "id": 3, "method": "tools/call",
"params": {"name": "session.speak", "arguments": {"text": "hello"}}}),
]) + "\n"
r = subprocess.run([sys.executable, "-m", "freestream.mcp_server"], cwd=str(ROOT),
input=reqs, capture_output=True, text=True, timeout=30)
lines = [json.loads(l) for l in r.stdout.strip().splitlines() if l.strip()]
by_id = {l.get("id"): l for l in lines}
tools = (by_id.get(2, {}).get("result", {}) or {}).get("tools", [])
speak = (by_id.get(3, {}).get("result", {}) or {}).get("content", [{}])[0].get("text", "")
check("MCP initialize responds", 1 in by_id and "protocolVersion" in by_id[1].get("result", {}))
check("MCP tools/list has 4 session tools",
len(tools) == 4 and all(t["name"].startswith("session.") for t in tools),
str([t["name"] for t in tools]))
check("MCP tools/call session.speak accepted", "accepted" in speak, speak[:100])
# 10. SKILL.md frontmatter parses -------------------------------------------
skill = (ROOT / "SKILL.md").read_text()
check("SKILL.md frontmatter present", skill.startswith("---\nname: freestream")
and "openclaw" in skill.split("---")[1])
failed = [n for n, ok, _ in results if not ok]
print(f"\n{len(results) - len(failed)}/{len(results)} checks passed")
if failed:
print("FAILED: " + ", ".join(failed))
sys.exit(1)
print("SMOKE OK")