okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
c7ec1e8fe
main
1"""netpolicy rule 4b (owner 11-11, "Remembering refused update feeds on Windows": Ok): a feed host that REFUSED the connection is remembered 2on disk for 6 hours, in Strata's own state folder, host:port and the time only. Only automatic reads (`automatic=True`) read the note; a read 3the person asked for by name ignores it; the first answer from the host removes it; a damaged or unreadable note is no note, without a message. 4 5Windows needs about 2.0 s to report a refused connection (measured 2.03-2.04 s on the owner PC, owner-20261110-2003-a8da); a launch of a model 6with its own engine shape read the feed on every start, so a PC behind a dead proxy paid that on every start. Every test here works in a test 7HOME (conftest.py and launch_support.Home redirect the state folder) or on a note file of its own.""" 8 9from __future__import annotations 10 11import contextlib 12import io 13import json 14import os 15import tempfile 16import time 17import unittest 18import urllib .request 19from pathlib import Path 20from unittest import mock 21 22from strata_control import netpolicy ,paths ,transfer 23from tests .terminal .launch_support import Home 24from tests .terminal .test_netpolicy import refused_port 25 26 27class Clock : 28def __init__ (self ,t :float = 1_000_000.0 ): 29self .t = t 30 31def __call__ (self )-> float : 32return self .t 33 34 35def note_in (folder :Path ,clock = None )-> netpolicy .RefusalNote : 36return netpolicy .RefusalNote (path = folder / "net" / netpolicy .REFUSED_NOTE_NAME ,clock = clock or Clock ()) 37 38 39class Base (unittest .TestCase ): 40def setUp (self ): 41t = tempfile .TemporaryDirectory (prefix = "strata-refused-" ) 42self .addCleanup (t .cleanup ) 43self .dir = Path (t .name ) 44self .clock = Clock () 45self .note = note_in (self .dir ,self .clock ) 46netpolicy .HOSTS .forget () 47self .addCleanup (netpolicy .HOSTS .forget ) 48 49 50def refuse (request ,timeout ): 51raise ConnectionRefusedError (10061 if os .name == "nt" else 111 ,"refused" ) 52 53 54class TheNote (Base ): 55def test_the_values_of_the_rule (self ): 56self .assertEqual (netpolicy .REFUSED_NOTE_S ,6 * 3600 ) 57with Home ():# the default note lives in Strata's own state folder (read when used) 58self .assertEqual (netpolicy .REFUSALS .path (),paths .state_base ()/ "net" / "refused-hosts.json" ) 59base = Path (os .environ ["LOCALAPPDATA" if os .name == "nt" else "XDG_STATE_HOME" ]) 60self .assertEqual (netpolicy .REFUSALS .path ().parent .parent .parent ,base ,"inside the test HOME's state folder" ) 61 62def test_host_port_and_time_only_and_six_hours (self ): 63self .note .remember ("github.com:443" ) 64self .assertEqual (json .loads (self .note .path ().read_text (encoding = "utf-8" )), {"github.com:443" :self .clock .t }) 65self .assertTrue (self .note .refused_recently ("github.com:443" )) 66self .assertFalse (self .note .refused_recently ("github.com:8443" ),"per host AND port" ) 67self .clock .t += 6 * 3600 - 1 68self .assertTrue (self .note .refused_recently ("github.com:443" )) 69self .clock .t += 1 70self .assertFalse (self .note .refused_recently ("github.com:443" ),"after 6 hours the host is asked again" ) 71self .note .remember ("example.org:443" )# writing drops the expired entries 72self .assertEqual (sorted (json .loads (self .note .path ().read_text (encoding = "utf-8" ))), ["example.org:443" ]) 73 74def test_a_clock_that_went_back_does_not_keep_a_host_forever (self ): 75self .note .remember ("github.com:443" ) 76self .clock .t -= 3600 77self .assertFalse (self .note .refused_recently ("github.com:443" )) 78 79def test_forget_removes_the_host_and_the_empty_note (self ): 80self .note .remember ("a:1" ) 81self .note .remember ("b:2" ) 82self .note .forget ("a:1" ) 83self .assertEqual (sorted (json .loads (self .note .path ().read_text (encoding = "utf-8" ))), ["b:2" ]) 84self .note .forget ("b:2" ) 85self .assertFalse (self .note .path ().exists ()) 86 87def test_forget_without_a_note_writes_nothing (self ): 88self .note .forget ("a:1" ) 89self .assertFalse (self .note .path ().parent .exists ()) 90 91def test_a_damaged_or_unreadable_note_is_no_note_and_says_nothing (self ): 92p = self .note .path () 93p .parent .mkdir (parents = True ) 94for text in ("{not json" ,"[1, 2]" ,'{"a:1": "yesterday"}' ,'{"a:1": true}' ,"\xff\xfe" .encode ("latin-1" ).decode ("latin-1" )): 95p .write_text (text ,encoding = "latin-1" ) 96out ,err = io .StringIO (),io .StringIO () 97with contextlib .redirect_stdout (out ),contextlib .redirect_stderr (err ): 98self .assertFalse (self .note .refused_recently ("a:1" ),text ) 99self .note .remember ("c:3" )# a damaged note is replaced by a good one 100self .assertTrue (self .note .refused_recently ("c:3" )) 101self .assertEqual ((out .getvalue (),err .getvalue ()), ("" ,"" )) 102p .unlink () 103p .mkdir ()# a folder where the note should be: cannot be read or written 104self .assertFalse (self .note .refused_recently ("a:1" )) 105self .note .remember ("a:1" )# silently not kept 106self .note .forget ("a:1" ) 107self .assertFalse (self .note .refused_recently ("a:1" )) 108 109 110class OpenUrl (Base ): 111def test_a_refusal_is_noted_and_the_next_automatic_read_does_not_connect (self ): 112with self .assertRaises (netpolicy .NetFailure )as cm : 113netpolicy .open_url (refuse ,"https://feed.example:443/strata-feed.json" ,refusals = self .note ,automatic = True ) 114self .assertEqual (cm .exception .kind ,"offline" ) 115self .assertTrue (self .note .refused_recently ("feed.example:443" )) 116calls = [] 117 118def counting (request ,timeout ): 119calls .append (1 ) 120return b"answer" 121with self .assertRaises (netpolicy .NetFailure )as cm : 122netpolicy .open_url (counting ,"https://feed.example:443/strata-feed.json" ,refusals = self .note ,automatic = True ) 123self .assertEqual ((cm .exception .kind ,calls ), ("offline" , []),"the automatic read failed at once, without a connection" ) 124self .assertIn ("could not connect" ,str (cm .exception ),"the same offline words as a refusal" ) 125 126def test_a_read_asked_for_by_name_ignores_the_note_and_its_answer_removes_the_host (self ): 127self .note .remember ("feed.example:443" ) 128calls = [] 129 130def answer (request ,timeout ): 131calls .append (1 ) 132return b"answer" 133self .assertEqual (netpolicy .open_url (answer ,"https://feed.example:443/strata-feed.json" ,refusals = self .note ),b"answer" ) 134self .assertEqual (calls , [1 ]) 135self .assertFalse (self .note .refused_recently ("feed.example:443" ),"the first success removes the host" ) 136self .assertEqual (netpolicy .open_url (answer ,"https://feed.example:443/strata-feed.json" ,refusals = self .note ,automatic = True ),b"answer" ) 137 138def test_an_http_answer_also_removes_the_host (self ): 139import urllib .error 140self .note .remember ("feed.example:443" ) 141 142def missing (request ,timeout ): 143raise urllib .error .HTTPError (str (request ),404 ,"Not Found" , {},None ) 144with self .assertRaises (urllib .error .HTTPError ): 145netpolicy .open_url (missing ,"https://feed.example:443/x" ,refusals = self .note ) 146self .assertFalse (self .note .refused_recently ("feed.example:443" )) 147 148def test_only_a_refusal_is_noted (self ): 149import socket 150 151def no_name (request ,timeout ): 152raise socket .gaierror (- 2 ,"Name or service not known" ) 153 154def timeout (request ,timeout ): 155raise TimeoutError ("timed out" ) 156for fn in (no_name ,timeout ): 157with self .assertRaises (netpolicy .NetFailure ): 158netpolicy .open_url (fn ,"https://feed.example:443/x" ,refusals = self .note ,limits = (0.01 ,),gap = 0 ,sleep = lambda s :None ) 159self .assertFalse (self .note .path ().exists (),"no DNS answer and a timeout are not refusals (the first fails at once anyway)" ) 160 161def test_a_refusal_through_urllib_is_seen (self ): 162import urllib .error 163self .assertTrue (netpolicy .refused (urllib .error .URLError (ConnectionRefusedError (111 ,"refused" )))) 164self .assertFalse (netpolicy .refused (urllib .error .URLError ("timed out" ))) 165 166 167class RealSocket (Base ): 168def test_a_refused_loopback_port_costs_its_wait_once_then_nothing (self ): 169url = f"http://127.0.0.1: { refused_port () } /strata-feed.json" 170with mock .patch .object (netpolicy ,"REFUSALS" ,self .note ): 171t0 = time .monotonic () 172with self .assertRaises (transfer .Unreachable ): 173transfer .read_small (url ,timeout = 5 ,automatic = True ) 174first = time .monotonic ()- t0 175t0 = time .monotonic () 176with self .assertRaises (transfer .Unreachable ): 177transfer .read_small (url ,timeout = 5 ,automatic = True ) 178second = time .monotonic ()- t0 179t0 = time .monotonic () 180with self .assertRaises (transfer .Unreachable ): 181transfer .read_small (url ,timeout = 5 )# asked for by name: it tries again 182explicit = time .monotonic ()- t0 183f"refused loopback: first { first :.3f } s, second (noted) { second :.3f } s, explicit { explicit :.3f } s" ) 184self .assertLess (second ,0.2 ) 185if os .name == "nt" :# Windows reports a refusal after about 2 s: the note saves exactly that 186self .assertGreater (first ,1.0 ) 187self .assertGreater (explicit ,1.0 ) 188 189 190if __name__ == "__main__" : 191unittest .main ()