okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
bc6f248ff
main
1r"""pytest: setup.py's data-folder migration (#198) saves the data folder it settled on in the user's settings file 2(%APPDATA%\Strata\settings.json, ~/.config/strata/settings.json) and can MOVE model files from a folder it finds there. 3A test that reaches it must never touch the real file, so the whole session gets its own config home.""" 4import os 5import tempfile 6 7import pytest as _pytest 8 9 10@ _pytest . fixture ( autouse = True ) 11def _fresh_host_memory (): 12"""The network rule remembers, per process, a host that did not answer (strata_control/netpolicy.py HOSTS). A test run is one process: each 13test starts with an empty memory, so one test's dead fake server does not make the next test's request "fail a moment ago".""" 14def forget (): 15try : 16from strata_control import netpolicy 17netpolicy .HOSTS .forget () 18except ImportError : 19pass 20forget () 21yield 22forget () 23 24@ _pytest . fixture ( autouse = True ) 25def _no_language_of_the_box (): 26"""The draft vocabulary follows the computer's languages (strata_control/drafting.py auto_vocab): a test that starts the drafter must not depend on the language, regional format or keyboards of the 27box it runs on (a Windows PC with a Slovenian keyboard layout, a Russian runner). Every test starts on a computer that says no language; the tests about the rule give their own signals.""" 28try : 29from unittest import mock 30from strata_control import drafting 31except ImportError : 32yield 33return 34with mock .patch .object (drafting ,"computer_language_signals" ,return_value = {"ui" : [],"region" : [],"keyboards" : []}): 35yield 36 37 38_home = tempfile .mkdtemp (prefix = "strata-pytest-config-" ) 39os .environ ["APPDATA" ]= _home 40os .environ ["XDG_CONFIG_HOME" ]= _home 41# The per-user STATE and DATA folders too (%LOCALAPPDATA%\Strata: tuning/recheck.json, the engine store, the update records; ~/.local/state, ~/.local/share). 42# A test that installs a stub engine marks saved tuning presets for a re-check there: on 2026-10-24 one such run left an entry in the owner's real 43# tuning\recheck.json. A test that wants a place of its own still names it (STRATA_COMPONENTS_DIR, state_base=...). 44os .environ ["LOCALAPPDATA" ]= _home 45os .environ ["XDG_STATE_HOME" ]= _home 46os .environ ["XDG_DATA_HOME" ]= _home 47# Run from PowerShell 7 (GitHub's Windows runners), PSModulePath names PowerShell 7's module folders first: a Windows PowerShell 5.1 child that a 48# test starts (install.ps1, fetch-node.ps1) then finds their Microsoft.PowerShell.Utility/Security and cannot load them ("Get-FileHash is not 49# recognized"). Keep only the folders that are not PowerShell 7's, as in a Windows PowerShell or cmd window. 50if os .name == "nt" and os .environ .get ("PSModulePath" ): 51_keep = [p for p in os .environ ["PSModulePath" ].split (os .pathsep ) 52if p and not ("\\powershell\\" in p .lower ().replace ("/" ,"\\" )and "\\windowspowershell\\" not in p .lower ().replace ("/" ,"\\" ))] 53os .environ ["PSModulePath" ]= os .pathsep .join (_keep ) 54# The tests run where GitHub's runners do: no NVIDIA card the code can read. On a box with one (p1004's P100, Boston's A6000s, l620) the 55# real nvidia-smi answered and every check that reads the card (engine choice, a stub engine's own start, setup) judged the stand-in 56# packages against it: sm_60 has no code in them, so 64 update tests failed on p1004. A `nvidia-smi` that answers nothing and fails 57# comes first on PATH for the whole run, child processes included; the code reads that as "cannot tell", as without the tool, and a 58# test that needs a card puts its own stand-in first (tools/feed_model_install_gate.py does when `nvidia-smi -L` fails). A test about a 59# card patches the reader (engine_component.cuda_archs_present, setup.gpus, ...) as before. POSIX only for now (a stub there would be 60# a .cmd, which code that runs `nvidia-smi` directly does not start); the Windows test boxes' cards fit the stand-ins. 61if os .name != "nt" and not os .environ .get ("STRATA_TEST_REAL_NVIDIA_SMI" ): 62_smi = os .path .join (_home ,"no-nvidia-smi" ) 63os .makedirs (_smi ,exist_ok = True ) 64with open (os .path .join (_smi ,"nvidia-smi" ),"w" )as _f : 65_f .write ("#!/bin/sh\n# tests: no NVIDIA card can be read here (conftest.py): it answers nothing and fails, as without a loaded driver\nexit 1\n" ) 66os .chmod (os .path .join (_smi ,"nvidia-smi" ),0o755 ) 67os .environ ["PATH" ]= _smi + os .pathsep + os .environ .get ("PATH" ,"" ) 68 69# No test reaches the network (lane NET, 11-10). A test whose fake was bypassed went to the real hosts (on 11-10 a non-hermetic test pulled 70# 1.2 GB), and one on a box without internet hung for the whole timeout. Every connect and every name lookup of this process is checked: 71# loopback and local sockets pass; anything else is refused at once (ConnectionRefusedError / gaierror, which the code under test reads as 72# "offline") and the test FAILS, naming the host. A live test sets STRATA_TEST_ALLOW_NETWORK=1 itself (the 73# STRATA_LIVE_HF test class in tools/ does). Child processes are not covered (the install.sh tests use loopback servers only). 74# Three things that are not "the network" pass, named here: a UDP connect() (it only names the peer and sends nothing: tests that ask which address 75# leads out), a lookup of this computer's own host name, and the RFC 5737 documentation addresses (192.0.2.0/24, 198.51.100.0/24, 203.0.113.0/24, 76# which nothing answers: a test that needs an address that cannot work); they are called (a), (b) and (c) below. Every use is counted per test and 77# the list is printed once at the end of the run (pytest_terminal_summary), so the allowances cannot quietly grow; tests/terminal/test_net_guard.py 78# pins that anything else (an address outside them, a real host name, a TCP connect outside the ranges) still fails. The failure message also says 79# where in the code the reach came from. 80import ipaddress # noqa: E402 81import socket # noqa: E402 82 83import pytest # noqa: E402 84 85_reached :list = [] 86_allowed :list = []# (test id, which allowance, the address): printed once at the end of the run 87_current = {"id" :"(outside a test)" } 88 89 90def _allow (which :str ,address )-> None : 91_allowed .append ((_current ["id" ],which ,str (address ))) 92_OWN_NAME = socket .gethostname ().lower ()# this computer's own name: a lookup of it is a lookup of itself (tests that read the machine's address) 93 94 95def _where ()-> str : 96"""The innermost frame outside this file and the standard library: where the reach came from.""" 97import sysconfig 98import traceback 99stdlib = sysconfig .get_paths ()["stdlib" ].replace ("\\" ,"/" ) 100for frame in reversed (traceback .extract_stack (limit = 40 )): 101name = frame .filename .replace ("\\" ,"/" ) 102if name .endswith ("/conftest.py" )or name .startswith (stdlib ): 103continue 104return f" { name . rsplit ( '/' , 1 )[ - 1 ] } : { frame . lineno } " 105return "?" 106 107 108def _network_allowed ()-> bool : 109return os .environ .get ("STRATA_TEST_ALLOW_NETWORK" )== "1" 110 111 112_DOC_NETS = [ipaddress .ip_network (n )for n in ("192.0.2.0/24" ,"198.51.100.0/24" ,"203.0.113.0/24" )] 113 114 115def _is_documentation (host )-> bool : 116try : 117return any (ipaddress .ip_address (str (host ).strip ("[]" ))in net for net in _DOC_NETS ) 118except ValueError : 119return False 120 121 122def _is_loopback (host )-> bool : 123if host is None : 124return True 125if isinstance (host ,bytes ): 126host = host .decode ("ascii" ,"replace" ) 127host = str (host ).strip ("[]" ).split ("%" ,1 )[0 ].lower () 128if host in ("" ,"localhost" ,"localhost.localdomain" ,"ip6-localhost" ): 129return True 130try : 131return ipaddress .ip_address (host ).is_loopback 132except ValueError : 133return False 134 135 136_real_connect ,_real_connect_ex ,_real_getaddrinfo = socket .socket .connect ,socket .socket .connect_ex ,socket .getaddrinfo 137 138 139def _check (sock ,address )-> None : 140if not isinstance (address ,tuple )or getattr (sock ,"family" ,None )not in (socket .AF_INET ,socket .AF_INET6 ): 141return # a local socket (AF_UNIX) or an address form that is not an IP one 142if _is_loopback (address [0 ])or _network_allowed (): 143return 144if getattr (sock ,"type" ,None )== socket .SOCK_DGRAM : 145_allow ("(a) UDP connect" ,f" { address [ 0 ] } : { address [ 1 ] } " ) 146return # a UDP connect() only names the peer: it sends nothing (a test that asks which address leads out) 147if _is_documentation (address [0 ]): 148_allow ("(c) documentation address" ,f" { address [ 0 ] } : { address [ 1 ] } " ) 149return # RFC 5737 TEST-NET: reserved so that nothing answers (a test that needs an address that cannot work) 150_reached .append (f" { address [ 0 ] } : { address [ 1 ] } [ { _where () } ]" ) 151raise ConnectionRefusedError (f"a test reached the network ( { address [ 0 ] } : { address [ 1 ] } ): fake it, or set STRATA_TEST_ALLOW_NETWORK=1 in a live test" ) 152 153 154def _guarded_connect (self ,address ): 155_check (self ,address ) 156return _real_connect (self ,address ) 157 158 159def _guarded_connect_ex (self ,address ): 160_check (self ,address ) 161return _real_connect_ex (self ,address ) 162 163 164def _guarded_getaddrinfo (host ,* args ,** kwargs ): 165if str (host ).lower ()== _OWN_NAME and not _is_loopback (host ): 166_allow ("(b) own host name" ,host ) 167if not (_is_loopback (host )or _network_allowed ()or str (host ).lower ()== _OWN_NAME ): 168_reached .append (f" { host } [ { _where () } ]" ) 169raise socket .gaierror (socket .EAI_NONAME ,f"a test looked up { host } : fake it, or set STRATA_TEST_ALLOW_NETWORK=1 in a live test" ) 170return _real_getaddrinfo (host ,* args ,** kwargs ) 171 172 173socket .socket .connect = _guarded_connect 174socket .socket .connect_ex = _guarded_connect_ex 175socket .getaddrinfo = _guarded_getaddrinfo 176 177 178@ pytest . fixture ( autouse = True ) 179def _no_network (request ): 180"""Fails the test that reached for a host other than this computer (after it ran, so its own result is not hidden).""" 181del _reached [:] 182_current ["id" ]= request .node .nodeid 183yield 184_current ["id" ]= "(outside a test)" 185if _reached : 186hosts = sorted (set (_reached )) 187del _reached [:] 188pytest .fail (f" { request . node . nodeid } reached the network: { ', ' . join ( hosts ) } (fake it, or set STRATA_TEST_ALLOW_NETWORK=1 in a live test)" , 189pytrace = False ) 190 191 192def pytest_terminal_summary (terminalreporter ): 193"""The allowances the guard made in this run, once: which test, which allowance, which address.""" 194if not _allowed : 195return 196terminalreporter .section ("network guard: allowances used" ) 197for test_id ,which ,address in sorted (set (_allowed )): 198terminalreporter .write_line (f" { test_id } { which } { address } " )