okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-draft-vocab 925d6fb05 into f-p4-int (the draft vocabulary is picked by the computer's languages; a renamed Flash-Next file starts the drafter)bc6f248ff

main
10.5 KiB198 linesraw
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
13    test starts with an empty memory, so one test's dead fake server does not make the next test's request "fail a moment ago"."""
14    def forget():
15        try:
16            from strata_control import netpolicy
17            netpolicy.HOSTS.forget()
18        except ImportError:
19            pass
20    forget()
21    yield
22    forget()
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
27    box 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."""
28    try:
29        from unittest import mock
30        from strata_control import drafting
31    except ImportError:
32        yield
33        return
34    with mock.patch.object(drafting, "computer_language_signals", return_value={"ui": [], "region": [], "keyboards": []}):
35        yield
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)
52             if p and not ("\\powershell\\" in p.lower().replace("/", "\\") and "\\windowspowershell\\" not in p.lower().replace("/", "\\"))]
53    os.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")
63    os.makedirs(_smi, exist_ok=True)
64    with 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")
66    os.chmod(os.path.join(_smi, "nvidia-smi"), 0o755)
67    os.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."""
97    import sysconfig
98    import traceback
99    stdlib = sysconfig.get_paths()["stdlib"].replace("\\", "/")
100    for frame in reversed(traceback.extract_stack(limit=40)):
101        name = frame.filename.replace("\\", "/")
102        if name.endswith("/conftest.py") or name.startswith(stdlib):
103            continue
104        return f"{name.rsplit('/', 1)[-1]}:{frame.lineno}"
105    return "?"
106
107
108def _network_allowed() -> bool:
109    return 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:
116    try:
117        return any(ipaddress.ip_address(str(host).strip("[]")) in net for net in _DOC_NETS)
118    except ValueError:
119        return False
120
121
122def _is_loopback(host) -> bool:
123    if host is None:
124        return True
125    if isinstance(host, bytes):
126        host = host.decode("ascii", "replace")
127    host = str(host).strip("[]").split("%", 1)[0].lower()
128    if host in ("", "localhost", "localhost.localdomain", "ip6-localhost"):
129        return True
130    try:
131        return ipaddress.ip_address(host).is_loopback
132    except ValueError:
133        return 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:
140    if not isinstance(address, tuple) or getattr(sock, "family", None) not in (socket.AF_INET, socket.AF_INET6):
141        return                                              # a local socket (AF_UNIX) or an address form that is not an IP one
142    if _is_loopback(address[0]) or _network_allowed():
143        return
144    if getattr(sock, "type", None) == socket.SOCK_DGRAM:
145        _allow("(a) UDP connect", f"{address[0]}:{address[1]}")
146        return                                              # a UDP connect() only names the peer: it sends nothing (a test that asks which address leads out)
147    if _is_documentation(address[0]):
148        _allow("(c) documentation address", f"{address[0]}:{address[1]}")
149        return                                              # 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()}]")
151    raise 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)
156    return _real_connect(self, address)
157
158
159def _guarded_connect_ex(self, address):
160    _check(self, address)
161    return _real_connect_ex(self, address)
162
163
164def _guarded_getaddrinfo(host, *args, **kwargs):
165    if str(host).lower() == _OWN_NAME and not _is_loopback(host):
166        _allow("(b) own host name", host)
167    if not (_is_loopback(host) or _network_allowed() or str(host).lower() == _OWN_NAME):
168        _reached.append(f"{host} [{_where()}]")
169        raise socket.gaierror(socket.EAI_NONAME, f"a test looked up {host}: fake it, or set STRATA_TEST_ALLOW_NETWORK=1 in a live test")
170    return _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)."""
181    del _reached[:]
182    _current["id"] = request.node.nodeid
183    yield
184    _current["id"] = "(outside a test)"
185    if _reached:
186        hosts = sorted(set(_reached))
187        del _reached[:]
188        pytest.fail(f"{request.node.nodeid} reached the network: {', '.join(hosts)} (fake it, or set STRATA_TEST_ALLOW_NETWORK=1 in a live test)",
189                    pytrace=False)
190
191
192def pytest_terminal_summary(terminalreporter):
193    """The allowances the guard made in this run, once: which test, which allowance, which address."""
194    if not _allowed:
195        return
196    terminalreporter.section("network guard: allowances used")
197    for test_id, which, address in sorted(set(_allowed)):
198        terminalreporter.write_line(f"{test_id}   {which}   {address}")