okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
b0fc432ed
main
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 : 22return "" .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 27previous prompt (4 characters = 1 token).""" 28daemon_threads = True 29 30def __init__ (self ,ctx = 32768 ,fail_after = None ): 31super ().__init__ (("127.0.0.1" ,0 ),Handler ) 32self .ctx ,self .prev ,self .requests ,self .fail_after = ctx ,"" ,0 ,fail_after 33self .lock = threading .Lock () 34threading .Thread (target = self .serve_forever ,daemon = True ).start () 35 36def stop (self ): 37self .shutdown () 38self .server_close () 39 40@property 41def base (self ): 42return f"http://127.0.0.1: { self . server_address [ 1 ] } " 43 44 45class Handler (BaseHTTPRequestHandler ): 46def log_message (self ,* a ): 47pass 48 49def send_json (self ,obj ,code = 200 ): 50body = json .dumps (obj ).encode () 51self .send_response (code ) 52self .send_header ("Content-Type" ,"application/json" ) 53self .send_header ("Content-Length" ,str (len (body ))) 54self .end_headers () 55self .wfile .write (body ) 56 57def do_GET (self ): 58s = self .server 59if self .path == "/health" : 60self .send_json ({"status" :"ok" ,"service" :"strata" ,"loaded" :True }) 61elif self .path == "/v1/models" : 62self .send_json ({"object" :"list" ,"data" : [{"id" :"fake" ,"meta" : {"n_ctx" :s .ctx }}]}) 63elif self .path == "/props" : 64self .send_json ({"total_slots" :4 ,"model_alias" :"fake-model" ,"build_info" :"Strata 9.9.9" }) 65elif self .path == "/v1/status" : 66self .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 }}) 68elif self .path == "/metrics" : 69self .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 }}) 71else : 72self .send_json ({},404 ) 73 74def do_POST (self ): 75s = self .server 76req = json .loads (self .rfile .read (int (self .headers ["Content-Length" ]))) 77text = text_of (req ["messages" ]) 78with s .lock : 79s .requests += 1 80n = s .requests 81common = 0 82for x ,y in zip (s .prev ,text ): 83if x != y : 84break 85common += 1 86s .prev = text 87if s .fail_after is not None and n > s .fail_after : 88self .send_json ({"error" :"boom" },500 ) 89return 90prompt = max (1 ,len (text )// 4 ) 91cached = min (prompt ,common // 4 ) 92gen = min (req .get ("max_tokens" ,16 ),12 ) 93self .send_response (200 ) 94self .send_header ("Content-Type" ,"text/event-stream" ) 95self .end_headers () 96 97def chunk (delta ,finish = None ,** extra ): 98d = {"id" :"x" ,"choices" : [{"index" :0 ,"delta" :delta ,"finish_reason" :finish }],** extra } 99self .wfile .write (b"data: " + json .dumps (d ).encode ()+ b"\n\n" ) 100self .wfile .flush () 101chunk ({"role" :"assistant" }) 102for _ in range (gen ): 103chunk ({"content" :"word " }) 104chunk ({},"stop" ,usage = {"prompt_tokens" :prompt ,"completion_tokens" :gen ,"total_tokens" :prompt + gen , 105"prompt_tokens_details" : {"cached_tokens" :cached }}, 106timings = {"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 }) 108self .wfile .write (b"data: [DONE]\n\n" ) 109 110 111class SuiteTests (unittest .TestCase ): 112def setUp (self ): 113self .srv = FakeStrata () 114self .addCleanup (self .srv .stop ) 115 116def suite (self ,** kw ): 117return B .Suite (self .srv .base ,"" ,kw .pop ("ctx" ,32768 ),kw .pop ("runs" ,3 ),False ,log = lambda * a :None ,** kw ) 118 119def test_full_suite_shapes_and_medians (self ): 120out = self .suite (want_clients = 3 ).run () 121self .assertEqual (out ["failures" ], []) 122self .assertEqual (out ["chat" ]["decode_tps" ]["median" ],60.0 ) 123self .assertEqual (out ["chat" ]["decode_tps" ]["n" ],9 )# 3 questions x 3 runs 124self .assertEqual (set (out ["prompts" ]), {"4K" ,"16K" }) 125for v in out ["prompts" ].values (): 126self .assertEqual (v ["prompt_tps" ]["n" ],3 ) 127self .assertLess (v ["reused_tokens" ]["median" ],v ["prompt_tokens" ]["median" ]/ 100 )# a fresh tag at the start: next to nothing reused 128p4 ,p16 = (out ["prompts" ][k ]["prompt_tokens" ]["median" ]for k in ("4K" ,"16K" )) 129self .assertAlmostEqual (p16 / p4 ,4 ,delta = 0.6 )# the sizes are calibrated, not guessed 130self .assertEqual (out ["clients" ]["clients" ],3 ) 131self .assertEqual (out ["clients" ]["errors" ],0 ) 132self .assertEqual (out ["clients" ]["rounds" ][0 ]["tokens" ],3 * 12 ) 133 134def test_agent_session_reuses_the_conversation (self ): 135out = self .suite (runs = 2 ).run () 136ag = out ["agent" ] 137self .assertEqual (len (ag ["sessions" ]),2 ) 138turns = ag ["sessions" ][0 ] 139self .assertEqual ([t ["turn" ]for t in turns ],list (range (B .AGENT_TURNS + 1 ))) 140self .assertEqual (turns [0 ]["reused_tokens" ],0 ) 141for t in turns [1 :]: 142self .assertGreater (t ["reused_tokens" ],0 ) 143self .assertLess (t ["read_tokens" ],t ["prompt_tokens" ]) 144self .assertGreater (ag ["hit_pct" ]["median" ],50 ) 145self .assertLess (ag ["reread_tokens" ]["median" ],ag ["new_tokens" ]["median" ])# new file text dominates, not re-reading 146self .assertGreater (turns [- 1 ]["prompt_tokens" ],turns [1 ]["prompt_tokens" ])# the conversation grows 147 148def test_small_context_skips_the_long_prompts (self ): 149self .srv .ctx = 8192 150out = self .suite (ctx = 8192 ,runs = 1 ,want_long = True ).run () 151self .assertIn ("4K" ,out ["prompts" ]) 152self .assertEqual (set (out ["skipped" ]), {"16K" ,"32K" ,"agent" }) 153self .assertIn ("below ~10K" ,out ["skipped" ]["agent" ]) 154self .assertEqual (out ["agent" ], {})# no request was sent for the agent session 155 156def test_agent_runs_when_the_context_fits_it (self ): 157out = self .suite (ctx = 16384 ,runs = 1 ).run () 158self .assertNotIn ("agent" ,out ["skipped" ]) 159self .assertTrue (out ["agent" ]["sessions" ]) 160 161def test_failures_are_reported_not_hidden (self ): 162self .srv .fail_after = 3 # warm-up and calibration succeed, then every request fails 163out = self .suite (runs = 1 ).run () 164self .assertTrue (out ["failures" ]) 165self .assertTrue (all ("HTTP 500" in f ["error" ]for f in out ["failures" ])) 166self .assertIsNone (out ["chat" ]["decode_tps" ]) 167 168 169class RedactionTests (unittest .TestCase ): 170def test_paths_names_ips_and_keys (self ): 171red = B .redactor (extra = ["Jane Roe Laptop" ],key = "sk-secret-123456" ) 172user = os .environ .get ("USERNAME" )or os .environ .get ("USER" )or "tester" 173cases = [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" ] 176text = red ("\n" .join (cases )) 177for 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" ): 179self .assertNotIn (s ,text ) 180self .assertIn ("<user>" ,text ) 181self .assertIn ("<ip>" ,text ) 182self .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" ) 183self .assertNotIn (str (B .ROOT ),red (f"loading { B . ROOT / 'strata-x.json' } " )) 184self .assertIn ("<strata>" ,red (f"loading { B . ROOT / 'strata-x.json' } " )) 185self .assertNotIn (str (Path .home ()),red (f"in { Path . home () / 'data' } " )) 186if len (user )>= 4 and user .lower ()not in "<user><home><ip><strata>" :# a user called "user" is left in the <user> that replaces it 187self .assertNotIn (user ,red (f"hello { user } world" )) 188 189def 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>. 193def red (root ,home ,user ,host ,tmp ): 194with mock .patch .object (B ,"ROOT" ,root ),mock .patch .object (B .Path ,"home" ,return_value = home ), \ 195mock .patch .object (B .getpass ,"getuser" ,return_value = user ), \ 196mock .patch .object (B .socket ,"gethostname" ,return_value = host ), \ 197mock .patch .object (B .platform ,"node" ,return_value = host ), \ 198mock .patch .object (B .tempfile ,"gettempdir" ,return_value = tmp ): 199return B .redactor () 200 201linux = red (PurePosixPath ("/home/dgbox/Strata" ),PurePosixPath ("/home/dgbox" ),"dgbox" ,"dgbox-ubuntu-server" ,"/tmp" ) 202self .assertEqual (linux ("loading /home/dgbox/Strata/strata-x.json" ),"loading <strata>/strata-x.json" ) 203self .assertEqual (linux ("dgbox-ubuntu-server wrote /home/dgbox/Strata/bench/results/run/results.json" ), 204"<host> wrote <strata>/bench/results/run/results.json" ) 205self .assertEqual (linux ("in /home/dgbox/data" ),"in <home>/data" ) 206self .assertEqual (linux ("hello dgbox world" ),"hello <user> world" ) 207self .assertEqual (linux ("log /tmp/strata.log" ),"log <tmp>/strata.log" ) 208win = red (PureWindowsPath (r"C:\Users\dgbox\Strata" ),PureWindowsPath (r"C:\Users\dgbox" ),"dgbox" ,"dgbox-pc" , 209r"C:\Users\dgbox\AppData\Local\Temp" ) 210self .assertEqual (win (r"in C:\Users\dgbox\data" ),r"in <home>\data" ) 211self .assertEqual (win (r"loading C:\Users\dgbox\Strata\strata-x.json" ),r"loading <strata>\strata-x.json" ) 212 213def test_objects_are_redacted_deeply (self ): 214red = B .redactor () 215out = B .redact_obj ({"a" : [{"p" :r"D:\Users\zed\x" }],"n" :3 },red ) 216self .assertNotIn ("zed" ,json .dumps (out )) 217self .assertEqual (out ["n" ],3 ) 218 219def test_config_view_drops_secrets_and_cuts_paths (self ): 220cfg = {"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" }} 223v = B .config_view (cfg ) 224self .assertEqual (v ["exe" ],"strata.exe" ) 225self .assertEqual (v ["args" ], ["--native" ,"m-IQ3_XXS.gguf" ,"--ctx" ,"65536" ]) 226self .assertNotIn ("api_key" ,v ) 227self .assertNotIn ("log" ,v ) 228self .assertEqual (v ["env" ], {"STRATA_FOO" :"z" }) 229self .assertEqual (B .detect_quant (v ),"IQ3_XXS" ) 230self .assertNotIn ("hunter2" ,json .dumps (v )) 231 232 233class ReportTests (unittest .TestCase ): 234def setUp (self ): 235p = mock .patch .object (B ,"gpu_info_local" ,return_value = {"gpus" : []})# the server's own GPU name, not this PC's 236p .start () 237self .addCleanup (p .stop ) 238 239def run_main (self ,srv ,out_dir ,* extra ): 240argv = ["--url" ,srv .base ,"--out" ,out_dir ,"--runs" ,"2" ,"--quiet" ,* extra ] 241return B .main (argv ) 242 243def test_main_writes_a_redacted_report (self ): 244srv = FakeStrata () 245self .addCleanup (srv .stop ) 246with tempfile .TemporaryDirectory ()as d : 247self .assertEqual (self .run_main (srv ,d ,"--clients" ,"2" ),0 ) 248dirs = list (Path (d ).iterdir ()) 249self .assertEqual (len (dirs ),1 ) 250name = dirs [0 ].name 251self .assertRegex (name ,r"^\d{4}-\d\d-\d\d-community-rtx-9999" ) 252readme = (dirs [0 ]/ "README.md" ).read_text (encoding = "utf-8" ) 253for 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 |" ): 256self .assertIn (part ,readme ) 257raw = json .loads ((dirs [0 ]/ "results.json" ).read_text (encoding = "utf-8" )) 258self .assertEqual (raw ["schema" ],B .SCHEMA ) 259self .assertEqual (raw ["machine" ]["engine_version" ],"9.9.9" ) 260self .assertEqual (raw ["results" ]["chat" ]["decode_tps" ]["median" ],60.0 ) 261blob = readme + json .dumps (raw ) 262self .assertNotIn ("Someone" ,blob )# the engine's model_path never reaches the report 263# a second run the same day does not overwrite the first 264self .assertEqual (self .run_main (srv ,d ),0 ) 265self .assertEqual (len (list (Path (d ).iterdir ())),2 ) 266 267def test_compare (self ): 268srv = FakeStrata () 269self .addCleanup (srv .stop ) 270with tempfile .TemporaryDirectory ()as d : 271self .run_main (srv ,d ) 272old = next (Path (d ).iterdir ()) 273data = json .loads ((old / "results.json" ).read_text (encoding = "utf-8" )) 274data ["results" ]["chat" ]["decode_tps" ]["median" ]= 30.0 275data ["machine" ]["engine_version" ]= "1.0" 276 (old / "results.json" ).write_text (json .dumps (data ),encoding = "utf-8" ) 277self .run_main (srv ,d ) 278new = max (Path (d ).iterdir (),key = lambda p :p .name ) 279table = B .compare_table (B .load_results (old ),B .load_results (new )) 280self .assertIn ("chat decode tok/s" ,table ) 281self .assertIn ("+100.0%" ,table ) 282self .assertIn ("engine: 1.0 -> 9.9.9" ,table ) 283 284def 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.""" 286srv = FakeStrata () 287self .addCleanup (srv .stop ) 288two = {"gpus" : [{"name" :"NVIDIA GeForce RTX 3060" ,"vram_mib" :12288 ,"driver" :"560.1" }, 289 {"name" :"NVIDIA GeForce RTX 9999" ,"vram_mib" :16384 ,"driver" :"560.1" }]} 290with mock .patch .object (B ,"gpu_info_local" ,return_value = two ): 291m = B .collect_machine (srv .base ,"" , {"gpu" :1 }) 292self .assertEqual ((m ["gpu" ],m ["gpu_vram_mib" ]), (["NVIDIA GeForce RTX 9999" ],16384 )) 293m = B .collect_machine (srv .base ,"" , {"gpu" : [0 ,1 ]}) 294self .assertEqual ((m ["gpu" ],m ["gpu_vram_mib" ]), (["NVIDIA GeForce RTX 3060" ,"NVIDIA GeForce RTX 9999" ],28672 )) 295m = B .collect_machine (srv .base ,"" , {"gpu" :"0" },"1" )# the bench's own --gpu wins 296self .assertEqual (m ["gpu" ], ["NVIDIA GeForce RTX 9999" ]) 297m = B .collect_machine (srv .base ,"" , {"args" : ["--gpu" ,"0" ]}) 298self .assertEqual (m ["gpu" ], ["NVIDIA GeForce RTX 3060" ]) 299# nothing selected: one card, the one the server reports (not every card of the PC) 300m = B .collect_machine (srv .base ,"" , {}) 301self .assertEqual ((m ["gpu" ],m ["gpu_vram_mib" ]), (["NVIDIA GeForce RTX 9999" ],16384 )) 302self .assertEqual (B .gpu_selection ({"gpu" :"0,2" }), [0 ,2 ]) 303self .assertEqual (B .gpu_selection ({},None ), []) 304 305def test_the_slug_names_mixed_cards_one_by_one (self ): 306"""#2062: two different cards are not N copies of the first.""" 307a ,b = "NVIDIA GeForce RTX 5070 Ti" ,"NVIDIA RTX A4000" 308self .assertEqual (B .gpu_slug ({"gpu" : [a ]}),"rtx-5070-ti" ) 309self .assertEqual (B .gpu_slug ({"gpu" : [a ,b ]}),"rtx-5070-ti-plus-rtx-a4000" ) 310self .assertEqual (B .gpu_slug ({"gpu" : [b ,a ]}),"rtx-a4000-plus-rtx-5070-ti" ) 311self .assertEqual (B .gpu_slug ({"gpu" : [b ,b ]}),"2x-rtx-a4000" ) 312self .assertEqual (B .gpu_slug ({"gpu" : [b ,a ,b ]}),"2x-rtx-a4000-plus-rtx-5070-ti" ) 313 314def 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).""" 316srv = FakeStrata () 317self .addCleanup (srv .stop ) 318nv = {"gpus" : [{"name" :"NVIDIA GeForce RTX 3080 Ti" ,"vram_mib" :12288 ,"driver" :"560.1" }],"cuda" :"12.6" } 319with mock .patch .object (B ,"gpu_info_local" ,return_value = nv ),mock .patch .object ( 320B ,"try_json" ,side_effect = lambda base ,path ,* a ,** k : ( 321 {"hardware_static" : {"gpu_name" :"Intel Arc Pro B70" }}if path == "/metrics" else {})): 322m = B .collect_machine (srv .base ,"" , {"backend" :"sycl" }) 323self .assertEqual ((m ["gpu" ],m ["cuda" ]), (["Intel Arc Pro B70" ],None )) 324 325def 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".""" 327srv = FakeStrata () 328self .addCleanup (srv .stop ) 329nv = {"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" } 332with mock .patch .object (B ,"gpu_info_local" ,return_value = nv ),mock .patch .object ( 333B ,"storage_info" ,return_value = "Samsung SSD 990 EVO Plus 2TB SSD/NVMe" ),mock .patch .object ( 334B ,"engine_build" ,return_value = {"version" :"0.1.43" ,"cuda" :"13.0" }): 335with tempfile .TemporaryDirectory ()as d : 336self .assertEqual (self .run_main (srv ,d ),0 ) 337readme = next (Path (d ).iterdir ()).joinpath ("README.md" ).read_text (encoding = "utf-8" ) 338for 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)" ): 343self .assertIn (part ,readme ) 344self .assertNotIn ("storage: not measured" ,readme ) 345 346def 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.""" 348cfg = {"args" : ["--expert-profile" ,"p.bin" ,"--expert-profile-save" ,"p.bin" ,"--spec" ,"4" ]} 349safe ,removed = B .without_profile_save (cfg ) 350self .assertTrue (removed ) 351self .assertEqual (safe ["args" ], ["--expert-profile" ,"p.bin" ,"--spec" ,"4" ]) 352self .assertEqual (cfg ["args" ][3 ],"p.bin" )# the input is not changed 353safe ,removed = B .without_profile_save ({"args" : ["--expert-profile-save=p.bin" ,"--spec" ,"4" ]}) 354self .assertEqual ((safe ["args" ],removed ), (["--spec" ,"4" ],True )) 355same = {"args" : ["--spec" ,"4" ]} 356self .assertEqual (B .without_profile_save (same ), (same ,False )) 357with tempfile .TemporaryDirectory (ignore_cleanup_errors = True )as d : 358c = Path (d )/ "strata-x.json" 359c .write_text (json .dumps (cfg )) 360with mock .patch .object (B .subprocess ,"Popen" )as popen ,contextlib .redirect_stderr (io .StringIO ()): 361B .start_server (c ,8080 ,None ,Path (d )/ "run.log" ) 362used = Path (popen .call_args [0 ][0 ][popen .call_args [0 ][0 ].index ("--config" )+ 1 ]) 363self .assertNotIn ("--expert-profile-save" ,json .loads (used .read_text ())["args" ]) 364self .assertIn ("--expert-profile-save" ,json .loads (c .read_text ())["args" ])# the user's file is as it was 365 366def test_an_attached_server_is_not_stopped (self ): 367"""#2088: with --url the bench only reads; the server it did not start keeps running.""" 368srv = FakeStrata () 369self .addCleanup (srv .stop ) 370with tempfile .TemporaryDirectory ()as d ,mock .patch .object (B ,"stop_server" )as stop : 371self .assertEqual (self .run_main (srv ,d ),0 ) 372stop .assert_not_called () 373 374def test_names (self ): 375m = {"gpu" : ["NVIDIA GeForce RTX 3060" ],"model" :"Qwen3.8 Flash-Next" ,"quant" :"IQ3_XXS" } 376self .assertEqual (B .results_dir_name (m ,"2026-10-10" ),"2026-10-10-community-rtx-3060-qwen3-8-flash-next-iq3-xxs" ) 377m ["model" ]= "qwen-iq3_xxs" # a quant already in the name is not added twice 378self .assertEqual (B .results_dir_name (m ,"2026-10-10" ),"2026-10-10-community-rtx-3060-qwen-iq3-xxs" ) 379self .assertEqual (B .gpu_slug ({"gpu" : ["A B 4090" ,"A B 4090" ]}),"2x-a-b-4090" ) 380m ["model" ]= "qwen-iq3_xxs" # a quant already in the name is not added twice 381self .assertEqual (B .results_dir_name (m ,"2026-10-10" ),"2026-10-10-community-rtx-3060-qwen-iq3-xxs" ) 382self .assertEqual (B .gpu_slug ({"gpu" : []}),"cpu" ) 383 384def test_no_server_is_an_error_not_a_crash (self ): 385self .assertEqual (B .main (["--url" ,"http://127.0.0.1:9" ,"--quiet" ]),2 ) 386 387def 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. 390original = Path .read_text 391with tempfile .TemporaryDirectory ()as d : 392root = 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" )) 396for code_page in ("cp874" ,"cp932" ,"cp936" ,"cp949" ,"cp950" ,"cp1250" ,"cp1251" ,"cp1252" ,"cp1253" , 397"cp1254" ,"cp1255" ,"cp1256" ,"cp1257" ,"cp1258" ): 398def locale_default (self ,encoding = None ,errors = None ,** kw ): 399return original (self ,encoding = encoding or code_page ,errors = errors ,** kw ) 400 401with self .subTest (code_page = code_page ),mock .patch .object (B ,"ROOT" ,root ), \ 402mock .patch .object (Path ,"read_text" ,locale_default ): 403self .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 409ROW = "NVIDIA GeForce RTX 4060 Ti, 16380, 616.92, 165.00, 20.25, 4, 8, P3, 45" 410 411@staticmethod 412def queries (cmd )-> bool : 413return any (str (c ).startswith ("--query-gpu" )for c in cmd ) 414 415def 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.""" 417for 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" )): 419def fake (cmd ,* a ,_head = head ,** k ): 420return self .ROW if self .queries (cmd )else _head 421with mock .patch .object (B ,"run_cmd" ,side_effect = fake ): 422info = B .gpu_info_local () 423self .assertEqual ((info ["cuda" ],info ["gpus" ][0 ]["power_limit_w" ]), (want ,"165.00" )) 424 425def test_power_pcie_pstate_and_temperature_are_read (self ): 426with mock .patch .object (B ,"run_cmd" , 427side_effect = lambda cmd ,* a ,** k :self .ROW if self .queries (cmd )else "" ): 428g = B .gpu_info_local ()["gpus" ][0 ] 429self .assertEqual ((g ["name" ],g ["vram_mib" ],g ["driver" ]), ("NVIDIA GeForce RTX 4060 Ti" ,16380 ,"616.92" )) 430self .assertEqual ((g ["power_limit_w" ],g ["pcie" ],g ["pstate" ],g ["temp_c" ]), ("165.00" ,"gen4 x8" ,"P3" ,"45" )) 431 432 433if __name__ == "__main__" : 434unittest .main ()