These grew one bug at a time in a scratch directory and were about to be thrown away, having caught four real regressions between them. Move them in as they are -- plain scripts, stdlib only, no test dependency -- behind a shared harness and `python3 tests/run.py`. The harness exists mostly for its guard. A suite testing the purge path once sandboxed LLMHOST_CONFIG but not LLMHOST_HOME and deleted a live install's data directory; BIN_DIR and SHIM have no env override at all, coming straight off Path.home(). So the harness repoints those into the sandbox and then asserts that every path llmhost could write or delete is inside it, aborting the run if not -- verified by pointing it at a real path and watching it refuse. The model plan the opencode suite needs is now a fixture rather than a file read out of someone's home directory; it carries no key (the key lives in its own file) and its machine-specific fields are pinned. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
113 lines
4.5 KiB
Python
113 lines
4.5 KiB
Python
"""Proxy tests: the model name a client asks for must be honoured or refused, never ignored."""
|
|
import json, threading, urllib.error, urllib.request
|
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
import harness
|
|
|
|
ROOT = harness.setup()
|
|
from llmhost import paths
|
|
from llmhost.backends import mlx
|
|
|
|
harness.guard(paths, ROOT)
|
|
|
|
SERVED = "ornith-1.5-9b"
|
|
REPO = "ornith-ai/Ornith-1.5-9B-MLX-6bit"
|
|
KEY = "sk-test-key"
|
|
seen = [] # bodies the inner (fake mlx_lm) server received
|
|
check = harness.Checks()
|
|
|
|
|
|
class Inner(BaseHTTPRequestHandler):
|
|
protocol_version = "HTTP/1.1"
|
|
def log_message(self, *a): pass
|
|
def do_POST(self):
|
|
n = int(self.headers.get("Content-Length") or 0)
|
|
raw = self.rfile.read(n) if n else b""
|
|
try: seen.append(json.loads(raw or b"{}"))
|
|
except ValueError: seen.append(None)
|
|
body = json.dumps({"id": "x", "object": "chat.completion", "model": "default_model",
|
|
"created": 0, "choices": [{"index": 0, "finish_reason": "stop",
|
|
"message": {"role": "assistant", "content": "pong"}}],
|
|
"usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}}).encode()
|
|
self.send_response(200)
|
|
self.send_header("Content-Type", "application/json")
|
|
self.send_header("Content-Length", str(len(body)))
|
|
self.end_headers(); self.wfile.write(body)
|
|
|
|
|
|
def serve(handler, port):
|
|
srv = ThreadingHTTPServer(("127.0.0.1", port), handler)
|
|
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
|
return srv
|
|
|
|
|
|
INNER, OUTER = 18231, 18232
|
|
serve(Inner, INNER)
|
|
stats = mlx.Stats()
|
|
serve(mlx.make_handler(INNER, SERVED, 262144, KEY, stats, aliases=(REPO,)), OUTER)
|
|
|
|
|
|
def post(model, key=KEY, path="/v1/chat/completions"):
|
|
body = {"messages": [{"role": "user", "content": "hi"}], "max_tokens": 4}
|
|
if model is not None:
|
|
body["model"] = model
|
|
req = urllib.request.Request(f"http://127.0.0.1:{OUTER}{path}", data=json.dumps(body).encode(),
|
|
headers={"Content-Type": "application/json",
|
|
"Authorization": f"Bearer {key}"}, method="POST")
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=20) as r:
|
|
return r.status, json.loads(r.read() or b"{}")
|
|
except urllib.error.HTTPError as e:
|
|
try: return e.code, json.loads(e.read() or b"{}")
|
|
except ValueError: return e.code, {}
|
|
|
|
|
|
print("\n1. the loaded model is accepted")
|
|
seen.clear()
|
|
code, body = post(SERVED)
|
|
check("200", code == 200, code)
|
|
check("answered", body.get("choices", [{}])[0].get("message", {}).get("content") == "pong", body)
|
|
check("forwarded as default_model (mlx_lm must not try to load by name)",
|
|
seen and seen[-1].get("model") == "default_model", seen[-1] if seen else None)
|
|
|
|
print("\n2. the repo id is accepted as an alias")
|
|
check("200", post(REPO)[0] == 200)
|
|
print("\n3. case differences are accepted")
|
|
check("200", post(SERVED.upper())[0] == 200)
|
|
print("\n4. no model named -> the loaded one")
|
|
check("200 when absent", post(None)[0] == 200)
|
|
check("200 when empty", post("")[0] == 200)
|
|
check("200 when blank", post(" ")[0] == 200)
|
|
|
|
print("\n5. a model that ISN'T loaded is refused, not silently answered")
|
|
code, body = post("qwen3.8-27b")
|
|
check("404", code == 404, code)
|
|
err = body.get("error") or {}
|
|
check("code=model_not_found", err.get("code") == "model_not_found", err)
|
|
check("param=model", err.get("param") == "model", err)
|
|
check("names the model asked for", "qwen3.8-27b" in err.get("message", ""), err)
|
|
check("names the loaded model", SERVED in err.get("message", ""), err)
|
|
check("says how to load it", "llmhost switch" in err.get("message", ""), err)
|
|
seen.clear()
|
|
post("qwen3.8-27b")
|
|
check("never reached the model server", seen == [], seen)
|
|
|
|
print("\n6. unknown junk is refused too")
|
|
check("404", post("../etc/passwd")[0] == 404)
|
|
check("404", post("gpt-4")[0] == 404)
|
|
|
|
print("\n7. auth still comes first")
|
|
code, body = post("qwen3.8-27b", key="sk-wrong")
|
|
check("401, not 404 (key checked before the model)", code == 401, code)
|
|
|
|
print("\n8. /v1/models still advertises the served name")
|
|
req = urllib.request.Request(f"http://127.0.0.1:{OUTER}/v1/models",
|
|
headers={"Authorization": f"Bearer {KEY}"})
|
|
with urllib.request.urlopen(req, timeout=10) as r:
|
|
d = json.loads(r.read())
|
|
check("advertises the loaded model", [m["id"] for m in d["data"]] == [SERVED], d)
|
|
|
|
check.done(ROOT)
|