okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
92ca0c7fb
main
1"""serve/test_runconfig.py - #564: the web page's Settings view of the run config (GET / POST /config), against the 2mock engine: only the listed keys change, every other key of the file stays, a bad value changes nothing, and only 3Strata's own page may write it (JSON, no foreign Origin, the API key when one is set). 4 5python -m unittest serve.test_runconfig 6""" 7from __future__import annotations 8 9import contextlib 10import io 11import json 12import tempfile 13import unittest 14import urllib .error 15import urllib .request 16from pathlib import Path 17 18from serve import runconfig 19from serve .frontend import ChatTemplate 20from serve .server import ByteTokenizer ,MockEngine ,Service ,serve 21 22ROOT = Path (__file__ ).resolve ().parents [1 ] 23CFG = {"exe" :"engine/strata.exe" ,"args" : ["--pack" ,"data/packs/q2_0" ,"--kv" ,"int8" ,"--spec-min-p" ,"0.5" ], 24"model_name" :"qwen3.8-flash-next-q2_0" ,"port" :8080 ,"host" :"0.0.0.0" ,"api_key" :"" , 25"sampling" : {"temperature" :0.7 ,"presence_penalty" :1.5 }, 26"mcp_servers" : {"files" : {"command" :"npx" ,"args" : ["-y" ,"server-filesystem" ,"." ]}}, 27"cors_origins" : ["http://localhost:3000" ]} 28 29 30class Apply (unittest .TestCase ): 31def test_only_the_named_keys_change (self ): 32new ,changed = runconfig .apply (CFG , {"sampling.top_p" :0.95 ,"reasoning_budget_tokens" :4096 , 33"vram_reserve_mib" :2048 ,"aliases" :"qwen, local" ,"lazy_load" :True }) 34self .assertEqual (changed , ["sampling.top_p" ,"reasoning_budget_tokens" ,"vram_reserve_mib" ,"aliases" , 35"lazy_load" ]) 36self .assertEqual (new ["sampling" ], {"temperature" :0.7 ,"presence_penalty" :1.5 ,"top_p" :0.95 }) 37self .assertEqual (new ["args" ][- 2 :], ["--vram-reserve-mib" ,"2048" ]) 38self .assertEqual (new ["aliases" ], ["qwen" ,"local" ]) 39for k in ("exe" ,"model_name" ,"port" ,"host" ,"api_key" ,"mcp_servers" ,"cors_origins" ): 40self .assertEqual (new [k ],CFG [k ],k ) 41self .assertEqual (CFG ["sampling" ], {"temperature" :0.7 ,"presence_penalty" :1.5 })# the input is left alone 42 43def test_null_is_the_default_again (self ): 44cfg ,_ = runconfig .apply (CFG , {"vram_reserve_mib" :2048 ,"fit_max_tokens" :True }) 45new ,changed = runconfig .apply (cfg , {"vram_reserve_mib" :None ,"fit_max_tokens" :None , 46"sampling.temperature" :None ,"idle_unload_s" :None }) 47self .assertEqual (changed , ["vram_reserve_mib" ,"fit_max_tokens" ,"sampling.temperature" ]) 48self .assertEqual (new ["args" ],CFG ["args" ]) 49self .assertNotIn ("fit_max_tokens" ,new ) 50self .assertEqual (new ["sampling" ], {"presence_penalty" :1.5 }) 51new ,_ = runconfig .apply ({"sampling" : {"top_k" :20 }}, {"sampling.top_k" :None }) 52self .assertNotIn ("sampling" ,new )# an empty block goes 53 54def test_refused (self ): 55for changes in ({"api_key" :"x" }, {"host" :"0.0.0.0" }, {"mcp_servers" : {}}, {"before_load" :"calc.exe" }, 56 {"args" : []}, {"exe" :"evil.exe" }, {"trusted_origins" : ["*" ]}, {"allowed_hosts" : ["*" ]}, 57 {"sampling.temperature" :- 1 }, {"sampling.top_p" :0 }, {"sampling.top_k" :65 }, 58 {"sampling.min_p" :2 }, {"reasoning_budget_tokens" :1.5 }, {"fit_max_tokens" :"yes" }, 59 {"effort_position" :"middle" }, {"vram_reserve_mib" :- 5 }, {"idle_unload_s" :True }, 60 {"aliases" : [1 ]}, {},None , ["x" ]): 61with self .subTest (changes = changes ),self .assertRaises (ValueError ): 62runconfig .apply (CFG ,changes ) 63with self .assertRaises (ValueError ):# one bad value: nothing is applied 64runconfig .apply (CFG , {"fit_max_tokens" :True ,"sampling.top_k" :0 }) 65with self .assertRaises (ValueError ): 66runconfig .apply ({** CFG ,"vision" : {"gpu" :True }}, {"lazy_load" :True }) 67 68def test_view (self ): 69v = runconfig .view ({** CFG ,"args" :CFG ["args" ]+ ["--vram-reserve-mib" ,"1500" ]},"x/strata-q2_0.json" ) 70self .assertEqual (v ["file" ],"strata-q2_0.json" ) 71got = {k ["key" ]:k for k in v ["keys" ]} 72self .assertEqual (got ["sampling.temperature" ]["value" ],0.7 ) 73self .assertEqual (got ["vram_reserve_mib" ]["value" ],1500 ) 74self .assertIsNone (got ["fit_max_tokens" ]["value" ]) 75self .assertEqual (got ["anthropic_thinking" ]["choices" ], ["model" ,"on_request" ]) 76self .assertNotIn ("api_key" ,got ) 77self .assertNotIn ("mcp_servers" ,got ) 78 79 80class Http (unittest .TestCase ): 81def setUp (self ): 82self .dir = tempfile .TemporaryDirectory () 83self .path = Path (self .dir .name )/ "strata-q2_0.json" 84self .path .write_text (json .dumps (CFG ,indent = 1 ),encoding = "utf-8" ) 85tok = ByteTokenizer () 86self .svc = Service (MockEngine (tok ,"ok" ,max_context = 4096 ),tok ,ChatTemplate (ROOT / "serve/chat_template.jinja" )) 87self .svc .config_path = str (self .path ) 88self .httpd = serve (self .svc ,port = 0 ) 89self .host = f"127.0.0.1: { self . httpd . server_address [ 1 ] } " 90 91def tearDown (self ): 92self .httpd .shutdown () 93self .httpd .server_close () 94self .dir .cleanup () 95 96def call (self ,method ,body = None ,headers = None ): 97h = {"Content-Type" :"application/json" ,** (headers or {})} 98req = urllib .request .Request (f"http:// { self . host } /config" ,method = method ,headers = h , 99data = None if body is None else (body if isinstance (body ,bytes ) 100else json .dumps (body ).encode ())) 101try : 102with urllib .request .urlopen (req ,timeout = 10 )as r : 103return r .status ,json .loads (r .read ()) 104except urllib .error .HTTPError as e : 105with e : 106return e .code ,json .loads (e .read ()) 107 108def saved (self ): 109return json .loads (self .path .read_text (encoding = "utf-8" )) 110 111def test_read_and_write_from_the_page (self ): 112status ,v = self .call ("GET" ) 113self .assertEqual (status ,200 ,v ) 114self .assertEqual ({k ["key" ]:k ["value" ]for k in v ["keys" ]}["sampling.temperature" ],0.7 ) 115with contextlib .redirect_stdout (io .StringIO ()): 116status ,v = self .call ("POST" , {"set" : {"sampling.temperature" :1.0 ,"open_browser" :False }}, 117 {"Origin" :f"http:// { self . host } " }) 118self .assertEqual (status ,200 ,v ) 119self .assertEqual (v ["changed" ], ["sampling.temperature" ,"open_browser" ]) 120cfg = self .saved () 121self .assertEqual (cfg ["sampling" ]["temperature" ],1.0 ) 122self .assertIs (cfg ["open_browser" ],False ) 123for k in ("mcp_servers" ,"cors_origins" ,"host" ,"args" ,"exe" ): 124self .assertEqual (cfg [k ],CFG [k ],k ) 125self .assertEqual (json .loads ((self .path .parent / "strata-q2_0.json.bak" ).read_text (encoding = "utf-8" )),CFG ) 126status ,v = self .call ("POST" , {"set" : {"open_browser" :False }})# no Origin (a script on this PC): allowed 127self .assertEqual ((status ,v ["changed" ]), (200 , [])) 128 129def test_only_from_strata_s_own_page (self ): 130before = self .path .read_bytes () 131status ,_ = self .call ("POST" , {"set" : {"fit_max_tokens" :True }}, {"Origin" :"https://evil.example" }) 132self .assertEqual (status ,403 ) 133status ,_ = self .call ("POST" ,b'{"set": {"fit_max_tokens": true}}' , {"Content-Type" :"text/plain" }) 134self .assertEqual (status ,415 ) 135for body in ({"set" : {"api_key" :"" }}, {"set" : {"mcp_servers" : {"x" : {"command" :"calc" }}}}, 136 {"set" : {"sampling.top_k" :0 }}, {"nothing" :1 },b"not json" ): 137status ,b = self .call ("POST" ,body , {"Origin" :f"http:// { self . host } " }) 138self .assertEqual (status ,400 , (body ,b )) 139self .assertEqual (self .path .read_bytes (),before )# nothing was written 140self .assertFalse ((self .path .parent / "strata-q2_0.json.bak" ).exists ()) 141 142def test_the_api_key (self ): 143self .svc .api_key = "secret" 144self .assertEqual (self .call ("GET" )[0 ],401 ) 145self .assertEqual (self .call ("POST" , {"set" : {"fit_max_tokens" :True }})[0 ],401 ) 146with contextlib .redirect_stdout (io .StringIO ()): 147status ,_ = self .call ("POST" , {"set" : {"fit_max_tokens" :True }}, {"Authorization" :"Bearer secret" }) 148self .assertEqual (status ,200 ) 149self .assertIs (self .saved ()["fit_max_tokens" ],True ) 150 151def test_without_a_run_config (self ): 152self .svc .config_path = None 153self .assertEqual (self .call ("GET" )[0 ],404 ) 154self .assertEqual (self .call ("POST" , {"set" : {"fit_max_tokens" :True }})[0 ],404 ) 155 156def test_the_page_has_the_view (self ): 157web = ROOT / "serve" / "web" 158html ,js = (web / "index.html" ).read_text (encoding = "utf-8" ), (web / "app.js" ).read_text (encoding = "utf-8" ) 159for el in ("cfg-card" ,"cfg-form" ,"cfg-save" ,"cfg-msg" ): 160self .assertIn (f'id=" { el } "' ,html ) 161self .assertIn ('fetch("config", {method: "POST", headers: headers(true)' ,js ) 162 163 164if __name__ == "__main__" : 165unittest .main ()