okami.mom/strata

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

Niko1221Merge commit 'b8d604d28' into f-clean-1ab0fc432ed

main
24.2 KiB434 linesraw
1"""Tests for tools/strata_bench.py with a fake engine behind a real HTTP server: the suite runner, the redaction, the report
2writing and the comparison.  Light: no GPU, no Strata server, a few seconds."""
3from __future__ import annotations
4
5import contextlib
6import io
7import json
8import os
9import sys
10import tempfile
11import threading
12import unittest
13from unittest import mock
14from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
15from pathlib import Path, PurePosixPath, PureWindowsPath
16
17sys.path.insert(0, str(Path(__file__).resolve().parent))
18import strata_bench as B  # noqa: E402
19
20
21def text_of(messages) -> str:
22    return "".join(m.get("content") or "" for m in messages)
23
24
25class FakeStrata(ThreadingHTTPServer):
26    """Speaks the parts of the Strata API the benchmark reads.  The conversation cache is the longest common prefix with the
27    previous prompt (4 characters = 1 token)."""
28    daemon_threads = True
29
30    def __init__(self, ctx=32768, fail_after=None):
31        super().__init__(("127.0.0.1", 0), Handler)
32        self.ctx, self.prev, self.requests, self.fail_after = ctx, "", 0, fail_after
33        self.lock = threading.Lock()
34        threading.Thread(target=self.serve_forever, daemon=True).start()
35
36    def stop(self):
37        self.shutdown()
38        self.server_close()
39
40    @property
41    def base(self):
42        return f"http://127.0.0.1:{self.server_address[1]}"
43
44
45class Handler(BaseHTTPRequestHandler):
46    def log_message(self, *a):
47        pass
48
49    def send_json(self, obj, code=200):
50        body = json.dumps(obj).encode()
51        self.send_response(code)
52        self.send_header("Content-Type", "application/json")
53        self.send_header("Content-Length", str(len(body)))
54        self.end_headers()
55        self.wfile.write(body)
56
57    def do_GET(self):
58        s = self.server
59        if self.path == "/health":
60            self.send_json({"status": "ok", "service": "strata", "loaded": True})
61        elif self.path == "/v1/models":
62            self.send_json({"object": "list", "data": [{"id": "fake", "meta": {"n_ctx": s.ctx}}]})
63        elif self.path == "/props":
64            self.send_json({"total_slots": 4, "model_alias": "fake-model", "build_info": "Strata 9.9.9"})
65        elif self.path == "/v1/status":
66            self.send_json({"machine": {"gpu": {"name": "NVIDIA GeForce RTX 9999", "total_mib": 12288}, "ram": {"total_gib": 64.0}},
67                            "engine": "9.9.9", "vram": {"free_mib": 1000}})
68        elif self.path == "/metrics":
69            self.send_json({"engine": {"version": "9.9.9", "max_context": s.ctx, "model_path": r"C:\Users\Someone\models\x.gguf"},
70                            "hardware_static": {"gpu_name": "NVIDIA GeForce RTX 9999", "cpu_name": "Fake CPU 9", "cores": 8, "threads": 16}})
71        else:
72            self.send_json({}, 404)
73
74    def do_POST(self):
75        s = self.server
76        req = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
77        text = text_of(req["messages"])
78        with s.lock:
79            s.requests += 1
80            n = s.requests
81            common = 0
82            for x, y in zip(s.prev, text):
83                if x != y:
84                    break
85                common += 1
86            s.prev = text
87        if s.fail_after is not None and n > s.fail_after:
88            self.send_json({"error": "boom"}, 500)
89            return
90        prompt = max(1, len(text) // 4)
91        cached = min(prompt, common // 4)
92        gen = min(req.get("max_tokens", 16), 12)
93        self.send_response(200)
94        self.send_header("Content-Type", "text/event-stream")
95        self.end_headers()
96
97        def chunk(delta, finish=None, **extra):
98            d = {"id": "x", "choices": [{"index": 0, "delta": delta, "finish_reason": finish}], **extra}
99            self.wfile.write(b"data: " + json.dumps(d).encode() + b"\n\n")
100            self.wfile.flush()
101        chunk({"role": "assistant"})
102        for _ in range(gen):
103            chunk({"content": "word "})
104        chunk({}, "stop", usage={"prompt_tokens": prompt, "completion_tokens": gen, "total_tokens": prompt + gen,
105                                 "prompt_tokens_details": {"cached_tokens": cached}},
106              timings={"cache_n": cached, "prompt_n": prompt - cached, "prompt_ms": 100.0,
107                       "prompt_per_second": 1000.0 + n, "predicted_n": gen, "predicted_ms": 200.0, "predicted_per_second": 60.0})
108        self.wfile.write(b"data: [DONE]\n\n")
109
110
111class SuiteTests(unittest.TestCase):
112    def setUp(self):
113        self.srv = FakeStrata()
114        self.addCleanup(self.srv.stop)
115
116    def suite(self, **kw):
117        return B.Suite(self.srv.base, "", kw.pop("ctx", 32768), kw.pop("runs", 3), False, log=lambda *a: None, **kw)
118
119    def test_full_suite_shapes_and_medians(self):
120        out = self.suite(want_clients=3).run()
121        self.assertEqual(out["failures"], [])
122        self.assertEqual(out["chat"]["decode_tps"]["median"], 60.0)
123        self.assertEqual(out["chat"]["decode_tps"]["n"], 9)                 # 3 questions x 3 runs
124        self.assertEqual(set(out["prompts"]), {"4K", "16K"})
125        for v in out["prompts"].values():
126            self.assertEqual(v["prompt_tps"]["n"], 3)
127            self.assertLess(v["reused_tokens"]["median"], v["prompt_tokens"]["median"] / 100)   # a fresh tag at the start: next to nothing reused
128        p4, p16 = (out["prompts"][k]["prompt_tokens"]["median"] for k in ("4K", "16K"))
129        self.assertAlmostEqual(p16 / p4, 4, delta=0.6)                      # the sizes are calibrated, not guessed
130        self.assertEqual(out["clients"]["clients"], 3)
131        self.assertEqual(out["clients"]["errors"], 0)
132        self.assertEqual(out["clients"]["rounds"][0]["tokens"], 3 * 12)
133
134    def test_agent_session_reuses_the_conversation(self):
135        out = self.suite(runs=2).run()
136        ag = out["agent"]
137        self.assertEqual(len(ag["sessions"]), 2)
138        turns = ag["sessions"][0]
139        self.assertEqual([t["turn"] for t in turns], list(range(B.AGENT_TURNS + 1)))
140        self.assertEqual(turns[0]["reused_tokens"], 0)
141        for t in turns[1:]:
142            self.assertGreater(t["reused_tokens"], 0)
143            self.assertLess(t["read_tokens"], t["prompt_tokens"])
144        self.assertGreater(ag["hit_pct"]["median"], 50)
145        self.assertLess(ag["reread_tokens"]["median"], ag["new_tokens"]["median"])      # new file text dominates, not re-reading
146        self.assertGreater(turns[-1]["prompt_tokens"], turns[1]["prompt_tokens"])    # the conversation grows
147
148    def test_small_context_skips_the_long_prompts(self):
149        self.srv.ctx = 8192
150        out = self.suite(ctx=8192, runs=1, want_long=True).run()
151        self.assertIn("4K", out["prompts"])
152        self.assertEqual(set(out["skipped"]), {"16K", "32K", "agent"})
153        self.assertIn("below ~10K", out["skipped"]["agent"])
154        self.assertEqual(out["agent"], {})                                  # no request was sent for the agent session
155
156    def test_agent_runs_when_the_context_fits_it(self):
157        out = self.suite(ctx=16384, runs=1).run()
158        self.assertNotIn("agent", out["skipped"])
159        self.assertTrue(out["agent"]["sessions"])
160
161    def test_failures_are_reported_not_hidden(self):
162        self.srv.fail_after = 3                  # warm-up and calibration succeed, then every request fails
163        out = self.suite(runs=1).run()
164        self.assertTrue(out["failures"])
165        self.assertTrue(all("HTTP 500" in f["error"] for f in out["failures"]))
166        self.assertIsNone(out["chat"]["decode_tps"])
167
168
169class RedactionTests(unittest.TestCase):
170    def test_paths_names_ips_and_keys(self):
171        red = B.redactor(extra=["Jane Roe Laptop"], key="sk-secret-123456")
172        user = os.environ.get("USERNAME") or os.environ.get("USER") or "tester"
173        cases = [r"C:\Users\someone_else\models\a.gguf", "/home/bob/strata/x.json", "/Users/alice/Library",
174                 "peer 192.168.1.20 and 10.0.0.7 and 100.101.102.103", "Authorization: Bearer abcdefghijkl12345",
175                 "key sk-secret-123456 here", "name Jane Roe Laptop"]
176        text = red("\n".join(cases))
177        for s in ("someone_else", "bob", "alice", "192.168.1.20", "10.0.0.7", "100.101.102.103", "abcdefghijkl12345",
178                  "sk-secret-123456", "Jane Roe Laptop"):
179            self.assertNotIn(s, text)
180        self.assertIn("<user>", text)
181        self.assertIn("<ip>", text)
182        self.assertEqual(red("127.0.0.1:8080 and version 0.1.40.3 and driver 32.0.15.7"), "127.0.0.1:8080 and version 0.1.40.3 and driver 32.0.15.7")
183        self.assertNotIn(str(B.ROOT), red(f"loading {B.ROOT / 'strata-x.json'}"))
184        self.assertIn("<strata>", red(f"loading {B.ROOT / 'strata-x.json'}"))
185        self.assertNotIn(str(Path.home()), red(f"in {Path.home() / 'data'}"))
186        if len(user) >= 4 and user.lower() not in "<user><home><ip><strata>":     # a user called "user" is left in the <user> that replaces it
187            self.assertNotIn(user, red(f"hello {user} world"))
188
189    def test_a_folder_under_a_short_home_keeps_its_own_placeholder(self):
190        # issue #3326 with a fixed machine (user name "dgbox", the repository directly under the home folder):
191        # a name is wrapped in word bounds, which makes its pattern longer than the pattern of the folder
192        # holding it, so the name won and the report kept the folder layout instead of <strata> and <home>.
193        def red(root, home, user, host, tmp):
194            with mock.patch.object(B, "ROOT", root), mock.patch.object(B.Path, "home", return_value=home), \
195                 mock.patch.object(B.getpass, "getuser", return_value=user), \
196                 mock.patch.object(B.socket, "gethostname", return_value=host), \
197                 mock.patch.object(B.platform, "node", return_value=host), \
198                 mock.patch.object(B.tempfile, "gettempdir", return_value=tmp):
199                return B.redactor()
200
201        linux = red(PurePosixPath("/home/dgbox/Strata"), PurePosixPath("/home/dgbox"), "dgbox", "dgbox-ubuntu-server", "/tmp")
202        self.assertEqual(linux("loading /home/dgbox/Strata/strata-x.json"), "loading <strata>/strata-x.json")
203        self.assertEqual(linux("dgbox-ubuntu-server wrote /home/dgbox/Strata/bench/results/run/results.json"),
204                         "<host> wrote <strata>/bench/results/run/results.json")
205        self.assertEqual(linux("in /home/dgbox/data"), "in <home>/data")
206        self.assertEqual(linux("hello dgbox world"), "hello <user> world")
207        self.assertEqual(linux("log /tmp/strata.log"), "log <tmp>/strata.log")
208        win = red(PureWindowsPath(r"C:\Users\dgbox\Strata"), PureWindowsPath(r"C:\Users\dgbox"), "dgbox", "dgbox-pc",
209                  r"C:\Users\dgbox\AppData\Local\Temp")
210        self.assertEqual(win(r"in C:\Users\dgbox\data"), r"in <home>\data")
211        self.assertEqual(win(r"loading C:\Users\dgbox\Strata\strata-x.json"), r"loading <strata>\strata-x.json")
212
213    def test_objects_are_redacted_deeply(self):
214        red = B.redactor()
215        out = B.redact_obj({"a": [{"p": r"D:\Users\zed\x"}], "n": 3}, red)
216        self.assertNotIn("zed", json.dumps(out))
217        self.assertEqual(out["n"], 3)
218
219    def test_config_view_drops_secrets_and_cuts_paths(self):
220        cfg = {"exe": r"C:\Users\me\Strata\engine\strata.exe", "args": ["--native", "/home/me/models/m-IQ3_XXS.gguf", "--ctx", "65536"],
221               "api_key": "hunter2", "model_name": "Fake Model", "log": "/tmp/x.log", "port": 8080,
222               "env": {"STRATA_FOO": "/home/me/z", "PATH": "/usr/bin", "STRATA_TOKEN": "t"}}
223        v = B.config_view(cfg)
224        self.assertEqual(v["exe"], "strata.exe")
225        self.assertEqual(v["args"], ["--native", "m-IQ3_XXS.gguf", "--ctx", "65536"])
226        self.assertNotIn("api_key", v)
227        self.assertNotIn("log", v)
228        self.assertEqual(v["env"], {"STRATA_FOO": "z"})
229        self.assertEqual(B.detect_quant(v), "IQ3_XXS")
230        self.assertNotIn("hunter2", json.dumps(v))
231
232
233class ReportTests(unittest.TestCase):
234    def setUp(self):
235        p = mock.patch.object(B, "gpu_info_local", return_value={"gpus": []})     # the server's own GPU name, not this PC's
236        p.start()
237        self.addCleanup(p.stop)
238
239    def run_main(self, srv, out_dir, *extra):
240        argv = ["--url", srv.base, "--out", out_dir, "--runs", "2", "--quiet", *extra]
241        return B.main(argv)
242
243    def test_main_writes_a_redacted_report(self):
244        srv = FakeStrata()
245        self.addCleanup(srv.stop)
246        with tempfile.TemporaryDirectory() as d:
247            self.assertEqual(self.run_main(srv, d, "--clients", "2"), 0)
248            dirs = list(Path(d).iterdir())
249            self.assertEqual(len(dirs), 1)
250            name = dirs[0].name
251            self.assertRegex(name, r"^\d{4}-\d\d-\d\d-community-rtx-9999")
252            readme = (dirs[0] / "README.md").read_text(encoding="utf-8")
253            for part in ("# Community benchmark on NVIDIA GeForce RTX 9999", "## Hardware and software", "## Model and configuration",
254                         "## Method", "## Results", "## Correctness and limitations", "### Agent session", "### Concurrency: 2 clients",
255                         "| Configuration | Actual prompt tokens | Reused tokens |"):
256                self.assertIn(part, readme)
257            raw = json.loads((dirs[0] / "results.json").read_text(encoding="utf-8"))
258            self.assertEqual(raw["schema"], B.SCHEMA)
259            self.assertEqual(raw["machine"]["engine_version"], "9.9.9")
260            self.assertEqual(raw["results"]["chat"]["decode_tps"]["median"], 60.0)
261            blob = readme + json.dumps(raw)
262            self.assertNotIn("Someone", blob)                    # the engine's model_path never reaches the report
263            # a second run the same day does not overwrite the first
264            self.assertEqual(self.run_main(srv, d), 0)
265            self.assertEqual(len(list(Path(d).iterdir())), 2)
266
267    def test_compare(self):
268        srv = FakeStrata()
269        self.addCleanup(srv.stop)
270        with tempfile.TemporaryDirectory() as d:
271            self.run_main(srv, d)
272            old = next(Path(d).iterdir())
273            data = json.loads((old / "results.json").read_text(encoding="utf-8"))
274            data["results"]["chat"]["decode_tps"]["median"] = 30.0
275            data["machine"]["engine_version"] = "1.0"
276            (old / "results.json").write_text(json.dumps(data), encoding="utf-8")
277            self.run_main(srv, d)
278            new = max(Path(d).iterdir(), key=lambda p: p.name)
279            table = B.compare_table(B.load_results(old), B.load_results(new))
280            self.assertIn("chat decode tok/s", table)
281            self.assertIn("+100.0%", table)
282            self.assertIn("engine: 1.0 -> 9.9.9", table)
283
284    def test_only_the_gpus_the_engine_uses_are_listed(self):
285        """#1985: a PC with two cards, the engine on one: the report names that one, with its VRAM."""
286        srv = FakeStrata()
287        self.addCleanup(srv.stop)
288        two = {"gpus": [{"name": "NVIDIA GeForce RTX 3060", "vram_mib": 12288, "driver": "560.1"},
289                        {"name": "NVIDIA GeForce RTX 9999", "vram_mib": 16384, "driver": "560.1"}]}
290        with mock.patch.object(B, "gpu_info_local", return_value=two):
291            m = B.collect_machine(srv.base, "", {"gpu": 1})
292            self.assertEqual((m["gpu"], m["gpu_vram_mib"]), (["NVIDIA GeForce RTX 9999"], 16384))
293            m = B.collect_machine(srv.base, "", {"gpu": [0, 1]})
294            self.assertEqual((m["gpu"], m["gpu_vram_mib"]), (["NVIDIA GeForce RTX 3060", "NVIDIA GeForce RTX 9999"], 28672))
295            m = B.collect_machine(srv.base, "", {"gpu": "0"}, "1")            # the bench's own --gpu wins
296            self.assertEqual(m["gpu"], ["NVIDIA GeForce RTX 9999"])
297            m = B.collect_machine(srv.base, "", {"args": ["--gpu", "0"]})
298            self.assertEqual(m["gpu"], ["NVIDIA GeForce RTX 3060"])
299            # nothing selected: one card, the one the server reports (not every card of the PC)
300            m = B.collect_machine(srv.base, "", {})
301            self.assertEqual((m["gpu"], m["gpu_vram_mib"]), (["NVIDIA GeForce RTX 9999"], 16384))
302        self.assertEqual(B.gpu_selection({"gpu": "0,2"}), [0, 2])
303        self.assertEqual(B.gpu_selection({}, None), [])
304
305    def test_the_slug_names_mixed_cards_one_by_one(self):
306        """#2062: two different cards are not N copies of the first."""
307        a, b = "NVIDIA GeForce RTX 5070 Ti", "NVIDIA RTX A4000"
308        self.assertEqual(B.gpu_slug({"gpu": [a]}), "rtx-5070-ti")
309        self.assertEqual(B.gpu_slug({"gpu": [a, b]}), "rtx-5070-ti-plus-rtx-a4000")
310        self.assertEqual(B.gpu_slug({"gpu": [b, a]}), "rtx-a4000-plus-rtx-5070-ti")
311        self.assertEqual(B.gpu_slug({"gpu": [b, b]}), "2x-rtx-a4000")
312        self.assertEqual(B.gpu_slug({"gpu": [b, a, b]}), "2x-rtx-a4000-plus-rtx-5070-ti")
313
314    def test_a_card_the_pc_s_nvidia_smi_does_not_list_is_the_servers_own(self):
315        """#2001: the engine on an Intel Arc beside a GeForce: the report names the Arc (the name the server reads)."""
316        srv = FakeStrata()
317        self.addCleanup(srv.stop)
318        nv = {"gpus": [{"name": "NVIDIA GeForce RTX 3080 Ti", "vram_mib": 12288, "driver": "560.1"}], "cuda": "12.6"}
319        with mock.patch.object(B, "gpu_info_local", return_value=nv), mock.patch.object(
320                B, "try_json", side_effect=lambda base, path, *a, **k: (
321                    {"hardware_static": {"gpu_name": "Intel Arc Pro B70"}} if path == "/metrics" else {})):
322            m = B.collect_machine(srv.base, "", {"backend": "sycl"})
323        self.assertEqual((m["gpu"], m["cuda"]), (["Intel Arc Pro B70"], None))
324
325    def test_the_report_labels_the_driver_s_cuda_and_the_engine_s_build(self):
326        """#2111: the CUDA line was the driver's ceiling read as the engine's toolkit, and storage said "not measured"."""
327        srv = FakeStrata()
328        self.addCleanup(srv.stop)
329        nv = {"gpus": [{"name": "NVIDIA GeForce RTX 9999", "vram_mib": 16384, "driver": "616.92",
330                        "power_limit_w": "165.00", "power_draw_w": "20.25", "pcie": "gen4 x8",
331                        "pstate": "P3", "temp_c": "45"}], "cuda": "13.4"}
332        with mock.patch.object(B, "gpu_info_local", return_value=nv), mock.patch.object(
333                B, "storage_info", return_value="Samsung SSD 990 EVO Plus 2TB SSD/NVMe"), mock.patch.object(
334                B, "engine_build", return_value={"version": "0.1.43", "cuda": "13.0"}):
335            with tempfile.TemporaryDirectory() as d:
336                self.assertEqual(self.run_main(srv, d), 0)
337                readme = next(Path(d).iterdir()).joinpath("README.md").read_text(encoding="utf-8")
338        for part in ("CUDA (driver supports up to): 13.4; engine built for CUDA 13.0",
339                     "storage: Samsung SSD 990 EVO Plus 2TB SSD/NVMe",
340                     "GPU detail (after the run, near idle): power_limit_w=165.00, power_draw_w=20.25, "
341                     "pcie=gen4 x8, pstate=P3, temp_c=45",
342                     "Background workloads: not recorded (GPU power limit/draw read above)"):
343            self.assertIn(part, readme)
344        self.assertNotIn("storage: not measured", readme)
345
346    def test_a_bench_server_never_saves_over_the_users_profile(self):
347        """#2088: --expert-profile-save writes the profile at quit; the bench's own server runs without it."""
348        cfg = {"args": ["--expert-profile", "p.bin", "--expert-profile-save", "p.bin", "--spec", "4"]}
349        safe, removed = B.without_profile_save(cfg)
350        self.assertTrue(removed)
351        self.assertEqual(safe["args"], ["--expert-profile", "p.bin", "--spec", "4"])
352        self.assertEqual(cfg["args"][3], "p.bin")                       # the input is not changed
353        safe, removed = B.without_profile_save({"args": ["--expert-profile-save=p.bin", "--spec", "4"]})
354        self.assertEqual((safe["args"], removed), (["--spec", "4"], True))
355        same = {"args": ["--spec", "4"]}
356        self.assertEqual(B.without_profile_save(same), (same, False))
357        with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as d:
358            c = Path(d) / "strata-x.json"
359            c.write_text(json.dumps(cfg))
360            with mock.patch.object(B.subprocess, "Popen") as popen, contextlib.redirect_stderr(io.StringIO()):
361                B.start_server(c, 8080, None, Path(d) / "run.log")
362            used = Path(popen.call_args[0][0][popen.call_args[0][0].index("--config") + 1])
363            self.assertNotIn("--expert-profile-save", json.loads(used.read_text())["args"])
364            self.assertIn("--expert-profile-save", json.loads(c.read_text())["args"])   # the user's file is as it was
365
366    def test_an_attached_server_is_not_stopped(self):
367        """#2088: with --url the bench only reads; the server it did not start keeps running."""
368        srv = FakeStrata()
369        self.addCleanup(srv.stop)
370        with tempfile.TemporaryDirectory() as d, mock.patch.object(B, "stop_server") as stop:
371            self.assertEqual(self.run_main(srv, d), 0)
372        stop.assert_not_called()
373
374    def test_names(self):
375        m = {"gpu": ["NVIDIA GeForce RTX 3060"], "model": "Qwen3.8 Flash-Next", "quant": "IQ3_XXS"}
376        self.assertEqual(B.results_dir_name(m, "2026-10-10"), "2026-10-10-community-rtx-3060-qwen3-8-flash-next-iq3-xxs")
377        m["model"] = "qwen-iq3_xxs"                                      # a quant already in the name is not added twice
378        self.assertEqual(B.results_dir_name(m, "2026-10-10"), "2026-10-10-community-rtx-3060-qwen-iq3-xxs")
379        self.assertEqual(B.gpu_slug({"gpu": ["A B 4090", "A B 4090"]}), "2x-a-b-4090")
380        m["model"] = "qwen-iq3_xxs"                                      # a quant already in the name is not added twice
381        self.assertEqual(B.results_dir_name(m, "2026-10-10"), "2026-10-10-community-rtx-3060-qwen-iq3-xxs")
382        self.assertEqual(B.gpu_slug({"gpu": []}), "cpu")
383
384    def test_no_server_is_an_error_not_a_crash(self):
385        self.assertEqual(B.main(["--url", "http://127.0.0.1:9", "--quiet"]), 2)
386
387    def test_project_version_does_not_use_the_locale_code_page(self):
388        # #2792: on Windows a text file read without an encoding is decoded with the locale's code page, and CMakeLists.txt
389        # is UTF-8 with non-ASCII text.  Path.read_text here defaults to each Windows ANSI code page in turn.
390        original = Path.read_text
391        with tempfile.TemporaryDirectory() as d:
392            root = Path(d)
393            (root / "CMakeLists.txt").write_bytes(
394                "cmake_minimum_required(VERSION 3.24)\n# notes — § €\nproject(strata VERSION 9.8.7 LANGUAGES CXX)\n"
395                .encode("utf-8"))
396            for code_page in ("cp874", "cp932", "cp936", "cp949", "cp950", "cp1250", "cp1251", "cp1252", "cp1253",
397                              "cp1254", "cp1255", "cp1256", "cp1257", "cp1258"):
398                def locale_default(self, encoding=None, errors=None, **kw):
399                    return original(self, encoding=encoding or code_page, errors=errors, **kw)
400
401                with self.subTest(code_page=code_page), mock.patch.object(B, "ROOT", root), \
402                        mock.patch.object(Path, "read_text", locale_default):
403                    self.assertEqual(B.project_version(), "9.8.7")
404
405
406class MachineDetailTests(unittest.TestCase):
407    """#2111: what the report reads straight from nvidia-smi on the PC."""
408
409    ROW = "NVIDIA GeForce RTX 4060 Ti, 16380, 616.92, 165.00, 20.25, 4, 8, P3, 45"
410
411    @staticmethod
412    def queries(cmd) -> bool:
413        return any(str(c).startswith("--query-gpu") for c in cmd)
414
415    def test_cuda_header_in_both_forms(self):
416        """Current drivers print "CUDA UMD Version: 13.4"; the old "CUDA Version:" line still has to be read."""
417        for head, want in (("Some header\n\nCUDA UMD Version: 13.4\n", "13.4"),
418                           ("Some header\n\nCUDA Version: 12.6\n", "12.6")):
419            def fake(cmd, *a, _head=head, **k):
420                return self.ROW if self.queries(cmd) else _head
421            with mock.patch.object(B, "run_cmd", side_effect=fake):
422                info = B.gpu_info_local()
423            self.assertEqual((info["cuda"], info["gpus"][0]["power_limit_w"]), (want, "165.00"))
424
425    def test_power_pcie_pstate_and_temperature_are_read(self):
426        with mock.patch.object(B, "run_cmd",
427                               side_effect=lambda cmd, *a, **k: self.ROW if self.queries(cmd) else ""):
428            g = B.gpu_info_local()["gpus"][0]
429        self.assertEqual((g["name"], g["vram_mib"], g["driver"]), ("NVIDIA GeForce RTX 4060 Ti", 16380, "616.92"))
430        self.assertEqual((g["power_limit_w"], g["pcie"], g["pstate"], g["temp_c"]), ("165.00", "gen4 x8", "P3", "45"))
431
432
433if __name__ == "__main__":
434    unittest.main()