Prime OpenCode catalog before container login and model validation

This commit is contained in:
2026-10-09 23:34:01 +01:00
parent 08b8647d5b
commit 16389b8270
3 changed files with 157 additions and 18 deletions
+115 -10
View File
@@ -16,6 +16,111 @@ spec.loader.exec_module(setup)
class DockerSetupTests(unittest.TestCase):
def test_validation_primes_its_own_service_and_passes_model_as_argument(self):
with tempfile.TemporaryDirectory() as directory:
root=Path(directory);(root/".env").write_text("CUSTOM=keep\n")
opencode=root/"opencode"
opencode.write_text('''#!/bin/sh
if [ "$1" = api ]; then
touch "$FIXTURE/primed"
echo '{"data":[]}'
elif [ "$1" = models ]; then
echo 'opencode-go/deepseek-v4.1-flash'
else
exit 9
fi
''');opencode.chmod(0o700)
pipelines=root/"pipelines"
pipelines.write_text('''#!/bin/sh
test -f "$FIXTURE/primed" || exit 8
test "$1" = provider-check || exit 9
printf '%s' "$3" > "$FIXTURE/model"
echo '{"healthy":true,"session_id":"ses_validation"}'
''');pipelines.chmod(0o700)
def runner(command,**kwargs):
index=command.index("-c")
# Each one-off container has a separate service/catalog.
(root/"primed").unlink(missing_ok=True)
return subprocess.run(["sh",*command[index:]],capture_output=True,text=True,
env=dict(os.environ,PATH=str(root)+os.pathsep+os.environ["PATH"],FIXTURE=str(root)))
installer=setup.Setup(directory,runner=runner)
installer.validate_provider(setup.arguments(["--model","opencode-go/deepseek-v4.1-flash"]))
self.assertEqual((root/"model").read_text(),"opencode-go/deepseek-v4.1-flash")
self.assertIn("CUSTOM=keep\n",(root/".env").read_text())
def test_native_login_ui_uses_same_primed_container(self):
with tempfile.TemporaryDirectory() as directory:
root=Path(directory)
executable=root/"opencode"
executable.write_text('''#!/bin/sh
if [ "$1" = api ]; then
touch "$FIXTURE/primed"
echo '{"data":[]}'
elif [ "$1 $2" = 'auth login' ]; then
test -f "$FIXTURE/primed" || exit 8
touch "$FIXTURE/logged"
else
exit 9
fi
''')
executable.chmod(0o700)
logins=[]
def runner(command,**kwargs):
if command[-4:]==["auth","list","--format","json"]:
accounts='[{"id":"opencode-go","connections":[{"id":"fixture"}]}]' if (root/"logged").exists() else '[]'
return subprocess.CompletedProcess(command,0,stdout=accounts,stderr="")
logins.append(command)
self.assertNotIn("-T",command,"interactive login lost its terminal")
return subprocess.run(["sh","-c",command[-1]],
env=dict(os.environ,PATH=str(root)+os.pathsep+os.environ["PATH"],FIXTURE=str(root)))
setup.Setup(directory,runner=runner).authenticate()
self.assertEqual(len(logins),1)
self.assertTrue((root/"logged").exists())
def test_model_discovery_primes_catalog_and_retries_in_one_container(self):
with tempfile.TemporaryDirectory() as directory:
root=Path(directory)
executable=root/"opencode"
executable.write_text('''#!/bin/sh
if [ "$1" = api ]; then
touch "$FIXTURE/primed"
echo '{"data":[]}'
elif [ "$1" = models ]; then
test -f "$FIXTURE/primed" || exit 8
if [ ! -f "$FIXTURE/first-read" ]; then
touch "$FIXTURE/first-read"
else
echo 'opencode-go/deepseek-v4.1-flash'
fi
else
exit 9
fi
''')
executable.chmod(0o700)
calls=[]
def runner(command,**kwargs):
calls.append(command)
self.assertIn("sh",command)
return subprocess.run(["sh","-c",command[-1]],capture_output=True,text=True,
env=dict(os.environ,PATH=str(root)+os.pathsep+os.environ["PATH"],FIXTURE=str(root)))
models=setup.Setup(directory,runner=runner).discover_models()
self.assertEqual(models,["opencode-go/deepseek-v4.1-flash"])
self.assertEqual(len(calls),1,"retry started a fresh container/service")
def test_empty_catalog_does_not_blame_or_replace_saved_key(self):
with tempfile.TemporaryDirectory() as directory:
path=Path(directory,".env");path.write_text("CUSTOM=keep\n")
def runner(command,**kwargs):
return subprocess.CompletedProcess(command,0,stdout="",stderr="")
installer=setup.Setup(directory,runner=runner)
installer.accounts=[{"id":"opencode-go","connections":[{"id":"saved-account"}]}]
with self.assertRaises(ValueError) as raised:
installer.validate_provider(setup.arguments([]))
self.assertIn("NOT proof it is invalid",str(raised.exception))
self.assertIn("opencode-go",str(raised.exception))
self.assertNotIn("--relogin",str(raised.exception))
self.assertEqual(path.read_text(),"CUSTOM=keep\n")
def test_provider_validation_failure_preserves_saved_model(self):
for report in ['{"healthy":false,"diagnostic":"quota exhausted","session_id":"ses_failed"}',
'{"healthy":true}', '[]', 'not-json']:
@@ -26,13 +131,13 @@ class DockerSetupTests(unittest.TestCase):
calls=[]
def runner(command,**kwargs):
calls.append(command)
out="fixture/new\n" if command[-1:]==["models"] else report
out="fixture/new\n" if "opencode models" in command[-1] else report
return subprocess.CompletedProcess(command,0,stdout=out,stderr="")
installer=setup.Setup(directory,runner=runner)
with patch("sys.stderr"),self.assertRaises(ValueError):
installer.validate_provider(setup.arguments(["--model","fixture/new"]))
self.assertEqual(before,path.read_bytes())
self.assertTrue(any("provider-check" in command for command in calls))
self.assertTrue(any(any("provider-check" in arg for arg in command) for command in calls))
def test_unavailable_model_does_not_attempt_generation(self):
with tempfile.TemporaryDirectory() as directory:
@@ -43,7 +148,7 @@ class DockerSetupTests(unittest.TestCase):
return subprocess.CompletedProcess(command,0,stdout="fixture/available\n",stderr="")
with self.assertRaises(ValueError):
setup.Setup(directory,runner=runner).validate_provider(setup.arguments(["--model","fixture/unavailable"]))
self.assertFalse(any("provider-check" in command for command in calls))
self.assertFalse(any(any("provider-check" in arg for arg in command) for command in calls))
def test_ctrl_c_exits_cleanly_and_retains_configuration(self):
with tempfile.TemporaryDirectory() as directory:
@@ -112,11 +217,11 @@ class DockerSetupTests(unittest.TestCase):
code, out = 0, ""
if args[-4:] == ["auth", "list", "--format", "json"]:
out = '[{"id":"fixture","connections":[{"id":"fixture"}]}]' if logged else '[]'
if args[-1:] == ["models"]:
if "opencode models" in args[-1]:
out = "fixture/test-model\n"
if "provider-check" in args:
if any("provider-check" in arg for arg in args):
out = '{"healthy":true,"session_id":"ses_fixture"}'
if args[-2:] == ["auth", "login"] and confirm == "yes":
if "exec opencode auth login" in args[-1] and confirm == "yes":
logged = True
if "token" in args:
out = f"token {token} created\n"
@@ -124,7 +229,7 @@ class DockerSetupTests(unittest.TestCase):
out = '{"ntfy":{"health":"healthy","url":"http://192.168.1.20:8090"},"topic":"pipelines"}'
if args[:1] == ["port"]:
out = "127.0.0.1:8081\n"
if fail and fail in args:
if fail and (fail in args or (fail=="login" and "exec opencode auth login" in args[-1]) or (fail=="provider-check" and any("provider-check" in arg for arg in args))):
code, out = 9, "private provider data/token"
return subprocess.CompletedProcess(command, code, stdout=out, stderr="")
@@ -138,12 +243,12 @@ class DockerSetupTests(unittest.TestCase):
def test_fresh_setup_wires_notifications_and_runs_container_login(self):
with tempfile.TemporaryDirectory() as directory:
calls, token = self.exercise(directory)
self.assertIn(["run", "--rm", "--no-deps", "--entrypoint", "opencode", "pipelines", "auth", "login"], calls)
self.assertTrue(any("exec opencode auth login" in c[-1] for c in calls))
self.assertTrue(any("--force-recreate" in c for c in calls))
self.assertEqual(Path(directory, "secrets/ntfy-token.txt").read_text(), token + "\n")
self.assertFalse(any(token in " ".join(c) for c in calls))
self.assertLess(next(i for i,c in enumerate(calls) if "token" in c), next(i for i,c in enumerate(calls) if "build" in c))
self.assertLess(next(i for i,c in enumerate(calls) if "login" in c), next(i for i,c in enumerate(calls) if "--force-recreate" in c))
self.assertLess(next(i for i,c in enumerate(calls) if "exec opencode auth login" in c[-1]), next(i for i,c in enumerate(calls) if "--force-recreate" in c))
self.assertTrue(any("curl --config -" in " ".join(c) for c in calls))
def test_reinstall_preserves_configuration_tokens_and_provider_setup(self):
@@ -152,7 +257,7 @@ class DockerSetupTests(unittest.TestCase):
files = [Path(directory, ".env"), Path(directory, "secrets/ntfy-token.txt")]
before = [p.read_bytes() for p in files]
calls, _ = self.exercise(directory, existing=True)
self.assertFalse(any("login" in c or "token" in c for c in calls))
self.assertFalse(any("exec opencode auth login" in c[-1] or "token" in c for c in calls))
self.assertEqual(before[1],files[1].read_bytes())
self.assertEqual(files[0].read_bytes(),before[0].replace(b"NTFY_BIND_ADDRESS=192.168.1.20",b"NTFY_BIND_ADDRESS=0.0.0.0")+b"PIPELINES_BIND_ADDRESS=0.0.0.0\n")
normalized=files[0].read_bytes()