okami.mom/strata

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

Niko1221Merge f-0250-tui into f-0243-rel0c53372a0

main
7.7 KiB157 linesraw
1"""Tests for `setup.py --update` (#475, UPDATE.bat / update.sh): it refreshes what a start would - the Python packages,
2the engine, each model's config and draft subset - and never starts the model.  Every outside effect is mocked: no
3GPU, no downloads, nothing written outside a temp folder.
4
5    python -m unittest tools.test_setup_update
6"""
7from __future__ import annotations
8
9import contextlib
10import io
11import json
12import sys
13import tempfile
14import unittest
15from pathlib import Path
16from unittest import mock
17
18ROOT = Path(__file__).resolve().parents[1]
19sys.path.insert(0, str(ROOT))
20import setup  # noqa: E402
21
22
23class Update(unittest.TestCase):
24    def config(self, d: Path, **extra) -> Path:
25        rt = d / "mtp" / "rt"
26        rt.mkdir(parents=True)
27        p = d / "strata-iq3_s.json"
28        p.write_text(json.dumps({"model_name": "Qwen IQ3_S", "exe": str(d / "engine" / setup.EXE),
29                                 "args": ["--native", "x", "--mtp", str(rt)], **extra}), encoding="utf-8")
30        return p
31
32    def run_update(self, have, argv=()):
33        a = mock.Mock(**{"build": False, "prebuilt": "URL", **dict(argv)})
34        out = io.StringIO()
35        with mock.patch.object(setup, "pip_install") as pip, \
36                mock.patch.object(setup, "update_installed_engine") as eng, \
37                mock.patch.object(setup, "refresh_draft_vocab") as dv, \
38                mock.patch.object(setup, "start") as start, \
39                mock.patch("subprocess.call") as call, \
40                contextlib.redirect_stdout(out):
41            rc = setup.update_install(have, a)
42        return rc, pip, eng, dv, start, call, out.getvalue()
43
44    def test_refreshes_without_starting(self):
45        with tempfile.TemporaryDirectory() as d:
46            p = self.config(Path(d), draft_vocab="en")
47            rc, pip, eng, dv, start, call, out = self.run_update([p])
48        self.assertEqual(rc, 0)
49        pip.assert_called_once()
50        eng.assert_called_once_with("URL")
51        dv.assert_called_once()
52        self.assertEqual(dv.call_args[0][1], "en")                 # the model's own subset is kept
53        start.assert_not_called()
54        call.assert_not_called()
55        self.assertIn("Strata is updated", out)
56
57    def test_an_engine_that_stayed_old_is_not_called_updated(self):                  # #3653
58        with tempfile.TemporaryDirectory() as d:
59            p = self.config(Path(d))
60            with mock.patch.object(setup, "engine_version", return_value=(0, 1, 44, 1)):
61                rc, pip, eng, dv, start, call, out = self.run_update([p])
62            self.assertIn("the engine was NOT", out)
63            self.assertIn("Next step:", out)
64            self.assertNotIn("[ok] Strata is updated", out)
65            with mock.patch.object(setup, "engine_version", return_value=(0, 1, 49, 2)):
66                rc, pip, eng, dv, start, call, out = self.run_update([p])
67            self.assertIn("Strata is updated (engine 0.1.49.2)", out)
68
69    def test_build_keeps_the_compiled_engine_path(self):
70        with tempfile.TemporaryDirectory() as d:
71            p = self.config(Path(d))
72            rc, pip, eng, dv, *_ = self.run_update([p], {"build": True})
73        self.assertEqual(rc, 0)
74        eng.assert_not_called()
75        self.assertEqual(dv.call_args[0][1], "cjk")
76
77    def test_nothing_installed(self):
78        rc, pip, eng, dv, start, call, out = self.run_update([])
79        self.assertEqual(rc, 0)
80        for m in (pip, eng, dv, start, call):
81            m.assert_not_called()
82        self.assertIn("START-HERE.bat", out)
83
84    def test_a_json_that_is_no_model_config_is_skipped(self):
85        """#549: a strata-*.json without "args" (not written by setup) stopped update.sh with KeyError: 'args'."""
86        with tempfile.TemporaryDirectory() as d:
87            p = self.config(Path(d))
88            other = Path(d) / "strata-notes.json"
89            other.write_text(json.dumps({"note": "mine"}), encoding="utf-8")
90            broken = Path(d) / "strata-cut.json"
91            broken.write_text("{\"args\": [", encoding="utf-8")
92            rc, pip, eng, dv, start, call, out = self.run_update([other, broken, p])
93        self.assertEqual(rc, 0, out)
94        self.assertIn('skipped strata-notes.json (no "exe" or "args"): it is not a Strata model config', out)
95        self.assertIn("skipped strata-cut.json (not valid JSON)", out)
96        dv.assert_called_once()                                     # the real model is still refreshed
97        self.assertIn("Qwen IQ3_S: up to date", out)
98        self.assertIn("Strata is updated", out)
99
100    def test_installed_configs_lists_only_model_configs(self):
101        with tempfile.TemporaryDirectory() as d:
102            p = self.config(Path(d))
103            (Path(d) / "strata-notes.json").write_text("{}", encoding="utf-8")
104            with mock.patch.object(setup, "ROOT", Path(d)), contextlib.redirect_stdout(io.StringIO()):
105                self.assertEqual(setup.installed_configs(), [p])
106
107    def test_main_update_never_starts(self):
108        with tempfile.TemporaryDirectory() as d:
109            p = self.config(Path(d))
110            with mock.patch.object(sys, "argv", ["setup.py", "--update"]), \
111                    mock.patch.object(setup, "data_folder", return_value=(Path(d), [])), \
112                    mock.patch.object(setup, "installed_configs", return_value=[p]), \
113                    mock.patch.object(setup, "update_install", return_value=0) as up, \
114                    mock.patch.object(setup, "start") as start, \
115                    contextlib.redirect_stdout(io.StringIO()):
116                self.assertEqual(setup.main(), 0)
117        up.assert_called_once()
118        start.assert_not_called()
119
120
121class SettingsLine(unittest.TestCase):
122    """#564: a start prints the settings it uses (the engine options without the model's paths, and the server's
123    fields), so a change made by hand to strata-<model>.json shows without reading the log."""
124
125    CFG = {"exe": "x", "host": "0.0.0.0", "port": 8081, "api_key": "secret", "gpu": [0, 1], "fit_max_tokens": True,
126           "args": ["--native", "E:\\Strata\\packs\\iq3_s", "--mtp", "/s/mtp/rt", "m.gguf", "--kv", "int8",
127                    "--kv-resident", "32768", "--spec-min-p", "0.5", "--vram-reserve-mib", "2048", "--mmap-experts",
128                    "--prefill", "auto"]}
129
130    def test_summary(self):
131        s = setup.settings_summary(self.CFG)
132        self.assertEqual(s, "--kv int8 --kv-resident 32768 --spec-min-p 0.5 --vram-reserve-mib 2048 --mmap-experts "
133                            "--prefill auto; server 0.0.0.0:8081, api key set, gpu 0,1, fit_max_tokens true")
134        self.assertNotIn("secret", s)
135        self.assertIn("127.0.0.1:9000", setup.settings_summary({"args": []}, 9000))
136
137    def test_a_start_prints_it(self):
138        with tempfile.TemporaryDirectory() as d:
139            exe = Path(d) / "strata.exe"
140            exe.write_bytes(b"")
141            p = Path(d) / "strata-iq3_s.json"
142            args = [x for x in self.CFG["args"] if x != "m.gguf"]           # no model file here
143            p.write_text(json.dumps({**self.CFG, "exe": str(exe), "gpu": 0, "args": args}), encoding="utf-8")
144            out = io.StringIO()
145            with mock.patch.object(setup, "gpus", lambda: []), \
146                    mock.patch.object(setup, "refresh_draft_vocab"), \
147                    mock.patch.object(setup, "is_wsl", lambda: False), \
148                    mock.patch.object(setup.subprocess, "call", return_value=0), \
149                    contextlib.redirect_stdout(out):
150                setup.start(p, None, open_browser=False, yes=True)
151        text = " ".join(out.getvalue().split())
152        self.assertIn("Settings (strata-iq3_s.json): --kv int8 --kv-resident 32768", text)
153        self.assertIn("--vram-reserve-mib 2048", text)
154
155
156if __name__ == "__main__":
157    unittest.main()