okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
aff3a132f
main
1"""The quiet line that says a newer engine is available, and the once-a-day check behind it (owner, 11-01). 2 3* the line comes from the last check's cached answer (a local file): one sentence, one next step, no network; 4* it is in the launch start screen and the launch monitor (and `strata update --check`), nowhere else; 5* the daily check is made by the launch monitor only, in a thread of its own, once a day, with a short timeout, and says NOTHING when it cannot reach 6the feed: no internet, blocked DNS, a proxy that refuses, a captive portal that answers junk, a connection that never answers. The attempt is 7written before the network is touched, so a failure is not retried until tomorrow. Offline, the launch, the monitor and the line behave exactly as 8they do with a working network that has nothing new. 9""" 10from __future__import annotations 11 12import asyncio 13import contextlib 14import datetime as dt 15import io 16import json 17import logging 18import os 19import socket 20import sys 21import threading 22import time 23import unittest 24from http .server import BaseHTTPRequestHandler ,ThreadingHTTPServer 25from pathlib import Path 26from unittest import mock 27 28sys .path .insert (0 ,str (Path (__file__ ).resolve ().parents [2 ])) 29from strata_cli .launch import app as launch_app # noqa: E402 30from strata_cli .launch .monitor_ext import LaunchMonitor # noqa: E402 31from strata_control import engine_component as ec ,engine_update ,updater # noqa: E402 32from tests .terminal import update_fixture as fx # noqa: E402 33from tests .terminal .launch_support import text_of # noqa: E402 34from tests .terminal .test_launch_monitor import INFO ,flat # noqa: E402 35from tests .terminal .test_launch_tui import Base as TuiBase ,make_ctx # noqa: E402 36from tests .terminal .test_overview import Source ,metrics # noqa: E402 37from tests .terminal .test_updater import UpdaterCase # noqa: E402 38 39 40class Cached (UpdaterCase ): 41"""The line is built from the cached check only.""" 42 43def remember (self ,** offers ): 44state = self .components / ".updates" / "state.json" 45state .parent .mkdir (parents = True ,exist_ok = True ) 46last = {"at" :dt .datetime .now (dt .timezone .utc ).isoformat (),"engine" :None ,"app" :None , 47"control" :ec .runtime_version (),"engine_installed" :ec .newest_installed_version (self .components ),** offers } 48state .write_text (json .dumps ({"schema_version" :1 ,"last_check" :last })) 49 50def test_nothing_cached_nothing_shown (self ): 51self .install_current ("0.1.45" ) 52self .assertIsNone (engine_update .notice (self .components )) 53self .assertIsNone (engine_update .notice_line (self .components )) 54self .assertIsNone (engine_update .monitor_note (self .components )) 55 56def test_a_newer_engine_is_one_sentence_and_one_next_step (self ): 57self .install_current ("0.1.45" ) 58self .remember (engine = "0.1.56" ) 59line = engine_update .notice_line (self .components ) 60self .assertEqual (line ,"A new engine 0.1.56 (you have 0.1.45) is available. Update with `strata update`." ) 61self .assertEqual (engine_update .monitor_note (self .components ),"New engine 0.1.56 is available. Press u to update." ) 62self .assertNotIn ("\n" ,line ) 63 64def test_a_cached_engine_that_is_not_newer_is_never_shown (self ): 65self .install_current ("0.1.56" ) 66self .remember (engine = "0.1.56" ,engine_installed = "0.1.56" ) 67self .assertIsNone (engine_update .notice (self .components )) 68 69def test_the_line_is_dropped_when_the_engine_changed_since_the_check (self ): 70self .install_current ("0.1.45" ) 71self .remember (engine = "0.1.56" ,engine_installed = "0.1.44" ) 72self .assertIsNone (engine_update .notice (self .components )) 73 74def test_reading_the_line_touches_no_network (self ): 75self .install_current ("0.1.45" ) 76self .remember (engine = "0.1.56" ) 77with mock .patch ("urllib.request.urlopen" ,side_effect = AssertionError ("network" )),mock .patch ("socket.create_connection" ,side_effect = AssertionError ("network" )): 78self .assertIsNotNone (engine_update .notice_line (self .components )) 79 80def test_a_check_writes_what_the_line_reads (self ): 81self .install_current ("0.1.45" ) 82self .publish (("0.1.56" ,fx .GOOD_ENGINE )) 83updater .check (self .ctx ()) 84self .assertIn ("0.1.56" ,engine_update .notice_line (self .components )) 85self .assertEqual (self .archive_requests (), [],"a check downloads no engine" ) 86 87 88class DailyCheck (UpdaterCase ): 89def setUp (self ): 90super ().setUp () 91self .install_current ("0.1.45" ) 92self .calls = 0 93 94def check (self ): 95self .calls += 1 96 97def attempt_file (self ): 98return self .components / ".updates" / engine_update .ATTEMPT_FILE 99 100def test_it_runs_once_and_not_again_the_same_day (self ): 101self .assertTrue (engine_update .refresh_cache (self .check ,self .components )) 102self .assertFalse (engine_update .refresh_cache (self .check ,self .components )) 103self .assertEqual (self .calls ,1 ) 104 105def test_a_failed_check_is_not_retried_until_tomorrow (self ): 106def broken (): 107self .calls += 1 108raise OSError ("no route to host" ) 109self .assertFalse (engine_update .refresh_cache (broken ,self .components )) 110self .assertFalse (engine_update .refresh_cache (broken ,self .components )) 111self .assertEqual (self .calls ,1 ,"the attempt was written before the network was touched" ) 112old = (dt .datetime .now (dt .timezone .utc )- dt .timedelta (hours = 25 )).isoformat () 113self .attempt_file ().write_text (json .dumps ({"at" :old })) 114self .assertTrue (engine_update .refresh_cache (self .check ,self .components )) 115self .assertEqual (self .calls ,2 ) 116 117def test_a_check_somebody_made_today_counts (self ): 118state = self .components / ".updates" / "state.json" 119state .parent .mkdir (parents = True ,exist_ok = True ) 120state .write_text (json .dumps ({"last_check" : {"at" :dt .datetime .now (dt .timezone .utc ).isoformat ()}})) 121self .assertFalse (engine_update .refresh_cache (self .check ,self .components )) 122self .assertEqual (self .calls ,0 ) 123 124def test_it_can_be_switched_off (self ): 125for value in ("0" ,"off" ,"never" ): 126with mock .patch .dict (os .environ , {engine_update .CHECK_ENV :value }): 127self .assertFalse (engine_update .refresh_cache (self .check ,self .components )) 128self .assertEqual (self .calls ,0 ) 129self .assertFalse (self .attempt_file ().exists ()) 130 131def test_it_never_runs_in_a_process_that_forbids_acquiring (self ): 132with mock .patch .dict (os .environ , {"STRATA_NO_ACQUIRE" :"1" }): 133self .assertIsNone (engine_update .start_daily_check (root = self .components )) 134 135def test_an_attempt_that_cannot_be_remembered_is_not_made (self ): 136with mock .patch .object (Path ,"write_text" ,side_effect = OSError ("read-only" )): 137self .assertFalse (engine_update .refresh_cache (self .check ,self .components )) 138self .assertEqual (self .calls ,0 ) 139 140 141class Portal (BaseHTTPRequestHandler ): 142"""A captive portal: 200 and a web page for every address.""" 143 144def do_GET (self ): 145body = b"<html><body>Please sign in to the hotel WiFi</body></html>" 146self .send_response (200 ) 147self .send_header ("Content-Type" ,"text/html" ) 148self .send_header ("Content-Length" ,str (len (body ))) 149self .end_headers () 150self .wfile .write (body ) 151 152def log_message (self ,* a ): 153pass 154 155 156class Offline (UpdaterCase ): 157"""The real daily check against a network that is not there. Whatever is wrong, the thread ends without a word and the person sees nothing.""" 158 159def setUp (self ): 160super ().setUp () 161self .install_current ("0.1.45" ) 162 163def run_check (self ,feed ,join = 60.0 ,env = None ): 164out ,err = io .StringIO (),io .StringIO () 165before = time .monotonic () 166from tests .terminal import net_dead 167with mock .patch .dict (os .environ ,env or {}),contextlib .redirect_stdout (out ),contextlib .redirect_stderr (err ), \ 168self .assertNoLogs (level = logging .INFO ),net_dead .no_name_resolution ():# (no real name service: the offline PC is faked) 169thread = engine_update .start_daily_check (root = self .components ,feed = feed ) 170started_in = time .monotonic ()- before 171thread .join (join ) 172self .assertFalse (thread .is_alive (),"the check gave up by itself" ) 173self .assertLess (started_in ,1.0 ,"starting the check does not wait for the network" ) 174self .assertEqual ((out .getvalue (),err .getvalue ()), ("" ,"" ),"nothing is printed" ) 175self .assertIsNone (engine_update .notice (self .components )) 176self .assertTrue ((self .components / ".updates" / engine_update .ATTEMPT_FILE ).is_file (),"tomorrow, not in a minute" ) 177self .assertEqual (self .archive_requests (), []) 178 179def test_nothing_listens (self ): 180self .run_check ("http://127.0.0.1:9/strata-feed.json" ) 181 182def test_dns_is_blocked (self ): 183self .run_check ("https://strata-feed.invalid/strata-feed.json" ) 184 185def test_a_proxy_that_refuses (self ): 186self .run_check ("https://example.invalid/strata-feed.json" , 187env = {"HTTPS_PROXY" :"http://127.0.0.1:9" ,"https_proxy" :"http://127.0.0.1:9" ,"HTTP_PROXY" :"http://127.0.0.1:9" }) 188 189def test_a_captive_portal_that_answers_junk (self ): 190server = ThreadingHTTPServer (("127.0.0.1" ,0 ),Portal ) 191threading .Thread (target = server .serve_forever ,daemon = True ).start () 192self .addCleanup (server .server_close ) 193self .addCleanup (server .shutdown ) 194self .run_check (f"http://127.0.0.1: { server . server_address [ 1 ] } /strata-feed.json" ) 195 196def test_a_connection_that_never_answers (self ): 197hang = socket .socket () 198hang .bind (("127.0.0.1" ,0 )) 199hang .listen (5 ) 200self .addCleanup (hang .close ) 201started = time .monotonic () 202self .run_check (f"http://127.0.0.1: { hang . getsockname ()[ 1 ] } /strata-feed.json" ,join = 60.0 ) 203self .assertLess (time .monotonic ()- started ,30 ,"the short timeout ended it" ) 204 205def test_a_second_try_the_same_day_makes_no_request_at_all (self ): 206server = ThreadingHTTPServer (("127.0.0.1" ,0 ),Portal ) 207threading .Thread (target = server .serve_forever ,daemon = True ).start () 208self .addCleanup (server .server_close ) 209self .addCleanup (server .shutdown ) 210seen = [] 211original = Portal .do_GET 212Portal .do_GET = lambda handler : (seen .append (handler .path ),original (handler ))[1 ] 213self .addCleanup (setattr ,Portal ,"do_GET" ,original ) 214feed = f"http://127.0.0.1: { server . server_address [ 1 ] } /strata-feed.json" 215self .run_check (feed ) 216first = len (seen ) 217self .assertGreater (first ,0 ) 218engine_update .start_daily_check (root = self .components ,feed = feed ).join (10 ) 219self .assertEqual (len (seen ),first ) 220 221 222class OnTheScreens (TuiBase ): 223def note (self ,text = "A new engine 0.1.56 (you have 0.1.55) is available. Update with `strata update`." ): 224patch = mock .patch .object (engine_update ,"notice_line" ,return_value = text ) 225patch .start () 226self .addCleanup (patch .stop ) 227 228def test_the_start_screen_shows_the_line_once (self ): 229self .note () 230 231async def case (app ,pilot ,ctx ): 232t = " " .join (text_of (app ).split ()) 233self .assertEqual (t .count ("A new engine 0.1.56" ),1 ) 234self .assertIn ("Update with `strata update`" ,t ) 235self .run_app (case ) 236 237def test_the_start_screen_without_a_newer_engine_is_as_before (self ): 238async def case (app ,pilot ,ctx ): 239self .assertNotIn ("new engine" ,text_of (app ).lower ()) 240self .run_app (case ) 241 242 243class Monitor (unittest .TestCase ): 244def run_app (self ,coro ,info = None ,note = None ): 245async def go (): 246app = LaunchMonitor (Source (metrics ("idle" )),None ,info = info or dict (INFO ),interval = 30 ) 247async with app .run_test (size = (120 ,40 ))as pilot : 248await pilot .pause (0.5 ) 249app .quiet_note = note 250app ._paint () 251await pilot .pause (0.2 ) 252return await coro (app ,pilot ) 253return asyncio .run (go ()) 254 255def test_the_line_and_the_key (self ): 256async def case (app ,pilot ): 257t = flat (app ) 258self .assertIn ("New engine 0.1.56 is available. Press u to update." ,t ) 259self .assertEqual (t .count ("is available" ),1 ) 260self .run_app (case ,note = "New engine 0.1.56 is available. Press u to update." ) 261 262def test_no_line_when_nothing_is_new (self ): 263async def case (app ,pilot ): 264self .assertNotIn ("Press u" ,flat (app )) 265self .run_app (case ) 266 267def test_the_daily_check_is_started_by_the_launch_monitor_only (self ): 268with mock .patch .object (engine_update ,"start_daily_check" )as start : 269self .run_app (lambda app ,pilot :asyncio .sleep (0 )) 270start .assert_not_called ()# (plain monitors, tests, `strata monitor --url`) 271self .run_app (lambda app ,pilot :asyncio .sleep (0 ),info = {** INFO ,"daily_check" :True }) 272start .assert_called_once () 273 274def test_run_monitor_asks_for_the_check (self ): 275seen = {} 276 277class Stub : 278def __init__ (self ,endpoint ,snapshot ,info ,** kw ): 279seen .update (info ) 280self .stop_requested = False 281 282def run (self ): 283return None 284with mock .patch ("strata_cli.launch.monitor_ext.LaunchMonitor" ,Stub ): 285launch_app .run_monitor ({"url" :"http://127.0.0.1:8080" ,"urls" : ["http://127.0.0.1:8080" ],"key" :"" ,"profile" :"launch-x" }) 286self .assertTrue (seen .get ("daily_check" )) 287 288def test_a_monitor_beside_a_hanging_feed_is_not_slowed (self ): 289hang = socket .socket () 290hang .bind (("127.0.0.1" ,0 )) 291hang .listen (5 ) 292self .addCleanup (hang .close ) 293with tempfile_home ()as home : 294env = {"STRATA_COMPONENTS_DIR" :home ,"STRATA_UPDATE_FEED" :f"http://127.0.0.1: { hang . getsockname ()[ 1 ] } /strata-feed.json" } 295with mock .patch .dict (os .environ ,env ): 296started = time .monotonic () 297 298async def case (app ,pilot ): 299self .assertNotIn ("Press u" ,flat (app )) 300return time .monotonic ()- started 301took = self .run_app (case ,info = {** INFO ,"daily_check" :True }) 302self .assertLess (took ,5.0 ,"the monitor drew and ran while the check was still waiting" ) 303 304def test_u_asks_names_the_model_and_shows_what_happened (self ): 305def flow (* ,ask ,say ,** kw ): 306say ("Checking for a newer engine..." ) 307if not ask ("Stop Demo model (port 8080) for the update?" ,False ): 308raise engine_update .Declined ("Nothing was changed. The model keeps running." ) 309return {"results" : [{"component" :"engine" ,"status" :"updated" ,"installed_after" :"0.1.56" }], 310"models" : {"restarts" : [{"name" :"Demo model" ,"restarted" :True ,"message" :"Demo model is serving again with the same settings." }]}} 311 312async def case (app ,pilot ): 313await pilot .press ("u" ) 314await pilot .pause (0.6 ) 315t = flat (app ) 316self .assertIn ("Stop Demo model (port 8080) for the update?" ,t ) 317await pilot .press ("enter" )# Yes 318await pilot .pause (0.8 ) 319t = flat (app ) 320self .assertIn ("Engine is now 0.1.56" ,t ) 321self .assertIn ("serving again" ,t ) 322self .assertFalse (app .updating ) 323with mock .patch .object (engine_update ,"run_flow" ,side_effect = flow ): 324self .run_app (case ,note = "New engine 0.1.56 is available. Press u to update." ) 325 326def test_u_and_no_changes_nothing (self ): 327def flow (* ,ask ,say ,** kw ): 328if not ask ("Stop Demo model for the update?" ,False ): 329raise engine_update .Declined ("Nothing was changed. The model keeps running." ) 330raise AssertionError ("must not get here" ) 331 332async def case (app ,pilot ): 333await pilot .press ("u" ) 334await pilot .pause (0.6 ) 335await pilot .press ("down" ,"enter" )# No 336await pilot .pause (0.8 ) 337self .assertIn ("Nothing was changed. The model keeps running." ,flat (app )) 338with mock .patch .object (engine_update ,"run_flow" ,side_effect = flow ): 339self .run_app (case ) 340 341def test_a_flow_that_breaks_is_a_sentence_not_a_trace (self ): 342async def case (app ,pilot ): 343await pilot .press ("u" ) 344await pilot .pause (0.8 ) 345self .assertIn ("The update did not run: boom" ,flat (app )) 346self .assertTrue (app .is_running ) 347with mock .patch .object (engine_update ,"run_flow" ,side_effect = RuntimeError ("boom" )): 348self .run_app (case ) 349 350 351@ contextlib . contextmanager 352def tempfile_home (): 353import tempfile 354# A check the app started in the background may still hold .updates/update.lock when the case ends (a file in use cannot be deleted on 355# Windows); the folder is scratch, so a leftover is not a failure of the case. 356with tempfile .TemporaryDirectory (prefix = "strata-notice-" ,ignore_cleanup_errors = True )as d : 357yield d 358 359 360if __name__ == "__main__" : 361unittest .main ()