okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
b0fc432ed
main
1"""Packaged client smoke test without site packages, engine files or model weights.""" 2 3import io 4import hashlib 5import importlib .util 6import json 7import os 8import subprocess 9import sys 10import tempfile 11import threading 12import unittest 13import zipfile 14from contextlib import redirect_stdout 15from http .server import BaseHTTPRequestHandler ,ThreadingHTTPServer 16from pathlib import Path 17from unittest import mock 18 19from strata_cli .cli import main as source_main 20 21 22ROOT = Path (__file__ ).resolve ().parents [2 ] 23BUILDER = ROOT / "packaging/monitor_bundle.py" 24SPEC = importlib .util .spec_from_file_location ("strata_monitor_bundle_builder" ,BUILDER ) 25assert SPEC is not None and SPEC .loader is not None 26BUILDER_MODULE = importlib .util .module_from_spec (SPEC ) 27SPEC .loader .exec_module (BUILDER_MODULE ) 28build = BUILDER_MODULE .build 29install = BUILDER_MODULE .install 30uninstall = BUILDER_MODULE .uninstall 31update = BUILDER_MODULE .update 32rollback = BUILDER_MODULE .rollback 33commit = BUILDER_MODULE .commit 34verify = BUILDER_MODULE .verify 35 36 37class MonitorBundleTests (unittest .TestCase ): 38@staticmethod 39def _candidate (source :Path ,destination :Path )-> Path : 40destination .parent .mkdir () 41destination .write_bytes (source .read_bytes ()) 42with zipfile .ZipFile (destination ,"a" )as archive : 43archive .comment = b"candidate client revision" 44report = json .loads (source .with_name (source .name + ".manifest.json" ).read_text ()) 45report ["bundle" ]= destination .name 46report ["sha256" ]= hashlib .sha256 (destination .read_bytes ()).hexdigest () 47destination .with_name (destination .name + ".manifest.json" ).write_text (json .dumps (report )) 48verify (destination ) 49return destination 50 51def test_crlf_license_checkout_still_verifies (self ): 52"""A Windows checkout (autocrlf) ships LICENSE with CRLF; the bundle must still verify.""" 53real_copy = BUILDER_MODULE .shutil .copyfile 54 55def crlf_license (src ,dst ,* args ,** kwargs ): 56if Path (src ).name != "LICENSE" : 57return real_copy (src ,dst ,* args ,** kwargs ) 58text = Path (src ).read_bytes ().replace (b"\r\n" ,b"\n" ).replace (b"\n" ,b"\r\n" ) 59Path (dst ).write_bytes (text ) 60return dst 61 62with tempfile .TemporaryDirectory ()as directory : 63bundle = Path (directory )/ "monitor.pyz" 64with mock .patch .object (BUILDER_MODULE .shutil ,"copyfile" ,crlf_license ): 65build (bundle ) 66with zipfile .ZipFile (bundle )as archive : 67self .assertIn (b"MIT License\r\n" ,archive .read ("LICENSE" )) 68self .assertEqual (verify (bundle )["schema_version" ],6 ) 69 70def test_update_rollback_and_commit_keep_one_verified_previous_copy (self ): 71with tempfile .TemporaryDirectory ()as directory : 72root = Path (directory ) 73first = root / "first" / "monitor.pyz" 74first .parent .mkdir () 75old = build (first ) 76candidate = self ._candidate (first ,root / "second" / "next-monitor.pyz" ) 77next_sha = verify (candidate )["sha256" ] 78target = root / "optional-monitor" 79install (first ,target ,if_candidate_sha256 = old ["sha256" ]) 80preview_run = subprocess .run ([sys .executable ,str (BUILDER ),"update" ,str (candidate ), 81"--target" ,str (target ),"--plan" ], 82capture_output = True ,text = True ,check = True ) 83preview = json .loads (preview_run .stdout ) 84self .assertEqual ((preview ["current_sha256" ],preview ["candidate_sha256" ]), 85 (old ["sha256" ],next_sha )) 86self .assertTrue (preview ["would_update" ]) 87with self .assertRaisesRegex (ValueError ,"preview again" ): 88update (candidate ,target ,if_current_sha256 = old ["sha256" ], 89if_candidate_sha256 = "0" * 64 ) 90self .assertFalse ((root / "optional-monitor.previous" ).exists ()) 91changed = subprocess .run ([sys .executable ,str (BUILDER ),"update" ,str (candidate ), 92"--target" ,str (target ),"--if-current-sha256" ,old ["sha256" ], 93"--if-candidate-sha256" ,next_sha ], 94capture_output = True ,text = True ,check = True ) 95result = json .loads (changed .stdout ) 96self .assertTrue (result ["updated" ]) 97previous = root / "optional-monitor.previous" 98self .assertEqual (verify (target / "next-monitor.pyz" )["sha256" ],next_sha ) 99self .assertEqual (verify (previous / "monitor.pyz" )["sha256" ],old ["sha256" ]) 100with self .assertRaisesRegex (FileExistsError ,"previous" ): 101update (candidate ,target ,plan = True ) 102preview_run = subprocess .run ([sys .executable ,str (BUILDER ),"rollback" ,"--target" , 103str (target ),"--plan" ],capture_output = True ,text = True ,check = True ) 104preview = json .loads (preview_run .stdout ) 105self .assertTrue (preview ["would_rollback" ]) 106with self .assertRaisesRegex (ValueError ,"preview again" ): 107rollback (target ,if_active_sha256 = old ["sha256" ],if_rollback_sha256 = old ["sha256" ]) 108original = os .rename 109calls = 0 110 111def fail_last_exchange (source ,destination ): 112nonlocal calls 113calls += 1 114if calls == 3 : 115raise OSError ("final exchange failed" ) 116return original (source ,destination ) 117 118with mock .patch .object (BUILDER_MODULE .os ,"rename" ,side_effect = fail_last_exchange ): 119with self .assertRaisesRegex (OSError ,"final exchange failed" ): 120rollback (target ,if_active_sha256 = next_sha ,if_rollback_sha256 = old ["sha256" ]) 121self .assertEqual (verify (target / "next-monitor.pyz" )["sha256" ],next_sha ) 122self .assertEqual (verify (previous / "monitor.pyz" )["sha256" ],old ["sha256" ]) 123self .assertFalse (list (root .glob (".strata-monitor-swap-*" ))) 124restored = subprocess .run ([sys .executable ,str (BUILDER ),"rollback" ,"--target" ,str (target ), 125"--if-active-sha256" ,next_sha , 126"--if-rollback-sha256" ,old ["sha256" ]], 127capture_output = True ,text = True ,check = True ) 128result = json .loads (restored .stdout ) 129self .assertTrue (result ["rolled_back" ]) 130self .assertEqual (verify (target / "monitor.pyz" )["sha256" ],old ["sha256" ]) 131self .assertEqual (verify (previous / "next-monitor.pyz" )["sha256" ],next_sha ) 132with self .assertRaisesRegex (ValueError ,"commit or rollback" ): 133uninstall (target ) 134planned = commit (target ,plan = True ) 135self .assertTrue (planned ["would_commit" ]) 136accepted = subprocess .run ([sys .executable ,str (BUILDER ),"commit" ,"--target" ,str (target ), 137"--if-active-sha256" ,old ["sha256" ], 138"--if-previous-sha256" ,next_sha ], 139capture_output = True ,text = True ,check = True ) 140self .assertTrue (json .loads (accepted .stdout )["committed" ]) 141self .assertFalse (previous .exists ()) 142self .assertTrue (uninstall (target ,if_active_sha256 = old ["sha256" ])["removed" ]) 143 144def test_update_activation_failure_restores_installed_client (self ): 145with tempfile .TemporaryDirectory ()as directory : 146root = Path (directory ) 147first = root / "first" / "monitor.pyz" 148first .parent .mkdir () 149old = build (first ) 150candidate = self ._candidate (first ,root / "second" / "monitor.pyz" ) 151next_sha = verify (candidate )["sha256" ] 152target = root / "optional-monitor" 153install (first ,target ,if_candidate_sha256 = old ["sha256" ]) 154original = os .rename 155calls = 0 156 157def fail_activation (source ,destination ): 158nonlocal calls 159calls += 1 160if calls == 2 : 161raise OSError ("activation failed" ) 162return original (source ,destination ) 163 164with mock .patch .object (BUILDER_MODULE .os ,"rename" ,side_effect = fail_activation ): 165with self .assertRaisesRegex (OSError ,"activation failed" ): 166update (candidate ,target ,if_current_sha256 = old ["sha256" ], 167if_candidate_sha256 = next_sha ) 168self .assertEqual (verify (target / "monitor.pyz" )["sha256" ],old ["sha256" ]) 169self .assertFalse ((root / "optional-monitor.previous" ).exists ()) 170self .assertFalse (list (root .glob (".strata-monitor-install-*" ))) 171 172original_stage = BUILDER_MODULE ._stage_copy 173 174def change_active_during_copy (bundle ,report ,destination ): 175stage = original_stage (bundle ,report ,destination ) 176active_bundle = destination / "monitor.pyz" 177with zipfile .ZipFile (active_bundle ,"a" )as archive : 178archive .comment = b"external owner edit" 179manifest = active_bundle .with_name (active_bundle .name + ".manifest.json" ) 180current = json .loads (manifest .read_text ()) 181current ["sha256" ]= hashlib .sha256 (active_bundle .read_bytes ()).hexdigest () 182manifest .write_text (json .dumps (current )) 183return stage 184 185with mock .patch .object (BUILDER_MODULE ,"_stage_copy" ,side_effect = change_active_during_copy ): 186with self .assertRaisesRegex (ValueError ,"changed during copy" ): 187update (candidate ,target ,if_current_sha256 = old ["sha256" ], 188if_candidate_sha256 = next_sha ) 189self .assertNotEqual (verify (target / "monitor.pyz" )["sha256" ],old ["sha256" ]) 190self .assertFalse ((root / "optional-monitor.previous" ).exists ()) 191self .assertFalse (list (root .glob (".strata-monitor-install-*" ))) 192 193def test_offline_install_plan_and_remove_touch_only_monitor_files (self ): 194with tempfile .TemporaryDirectory ()as directory : 195root = Path (directory ) 196bundle = root / "portable-client.pyz" 197built = build (bundle ) 198target = root / "optional-monitor" 199preview = subprocess .run ([sys .executable ,str (BUILDER ),"install" ,str (bundle ), 200"--target" ,str (target ),"--plan" ], 201capture_output = True ,text = True ,check = True ) 202planned = json .loads (preview .stdout ) 203self .assertTrue (planned ["would_install" ]) 204self .assertFalse (target .exists ()) 205with self .assertRaisesRegex (ValueError ,"preview again" ): 206install (bundle ,target ) 207with self .assertRaisesRegex (ValueError ,"preview again" ): 208install (bundle ,target ,if_candidate_sha256 = "0" * 64 ) 209self .assertFalse (target .exists ()) 210installed_run = subprocess .run ([sys .executable ,str (BUILDER ),"install" ,str (bundle ), 211"--target" ,str (target ), 212"--if-candidate-sha256" ,planned ["sha256" ]], 213capture_output = True ,text = True ,check = True ) 214installed = json .loads (installed_run .stdout ) 215self .assertTrue (installed ["installed" ]) 216self .assertEqual (verify (target / bundle .name )["sha256" ],built ["sha256" ]) 217self .assertEqual ({p .name for p in target .iterdir ()}, 218 {bundle .name ,bundle .name + ".manifest.json" }) 219if os .name == "posix" : 220self .assertEqual (target .stat ().st_mode & 0o077 ,0 ) 221self .assertEqual ((target / bundle .name ).stat ().st_mode & 0o077 ,0 ) 222portable = subprocess .run ([sys .executable ,"-I" ,str (target / bundle .name ),"logs" ,"--help" ], 223cwd = directory ,capture_output = True ,text = True ,check = True , 224encoding = "utf-8" ,errors = "replace" )# (the help text has non-ASCII characters; Windows would read it as cp1252) 225self .assertIn ("--follow" ,portable .stdout ) 226extra = target / "user-notes.txt" 227extra .write_text ("keep me" ) 228with self .assertRaisesRegex (ValueError ,"unexpected" ): 229uninstall (target ) 230self .assertTrue (extra .exists ()) 231extra .unlink () 232preview_remove = subprocess .run ([sys .executable ,str (BUILDER ),"uninstall" , 233"--target" ,str (target ),"--plan" ], 234capture_output = True ,text = True ,check = True ) 235self .assertTrue (json .loads (preview_remove .stdout )["would_remove" ]) 236self .assertTrue (target .exists ()) 237with self .assertRaisesRegex (ValueError ,"preview again" ): 238uninstall (target ) 239with self .assertRaisesRegex (ValueError ,"preview again" ): 240uninstall (target ,if_active_sha256 = "0" * 64 ) 241self .assertTrue (target .exists ()) 242removal = subprocess .run ([sys .executable ,str (BUILDER ),"uninstall" ,"--target" , 243str (target ),"--if-active-sha256" , 244json .loads (preview_remove .stdout )["sha256" ]], 245capture_output = True ,text = True ,check = True ) 246self .assertTrue (json .loads (removal .stdout )["removed" ]) 247self .assertFalse (target .exists ()) 248 249def test_failed_copy_leaves_no_partial_install (self ): 250with tempfile .TemporaryDirectory ()as directory : 251root = Path (directory ) 252bundle = root / "monitor.pyz" 253built = build (bundle ) 254target = root / "optional-monitor" 255with mock .patch .object (BUILDER_MODULE .shutil ,"copyfile" ,side_effect = OSError ("disk full" )): 256with self .assertRaisesRegex (OSError ,"disk full" ): 257install (bundle ,target ,if_candidate_sha256 = built ["sha256" ]) 258self .assertFalse (target .exists ()) 259self .assertFalse (list (root .glob (".strata-monitor-install-*" ))) 260 261def test_bundle_verification_rejects_large_or_linked_input (self ): 262with tempfile .TemporaryDirectory ()as directory : 263root = Path (directory ) 264bundle = root / "monitor.pyz" 265build (bundle ) 266linked = root / "linked.pyz" 267linked .symlink_to (bundle ) 268with self .assertRaisesRegex (ValueError ,"bounded regular" ): 269verify (linked ) 270with bundle .open ("ab" )as stream : 271stream .write (b"x" * (1024 * 1024 )) 272with self .assertRaisesRegex (ValueError ,"bounded regular" ): 273verify (bundle ) 274bundle = root / "unsigned.pyz" 275build (bundle ) 276manifest = bundle .with_name (bundle .name + ".manifest.json" ) 277forged = json .loads (manifest .read_text ()) 278forged ["publisher_signature" ]= "pretend-signed" 279manifest .write_text (json .dumps (forged )) 280with self .assertRaisesRegex (ValueError ,"manifest or SHA-256" ): 281verify (bundle ) 282manifest .write_text ("[]" ) 283with self .assertRaisesRegex (ValueError ,"manifest or SHA-256" ): 284verify (bundle ) 285 286def test_bundle_carries_every_module_its_entry_point_imports (self ): 287"""The import closure of strata_cli.monitor_commands (lazy imports included) minus the launch package must be in the bundle.""" 288import ast 289needed ,todo = set (), ["strata_cli/monitor_commands.py" ] 290while todo : 291name = todo .pop () 292if name in needed : 293continue 294needed .add (name ) 295for node in ast .walk (ast .parse ((ROOT / name ).read_text (encoding = "utf-8" ))): 296if isinstance (node ,ast .ImportFrom )and node .module and node .module .split ("." )[0 ]== "strata_cli" : 297names = [node .module ]+ [node .module + "." + a .name for a in node .names ] 298elif isinstance (node ,ast .Import ): 299names = [a .name for a in node .names ] 300else : 301continue 302for module in names : 303path = module .replace ("." ,"/" )+ ".py" 304if module .startswith ("strata_cli" )and (ROOT / path ).is_file ()and "/launch/" not in path : 305todo .append (path ) 306self .assertLessEqual (needed ,set (BUILDER_MODULE .SOURCES )) 307 308def test_plain_monitor_runs_when_the_launch_package_is_not_bundled (self ): 309"""The pyz has no strata_cli.launch: interactive `monitor` must fall back to the plain Monitor, not fail.""" 310from strata_cli import monitor as monitor_module 311from strata_cli import monitor_commands 312ran = [] 313blocked = {"strata_cli.launch.monitor_ext" :None }# None in sys.modules makes the import raise ImportError 314with mock .patch .dict (sys .modules ,blocked ),mock .patch .object (monitor_module .MonitorApp ,"run" ,lambda self :ran .append (self .endpoint .base_url )),mock .patch .object (sys .stdout ,"isatty" ,return_value = True ): 315code = monitor_commands .main (["monitor" ,"--url" ,"http://127.0.0.1:9" ]) 316self .assertEqual ((code ,ran ), (0 , ["http://127.0.0.1:9" ])) 317 318def test_versioned_manifest_keeps_legacy_update_and_rollback_available (self ): 319with tempfile .TemporaryDirectory ()as directory : 320root = Path (directory ) 321current = root / "monitor.pyz" 322modern = root / "next-monitor.pyz" 323previous = root / "previous-monitor.pyz" 324build (modern ) 325old_visual = root / "visual-monitor.pyz" 326for old_bundle ,version in ((current ,1 ), (previous ,2 ), (old_visual ,3 )): 327with zipfile .ZipFile (modern )as source ,zipfile .ZipFile (old_bundle ,"w" ,zipfile .ZIP_DEFLATED )as legacy : 328for item in source .infolist (): 329if item .filename not in ("strata_cli/detail_dashboard.py" ,"strata_cli/nav.py" , 330"strata_cli/consoleinfo.py" ,"strata_cli/overview.py" )and \ 331 (version >= 3 or item .filename != "strata_cli/dashboard.py" )and \ 332 (version != 1 or item .filename != "LICENSE" ): 333legacy .writestr (item ,source .read (item .filename )) 334report = json .loads ((root / "next-monitor.pyz.manifest.json" ).read_text ()) 335report ["schema_version" ]= version 336report ["bundle" ]= old_bundle .name 337report ["sha256" ]= hashlib .sha256 (old_bundle .read_bytes ()).hexdigest () 338del report ["files" ]["strata_cli/detail_dashboard.py" ] 339del report ["files" ]["strata_cli/nav.py" ] 340del report ["files" ]["strata_cli/consoleinfo.py" ] 341del report ["files" ]["strata_cli/overview.py" ] 342if version < 3 : 343del report ["files" ]["strata_cli/dashboard.py" ] 344if version == 1 : 345del report ["files" ]["LICENSE" ] 346for field in ("compatibility" ,"license" ,"license_file" ): 347del report [field ] 348old_bundle .with_name (old_bundle .name + ".manifest.json" ).write_text (json .dumps (report )) 349self .assertEqual (verify (current )["schema_version" ],1 ) 350self .assertEqual (verify (previous )["schema_version" ],2 ) 351self .assertEqual (verify (old_visual )["schema_version" ],3 ) 352self .assertEqual (verify (modern )["schema_version" ],6 ) 353with zipfile .ZipFile (modern )as archive : 354self .assertIn (b"MIT License" ,archive .read ("LICENSE" )) 355self .assertIn (b"render_dashboard" ,archive .read ("strata_cli/dashboard.py" )) 356self .assertIn (b"render_detail_dashboard" ,archive .read ("strata_cli/detail_dashboard.py" )) 357target = root / "optional-monitor" 358install (current ,target ,if_candidate_sha256 = verify (current )["sha256" ]) 359preview = update (modern ,target ,plan = True ) 360self .assertTrue (preview ["would_update" ]) 361self .assertTrue (update (modern ,target ,if_current_sha256 = preview ["current_sha256" ], 362if_candidate_sha256 = preview ["candidate_sha256" ])["updated" ]) 363self .assertEqual (verify (target / modern .name )["schema_version" ],6 ) 364self .assertEqual (verify (root / "optional-monitor.previous" / current .name )["schema_version" ],1 ) 365planned = rollback (target ,plan = True ) 366self .assertTrue (rollback (target ,if_active_sha256 = planned ["active_sha256" ], 367if_rollback_sha256 = planned ["rollback_sha256" ])["rolled_back" ]) 368self .assertEqual (verify (target / current .name )["schema_version" ],1 ) 369second_target = root / "optional-monitor-from-v2" 370install (previous ,second_target ,if_candidate_sha256 = verify (previous )["sha256" ]) 371preview = update (modern ,second_target ,plan = True ) 372self .assertTrue (update (modern ,second_target , 373if_current_sha256 = preview ["current_sha256" ], 374if_candidate_sha256 = preview ["candidate_sha256" ])["updated" ]) 375self .assertEqual (verify (second_target / modern .name )["schema_version" ],6 ) 376planned = rollback (second_target ,plan = True ) 377self .assertTrue (rollback (second_target ,if_active_sha256 = planned ["active_sha256" ], 378if_rollback_sha256 = planned ["rollback_sha256" ])["rolled_back" ]) 379self .assertEqual (verify (second_target / previous .name )["schema_version" ],2 ) 380third_target = root / "optional-monitor-from-v3" 381install (old_visual ,third_target ,if_candidate_sha256 = verify (old_visual )["sha256" ]) 382preview = update (modern ,third_target ,plan = True ) 383self .assertTrue (update (modern ,third_target , 384if_current_sha256 = preview ["current_sha256" ], 385if_candidate_sha256 = preview ["candidate_sha256" ])["updated" ]) 386planned = rollback (third_target ,plan = True ) 387self .assertTrue (rollback (third_target ,if_active_sha256 = planned ["active_sha256" ], 388if_rollback_sha256 = planned ["rollback_sha256" ])["rolled_back" ]) 389self .assertEqual (verify (third_target / old_visual .name )["schema_version" ],3 ) 390 391def test_manifest_compatibility_and_license_notice_are_checked (self ): 392with tempfile .TemporaryDirectory ()as directory : 393bundle = Path (directory )/ "monitor.pyz" 394built = build (bundle ) 395self .assertEqual (built ["compatibility" ], {"python_min" :"3.10" ,"telemetry_schema" : [1 ]}) 396self .assertEqual (built ["license_file" ],"LICENSE" ) 397manifest = bundle .with_name (bundle .name + ".manifest.json" ) 398edited = json .loads (manifest .read_text ()) 399edited ["compatibility" ]["telemetry_schema" ]= [2 ] 400manifest .write_text (json .dumps (edited )) 401with self .assertRaisesRegex (ValueError ,"compatibility or license" ): 402verify (bundle ) 403edited ["schema_version" ]= True 404manifest .write_text (json .dumps (edited )) 405with self .assertRaisesRegex (ValueError ,"manifest or SHA-256" ): 406verify (bundle ) 407 408def test_thin_bundle_and_source_share_one_shot_contract (self ): 409snapshot = {"schema_version" :1 ,"source" :"test-server" ,"sampled_at" :1_790_000_000 , 410"instance" : {"id" :"test-instance" ,"state" :"ready" }, 411"model" : {"id" :"fixture-model" ,"loaded" :True }, 412"work" : {"active" :2 ,"queued" :1 ,"slots_effective" :4 , 413"requests" : [{"id" :"r1" ,"state" :"reading" ,"slot" :0 , 414"prompt_tokens" :200 ,"prompt_read" :50 }]}} 415paths = [] 416 417class Handler (BaseHTTPRequestHandler ): 418def do_GET (self ): 419paths .append (self .path ) 420body = json .dumps (snapshot ).encode () 421self .send_response (200 ) 422self .send_header ("Content-Type" ,"application/json" ) 423self .send_header ("Content-Length" ,str (len (body ))) 424self .end_headers () 425self .wfile .write (body ) 426 427def log_message (self ,* _args ): 428pass 429 430server = ThreadingHTTPServer (("127.0.0.1" ,0 ),Handler ) 431thread = threading .Thread (target = server .serve_forever ,daemon = True ) 432thread .start () 433try : 434with tempfile .TemporaryDirectory ()as directory : 435bundle = Path (directory )/ "strata-monitor.pyz" 436subprocess .run ([sys .executable ,str (BUILDER ),"build" ,str (bundle )],check = True , 437capture_output = True ,text = True ) 438subprocess .run ([sys .executable ,str (BUILDER ),"verify" ,str (bundle )],check = True , 439capture_output = True ,text = True ) 440self .assertLess (bundle .stat ().st_size ,96 * 1024 ) 441with zipfile .ZipFile (bundle )as archive : 442self .assertIn (b"MIT License" ,archive .read ("LICENSE" )) 443self .assertIn ("strata_cli/dashboard.py" ,archive .namelist ()) 444if importlib .util .find_spec ("textual" )is not None : 445import_check = subprocess .run ( 446 [sys .executable ,"-I" ,"-c" , 447"import sys; sys.path.insert(0, " + repr (str (bundle ))+ "); " 448"from strata_cli.monitor import MonitorApp; print(MonitorApp.__name__)" ], 449cwd = directory ,capture_output = True ,text = True ,check = True ) 450self .assertEqual (import_check .stdout .strip (),"MonitorApp" ) 451url = f"http://127.0.0.1: { server . server_port } " 452source_output = io .StringIO () 453with redirect_stdout (source_output ): 454self .assertEqual (source_main (["monitor" ,"--once" ,"--json" ,"--url" ,url ]),0 ) 455clean_env = {k :v for k ,v in os .environ .items ()if k not in ("PYTHONPATH" ,"PYTHONHOME" )} 456clean_env ["STRATA_CONNECTION_DIR" ]= str (Path (directory )/ "connections" ) 457portable = subprocess .run ([sys .executable ,"-S" ,str (bundle ),"monitor" ,"--once" ,"--json" , 458"--url" ,url ],cwd = directory ,env = clean_env ,check = True , 459capture_output = True ,text = True ) 460self .assertEqual (json .loads (portable .stdout ),json .loads (source_output .getvalue ())) 461bare_source = subprocess .run ([sys .executable ,"-S" ,str (ROOT / "strata.py" ),"monitor" , 462"--once" ,"--json" ,"--url" ,url ],cwd = directory ,env = clean_env , 463check = True ,capture_output = True ,text = True ) 464self .assertEqual (json .loads (bare_source .stdout ),json .loads (portable .stdout )) 465status = subprocess .run ([sys .executable ,"-S" ,str (bundle ),"status" ,"--json" ,"--url" ,url ], 466cwd = directory ,env = clean_env ,check = True ,capture_output = True ,text = True ) 467self .assertEqual (json .loads (status .stdout )["snapshot" ]["work" ]["active" ],2 ) 468saved = subprocess .run ([sys .executable ,"-S" ,str (bundle ),"connection" ,"list" ,"--json" ], 469cwd = directory ,env = clean_env ,check = True ,capture_output = True ,text = True ) 470self .assertEqual (json .loads (saved .stdout )["connections" ], []) 471quiet_saved = subprocess .run ([sys .executable ,"-S" ,str (bundle ),"connection" ,"list" ,"--quiet" ], 472cwd = directory ,env = clean_env ,check = True , 473capture_output = True ,text = True ) 474self .assertEqual ((quiet_saved .stdout ,quiet_saved .stderr ), ("" ,"" )) 475quiet_json = subprocess .run ([sys .executable ,"-S" ,str (bundle ),"connection" ,"list" , 476"--quiet" ,"--json" ],cwd = directory ,env = clean_env , 477check = True ,capture_output = True ,text = True ) 478self .assertEqual (json .loads (quiet_json .stdout )["connections" ], []) 479self .assertEqual (paths , ["/v1/telemetry" ]* 4 ) 480data = bytearray (bundle .read_bytes ()) 481data [- 1 ]^= 1 482bundle .write_bytes (data ) 483broken = subprocess .run ([sys .executable ,str (BUILDER ),"verify" ,str (bundle )], 484capture_output = True ,text = True ) 485self .assertEqual (broken .returncode ,1 ) 486self .assertIn ("SHA-256 mismatch" ,broken .stderr ) 487finally : 488server .shutdown () 489server .server_close () 490thread .join (timeout = 2 )