Add tests/: four suites, a runner, and a sandbox that can't escape

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>
This commit is contained in:
Neil Bantoc 2026-11-03 02:23:15 -08:00
parent ba7bd76af6
commit 51c2880a2e
8 changed files with 852 additions and 0 deletions

271
tests/test_opencode.py Normal file
View file

@ -0,0 +1,271 @@
"""opencode integration: provider naming, ownership, removal, the credential cache."""
import json, os, shutil, pathlib
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
import harness
ROOT = harness.setup()
from llmhost import opencode, paths
harness.guard(paths, ROOT)
CFG = harness.config()
OC = opencode.config_file()
check = harness.Checks()
def reset(data=None):
shutil.rmtree(OC.parent, ignore_errors=True)
if data is not None:
OC.parent.mkdir(parents=True, exist_ok=True)
OC.write_text(json.dumps(data, indent=2))
def load():
return json.loads(OC.read_text())
def remote(host, prov=None):
prov = prov or opencode.remote_provider(host)
return prov, opencode.provider_block(CFG, host, opencode.remote_key_file(prov), host)
print("\n1. fresh install")
reset()
st, path, prov, authcl = opencode.configure(CFG)
d = load()
check("status added", st == "added", st)
check("id is llmhost", prov == "llmhost", prov)
check('name is "LLMHost (Local)"', d["provider"]["llmhost"]["name"] == "LLMHost (Local)", d["provider"]["llmhost"]["name"])
check("baseURL localhost", d["provider"]["llmhost"]["options"]["baseURL"] == "http://localhost:1134/v1")
check("apiKey -> llm-host key file", str(paths.KEY_FILE) in d["provider"]["llmhost"]["options"]["apiKey"])
check("model set", d["model"] == "llmhost/ornith-1.5-9b", d.get("model"))
mods = d["provider"]["llmhost"]["models"]
check("model keyed by slug", "qwen3.8-27b" in mods, list(mods))
check("label = title + slug", mods["qwen3.8-27b"]["name"] == "Qwen3.8 27B \u00b7 qwen3.8-27b (Local)", mods["qwen3.8-27b"]["name"])
check("active model marked loaded", mods[CFG["active"]]["name"].endswith("(Local, loaded)"), mods[CFG["active"]]["name"])
check("only the active one is marked",
sum(v["name"].endswith(", loaded)") for v in mods.values()) == 1,
[v["name"] for v in mods.values()])
check("slug searchable for every model", all(k in v["name"] for k, v in mods.items()))
print("\n2. local + remote side by side")
rp, rb = remote("popos.local")
reset({"provider": {rp: rb}, "model": f"{rp}/qwen3.8-27b"})
st, path, prov, authcl = opencode.configure(CFG)
d = load()
check("remote id is llmhost-popos", rp == "llmhost-popos", rp)
check('remote name is "LLMHost (popos.local)"', rb["name"] == "LLMHost (popos.local)", rb["name"])
check("remote model label", rb["models"]["qwen3.8-27b"]["name"] == "Qwen3.8 27B \u00b7 qwen3.8-27b (popos.local)", rb["models"]["qwen3.8-27b"]["name"])
check("remote block is NOT marked loaded", not any(", loaded)" in v["name"] for v in rb["models"].values()),
[v["name"] for v in rb["models"].values()])
check("local added alongside", sorted(d["provider"]) == ["llmhost", "llmhost-popos"], sorted(d["provider"]))
check("remote untouched", d["provider"][rp] == rb)
check("existing model kept", d["model"] == f"{rp}/qwen3.8-27b", d["model"])
print("\n3. a REMOTE block squatting on the `llmhost` id (gap 1)")
_, rb2 = remote("popos.local", prov="llmhost")
reset({"provider": {"llmhost": rb2}})
st, path, prov, authcl = opencode.configure(CFG)
d = load()
check("did not reuse `llmhost`", prov == "llmhost-local", prov)
check("remote block intact", d["provider"]["llmhost"] == rb2)
check("local under llmhost-local", d["provider"]["llmhost-local"]["options"]["baseURL"] == "http://localhost:1134/v1")
print("\n4. user renamed the local provider (gap 2)")
reset({"provider": {"mymac": opencode.local_block(CFG)}, "model": "mymac/ornith-1.5-9b"})
st, path, prov, authcl = opencode.configure(CFG)
d = load()
check("recognised under new name", prov == "mymac", prov)
check("no duplicate added", list(d["provider"]) == ["mymac"], list(d["provider"]))
check("status unchanged", st == "unchanged", st)
print("\n5. uninstall: remove local, keep remote, repoint model")
rp, rb = remote("popos.local")
reset({"provider": {"llmhost": opencode.local_block(CFG), rp: rb}, "model": "llmhost/ornith-1.5-9b"})
st, path, removed, new_model = opencode.remove(local=True)
d = load()
check("status removed", st == "removed", st)
check("removed only local", removed == ["llmhost"], removed)
check("remote survives", list(d["provider"]) == [rp], list(d["provider"]))
first = CFG["models"][0]["name"]
check("model repointed to remote's first (plan-order) model",
new_model == f"{rp}/{first}" and d["model"] == new_model, (new_model, d.get("model")))
print("\n6. uninstall must NOT glob llmhost*")
reset({"provider": {rp: rb}, "model": f"{rp}/qwen3.8-27b"})
st, path, removed, new_model = opencode.remove(local=True)
check("nothing matched", st == "none" and removed == [], (st, removed))
check("remote still there", list(load()["provider"]) == [rp])
print("\n7. retiring a remote server (gap 3)")
reset({"provider": {"llmhost": opencode.local_block(CFG), rp: rb}, "model": f"{rp}/qwen3.8-27b"})
st, path, removed, new_model = opencode.remove(local=False, host="popos.local")
d = load()
check("removed the remote", removed == [rp], removed)
check("local survives", list(d["provider"]) == ["llmhost"], list(d["provider"]))
check("model repointed to local", d["model"].startswith("llmhost/"), d.get("model"))
reset({"provider": {"llmhost": opencode.local_block(CFG), rp: rb}})
st, path, removed, _ = opencode.remove(local=False, host="popos")
check("short hostname also matches", removed == [rp], removed)
print("\n8. --all drops the model key when nothing is left")
reset({"provider": {"llmhost": opencode.local_block(CFG), rp: rb}, "model": "llmhost/ornith-1.5-9b"})
st, path, removed, new_model = opencode.remove(local=False, every=True)
d = load()
check("both removed", sorted(removed) == ["llmhost", rp], removed)
check("model key dropped", "model" not in d and new_model is None, d)
check("provider key dropped", "provider" not in d, d)
print("\n9. foreign providers are never touched")
foreign = {"npm": "@ai-sdk/openai-compatible", "name": "vLLM (popos)",
"options": {"baseURL": "http://popos.local:1134/v1", "apiKey": "{file:~/.config/opencode/popos-vllm.key}"},
"models": {"x": {"name": "x"}}}
reset({"provider": {"popos-vllm": foreign, "llmhost": opencode.local_block(CFG)}, "model": "popos-vllm/x"})
st, path, removed, new_model = opencode.remove(local=True)
d = load()
check("only ours removed", removed == ["llmhost"], removed)
check("foreign intact", d["provider"]["popos-vllm"] == foreign)
check("foreign model untouched", d["model"] == "popos-vllm/x", d.get("model"))
st, path, removed, _ = opencode.remove(local=False, every=True)
check("--all skips foreign", removed == [], removed)
print("\n10. .jsonc with comments is left alone")
shutil.rmtree(OC.parent, ignore_errors=True)
OC.parent.mkdir(parents=True, exist_ok=True)
j = OC.parent / "opencode.jsonc"
orig = '{\n // mine\n "provider": {}\n}\n'
j.write_text(orig)
st, path, prov, authcl = opencode.configure(CFG)
check("configure reports has-comments", st == "has-comments", st)
check("file unchanged", j.read_text() == orig)
st, path, removed, _ = opencode.remove(local=True)
check("remove reports has-comments", st == "has-comments", st)
check("file still unchanged", j.read_text() == orig)
check("snippet has the new name", '"LLMHost (Local)"' in opencode.snippet(CFG))
print("\n11. unparsable JSON is left alone")
reset(); OC.parent.mkdir(parents=True, exist_ok=True); OC.write_text("{ broken")
st, path, prov, authcl = opencode.configure(CFG)
check("configure reports unparsable", st == "unparsable", st)
check("file unchanged", OC.read_text() == "{ broken")
print("\n12. missing/garbage blocks don't crash the fingerprint")
reset({"provider": {"a": None, "b": "nope", "c": {}, "d": {"options": {}}}})
check("no crash, nothing ours", opencode.local_ids(load()["provider"]) == [])
st, path, prov, authcl = opencode.configure(CFG)
check("still installs", prov == "llmhost" and st == "added", (prov, st))
print("\n13. --host must not take a foreign provider on the same host (regression)")
rp, rb = remote("popos.local")
reset({"provider": {rp: rb, "popos-vllm": foreign, "llmhost": opencode.local_block(CFG)},
"model": "popos-vllm/x"})
st, path, removed, new_model = opencode.remove(local=False, host="popos.local")
d = load()
check("removed only ours", removed == [rp], removed)
check("foreign on same host survives", "popos-vllm" in d["provider"])
check("local survives", "llmhost" in d["provider"])
check("foreign model untouched", d["model"] == "popos-vllm/x", d.get("model"))
print("\n14. a stale cached key is cleared on configure")
def put_auth(d, mode=0o600):
f = opencode.auth_file(); f.parent.mkdir(parents=True, exist_ok=True)
fd = os.open(f, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, mode)
with os.fdopen(fd, "w") as fh: json.dump(d, fh)
return f
def get_auth():
return json.loads(opencode.auth_file().read_text())
reset()
af = put_auth({"llmhost": {"type": "api", "key": "sk-STALE"}, "anthropic": {"type": "oauth", "t": 1}})
st, path, prov, authcl = opencode.configure(CFG)
a = get_auth()
check("reported clearing the cache", authcl is True, authcl)
check("stale llmhost entry gone", "llmhost" not in a, a)
check("other providers' creds untouched", a.get("anthropic") == {"type": "oauth", "t": 1}, a)
check("file mode preserved (0600)", oct(af.stat().st_mode & 0o777) == "0o600", oct(af.stat().st_mode & 0o777))
print("\n15. nothing cached -> nothing reported, no file created")
reset(); opencode.auth_file().unlink(missing_ok=True)
st, path, prov, authcl = opencode.configure(CFG)
check("no clear reported", authcl is False, authcl)
check("no auth.json invented", not opencode.auth_file().exists())
reset(); put_auth({"other": {"type": "api", "key": "x"}})
st, path, prov, authcl = opencode.configure(CFG)
check("untouched when we have no entry", authcl is False and get_auth() == {"other": {"type": "api", "key": "x"}})
print("\n16. an unreadable auth store is left alone, not repaired")
reset()
f = opencode.auth_file(); f.parent.mkdir(parents=True, exist_ok=True); f.write_text("{ not json")
st, path, prov, authcl = opencode.configure(CFG)
check("no crash", st == "added", st)
check("left verbatim", f.read_text() == "{ not json")
check("reported nothing cleared", authcl is False, authcl)
print("\n17. remove() takes the cached key with the provider")
reset({"provider": {"llmhost": opencode.local_block(CFG), "llmhost-popos": remote("popos.local")[1]}})
put_auth({"llmhost": {"type": "api", "key": "sk-A"}, "llmhost-popos": {"type": "api", "key": "sk-B"}})
st, path, removed, _ = opencode.remove(local=True)
a = get_auth()
check("local cred cleared", "llmhost" not in a, a)
check("remote cred kept", a.get("llmhost-popos") == {"type": "api", "key": "sk-B"}, a)
print("\n18. purge --keep-key keeps the API key through a purge")
from llmhost import cli
cli_shim = pathlib.Path(ROOT) / "bin/llmhost"
cli_shim.parent.mkdir(parents=True, exist_ok=True)
paths.SHIM = cli_shim # never touch the real launcher from a test
for name in ("DATA", "CONFIG_DIR", "KEY_FILE", "SHIM"):
val = str(getattr(paths, name))
if not val.startswith(ROOT):
sys.exit(f"ABORT: paths.{name} = {val} is outside the sandbox {ROOT}; "
"purge() would delete a real install")
def seed():
paths.CONFIG_DIR.mkdir(parents=True, exist_ok=True)
paths.DATA.mkdir(parents=True, exist_ok=True)
(paths.DATA / "venv-mlx").mkdir(exist_ok=True)
key = paths.api_key(create=True)
paths.save_config({"active": "x"})
cli_shim.write_text("#!/bin/sh\n")
return key
key = seed()
kept = cli.purge(keep_key=True)
check("reported the kept path", kept == paths.KEY_FILE, kept)
check("key file survives", paths.KEY_FILE.exists())
check("key value unchanged", paths.KEY_FILE.read_text().strip() == key.strip(), paths.KEY_FILE.read_text())
check("key mode is 0600", oct(paths.KEY_FILE.stat().st_mode & 0o777) == "0o600", oct(paths.KEY_FILE.stat().st_mode & 0o777))
check("config.json gone", not paths.CONFIG_FILE.exists())
check("data dir gone", not paths.DATA.exists())
check("launcher gone", not cli_shim.exists())
check("a reinstall would reuse it", paths.api_key(create=True).strip() == key.strip())
print("\n19. purge without --keep-key removes everything")
key2 = seed()
kept = cli.purge(keep_key=False)
check("reported nothing kept", kept is None, kept)
check("key file gone", not paths.KEY_FILE.exists())
check("config dir gone", not paths.CONFIG_DIR.exists())
check("a reinstall mints a different key", paths.api_key(create=True).strip() != key2.strip())
print("\n20. sync() refreshes an existing block after a switch")
reset({"provider": {"llmhost": opencode.local_block(CFG)}, "model": "llmhost/" + CFG["active"]})
switched = dict(CFG, active="qwen3-coder")
prov = opencode.sync(switched)
mods = load()["provider"]["llmhost"]["models"]
check("reported the provider", prov == "llmhost", prov)
check("new model marked loaded", mods["qwen3-coder"]["name"].endswith("(Local, loaded)"), mods["qwen3-coder"]["name"])
check("old one unmarked", not mods[CFG["active"]]["name"].endswith(", loaded)"), mods[CFG["active"]]["name"])
check("idempotent", opencode.sync(switched) is None)
print("\n21. sync() never wires opencode up on its own")
reset()
check("no config file -> no-op", opencode.sync(CFG) is None)
check("still no config file", not opencode.config_file().exists())
reset({"provider": {"popos-vllm": foreign}, "model": "popos-vllm/x"})
check("no local block -> no-op", opencode.sync(CFG) is None)
check("foreign provider untouched", load()["provider"] == {"popos-vllm": foreign})
reset({"provider": {"mymac": opencode.local_block(CFG)}})
check("finds a renamed local block", opencode.sync(dict(CFG, active="qwen3-coder")) == "mymac")
check.done(ROOT)