okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221rc1 merge tui-update (3165c2e8a)a1cc285fa

main
7.1 KiB152 linesraw
1"""Fixes from the owner's TUI stress test of the 0.2.3 RC (status/logs discovery, key reuse, retune, folder, quit keys, --model-path)."""
2
3import io
4import json
5import os
6import unittest
7from contextlib import redirect_stdout
8from unittest import mock
9
10from strata_cli.cli import main
11
12
13class StatusLogsDiscoveryTests(unittest.TestCase):
14    """#7 (F02): status and logs find the running launch without --url."""
15
16    def _run(self, *argv):
17        info = {"running": True, "url": "http://127.0.0.1:8080", "key": "k-launch"}
18        env = {k: v for k, v in os.environ.items() if k not in ("STRATA_URL", "STRATA_CONNECTION")}
19        out = io.StringIO()
20        with mock.patch.dict(os.environ, env, clear=True), \
21             mock.patch("strata_cli.launch.cmd.launch_info", return_value=info), \
22             mock.patch("strata_cli.monitor_commands.Endpoint") as endpoint, redirect_stdout(out):
23            endpoint.return_value.snapshot.return_value = {"schema_version": 1}
24            code = main(list(argv))
25        return code, endpoint
26
27    def test_status_uses_the_running_launch(self):
28        code, endpoint = self._run("status", "--json")
29        self.assertEqual(code, 0)
30        self.assertEqual(endpoint.call_args[0][0], "http://127.0.0.1:8080")
31        self.assertEqual(endpoint.call_args[0][1], "k-launch")
32
33    def test_logs_use_the_running_launch(self):
34        with mock.patch("strata_cli.logs.run", return_value=0) as run:
35            code, endpoint = self._run("logs")
36        self.assertEqual(code, 0)
37        self.assertEqual(endpoint.call_args[0][0], "http://127.0.0.1:8080")
38
39    def test_explicit_url_wins(self):
40        code, endpoint = self._run("status", "--json", "--url", "http://127.0.0.1:9999")
41        self.assertEqual(endpoint.call_args[0][0], "http://127.0.0.1:9999")
42
43
44class KeptKeyTests(unittest.TestCase):
45    """#8 (E05/G01): a key made for a launch survives a restart."""
46
47    def setUp(self):
48        import tempfile
49        self.temp = tempfile.TemporaryDirectory()
50        self.addCleanup(self.temp.cleanup)
51        self.cfg = os.path.join(self.temp.name, "launch.json")
52
53    def _write(self, key):
54        with open(self.cfg, "w", encoding="utf-8") as f:
55            json.dump({"api_key": key}, f)
56
57    def test_key_of_the_launch_config_is_kept(self):
58        from strata_cli.launch import access
59        self._write("sk-strata-AAA")
60        with mock.patch("strata_control.profiles.load", return_value=({"source_config": self.cfg}, "r")):
61            self.assertEqual(access.kept_key("gyro-s 32K"), "sk-strata-AAA")
62
63    def test_no_key_and_none_are_not_kept(self):
64        from strata_cli.launch import access
65        self._write("none")
66        with mock.patch("strata_control.profiles.load", return_value=({"source_config": self.cfg}, "r")),              mock.patch("strata_control.profiles.list_profiles", return_value=[]):
67            self.assertIsNone(access.kept_key("gyro-s 32K"))
68
69    def test_newest_launch_config_is_the_fallback(self):
70        from strata_cli.launch import access
71        self._write("sk-strata-BBB")
72        rows = [{"id": "launch-other", "source_config": self.cfg}, {"id": "other", "source_config": "x"}]
73        with mock.patch("strata_control.profiles.load", side_effect=Exception("none")),              mock.patch("strata_cli.launch.store.load", return_value=None),              mock.patch("strata_control.profiles.list_profiles", return_value=rows):
74            self.assertEqual(access.kept_key("gyro-s 64K"), "sk-strata-BBB")
75
76    def test_apply_defaults_reuses_the_key_and_new_key_is_a_different_step(self):
77        from strata_cli.launch import cmd, settings as S
78        from tests.terminal.launch_support import HW_12, Home, catalog
79        s = S.LaunchSettings(family="qwen", model="IQ3_XXS")
80        s.access = "lan"
81        with Home(), mock.patch("strata_cli.launch.access.kept_key", return_value="sk-strata-KEPT"):
82            s2, notes = cmd.apply_defaults(s, catalog(HW_12))
83        self.assertEqual(s2.api_key, "sk-strata-KEPT")
84        self.assertFalse(any("A new API key was made" in n.line() for n in notes))
85
86
87from tests.terminal import test_updater, update_fixture as fx   # noqa: E402  (shared update fixtures)
88from strata_control import updater                                  # noqa: E402
89
90
91class OwnLaunchHoldsTheCardTests(test_updater.UpdaterCase):
92    """#10 (H04/H06): the engine update says one next step when Strata's own launch holds the card."""
93
94    def test_test_start_failure_with_own_launch_serving_gives_the_next_step(self):
95        self.install_current()
96        self.publish(("0.1.47", fx.GOOD_ENGINE))
97        flag = {"held": False}
98
99        def runner(stage_root, staged, ctx):
100            flag["held"] = True
101            raise updater.TestStartFailed(staged.version, "CUDA error: out of memory (raw engine text)")
102
103        serving = lambda: [{"profile": "launch-gyro-s-32k", "state": "ready"}] if flag["held"] else []
104        out = updater.run_update(self.ctx(test_start=runner, serving=serving), control=False)
105        result = out["results"][0]
106        self.assertEqual((out["exit_code"], result["status"]), (7, "failed"))
107        self.assertIn("strata launch --stop", result["error"])
108        self.assertIn("run `strata update` again", result["error"])
109        self.assertNotIn("raw engine text", result["error"])
110
111    def test_own_launch_serving_before_the_test_is_also_one_plain_step(self):
112        self.install_current()
113        self.publish(("0.1.47", fx.GOOD_ENGINE))
114        with self.assertRaises(updater.Busy) as caught:            # refused up front, before anything is downloaded
115            updater.run_update(self.ctx(serving=lambda: [{"profile": "launch-gyro-s-32k", "state": "ready"}]), control=False)
116        self.assertEqual(caught.exception.exit_code, 7)
117        self.assertIn("Stop the model first (`strata launch --stop`)", str(caught.exception))
118
119
120class RetuneStopsOwnServerTests(unittest.TestCase):
121    """#10 (E07): measuring while the same launch serves stops it first, and says so."""
122
123    def _runner(self, state):
124        from strata_cli.launch import settings as S
125        from strata_cli.launch.runner import Runner
126        class Bare(Runner):
127            profile = "launch-x"
128        r = Bare.__new__(Bare)
129        r.s = S.LaunchSettings(name="x")
130        r.restart_after = True
131        r._stop_first = []
132        r.said = []
133        r.emit = lambda *a, **k: r.said.append(a[1])
134        return r
135
136    def test_serving_profile_is_stopped_and_the_line_is_plain(self):
137        r = self._runner(None)
138        with mock.patch("strata_control.runtime.status", return_value={"state": "ready"}),              mock.patch("strata_control.runtime.stop") as stop:
139            r.stop_own_server_for_tuning()
140        stop.assert_called_once()
141        self.assertEqual(r.said, ["Stopping the model to measure; it starts again afterwards."])
142
143    def test_nothing_is_stopped_when_nothing_serves(self):
144        r = self._runner(None)
145        with mock.patch("strata_control.runtime.status", return_value={"state": "stopped"}),              mock.patch("strata_control.runtime.stop") as stop:
146            r.stop_own_server_for_tuning()
147        stop.assert_not_called()
148        self.assertEqual(r.said, [])
149
150
151if __name__ == "__main__":
152    unittest.main()