okami.mom/strata

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

Niko1221Merge f-0213-life (final 576d06553) into f-0213-int66331f9bc

main
6.6 KiB135 linesraw
1"""#4975 (PR #5185 is the reference): the OS and architecture are known without WMI on Windows.
2
3On Windows with Python 3.12 `platform.uname()` (so `system()`, `machine()`, `release()`, `version()`, `processor()` and `node()`) asks WMI
4(`platform._wmi_query`) with no timeout. A stuck `winmgmt` froze every Control command that resolves the engine component. A stuck WMI
5cannot be produced from a test, so these tests make every `platform` call that could reach it fail loudly, and check that the Windows
6answers still come out of the interpreter and the environment.
7
8    python -m pytest tests/terminal/test_sysinfo.py
9"""
10import os
11import re
12import sys
13import tempfile
14import unittest
15from collections import namedtuple
16from pathlib import Path
17from unittest import mock
18
19from strata_control import engine_component, sysinfo, targets
20
21WinVer = namedtuple("WinVer", "major minor build")
22
23
24def _stuck(name):
25    def hang(*a, **k):
26        raise AssertionError(f"platform.{name} reached WMI")
27    return hang
28
29
30def _windows(env, build=19045):
31    """sys.platform is win32, the environment is `env`, and every platform call that asks WMI fails."""
32    stack = [mock.patch.object(sys, "platform", "win32"),
33             mock.patch.object(sys, "getwindowsversion", lambda: WinVer(10, 0, build), create=True),
34             mock.patch.dict(os.environ, env, clear=False)]
35    for name in ("uname", "system", "machine", "release", "version", "processor", "node", "platform", "win32_ver", "_wmi_query"):
36        stack.append(mock.patch.object(sysinfo.platform, name, _stuck(name), create=True))
37    return stack
38
39
40class Stuck(unittest.TestCase):
41    def run_in(self, env, fn, build=19045):
42        stack = _windows(env, build)
43        for item in stack:
44            item.start()
45        try:
46            return fn()
47        finally:
48            for item in reversed(stack):
49                item.stop()
50
51    def test_windows_x64_host_platform_while_wmi_is_stuck(self):
52        env = {"PROCESSOR_ARCHITECTURE": "AMD64", "PROCESSOR_ARCHITEW6432": ""}
53        self.assertEqual(self.run_in(env, targets.host_platform), "windows-x86_64")
54
55    def test_windows_arm64_native(self):
56        env = {"PROCESSOR_ARCHITECTURE": "ARM64", "PROCESSOR_ARCHITEW6432": ""}
57        self.assertEqual(self.run_in(env, targets.host_platform), "windows-arm64")
58
59    def test_x64_python_emulated_on_arm64_sees_amd64_and_gets_the_x64_engine(self):
60        env = {"PROCESSOR_ARCHITECTURE": "AMD64", "PROCESSOR_ARCHITEW6432": ""}
61        self.assertEqual(self.run_in(env, sysinfo.machine), "AMD64")
62
63    def test_a_32_bit_process_on_64_bit_windows_reads_the_real_architecture(self):
64        for real, expect in (("AMD64", "windows-x86_64"), ("ARM64", "windows-arm64")):
65            env = {"PROCESSOR_ARCHITECTURE": "x86", "PROCESSOR_ARCHITEW6432": real}
66            self.assertEqual(self.run_in(env, targets.host_platform), expect)
67
68    def test_without_the_environment_the_interpreter_build_answers(self):
69        stack = _windows({})
70        for item in stack:
71            item.start()
72        try:
73            with mock.patch.dict(os.environ, {}, clear=True), mock.patch("sysconfig.get_platform", return_value="win-arm64"):
74                self.assertEqual(sysinfo.machine(), "ARM64")
75            with mock.patch.dict(os.environ, {}, clear=True), mock.patch("sysconfig.get_platform", return_value="win-amd64"):
76                self.assertEqual(sysinfo.machine(), "AMD64")
77        finally:
78            for item in reversed(stack):
79                item.stop()
80
81    def test_release_version_processor_and_node_need_no_wmi(self):
82        env = {"PROCESSOR_ARCHITECTURE": "AMD64", "PROCESSOR_IDENTIFIER": "Intel64 Family 6 Model 183"}
83
84        def facts():
85            return (sysinfo.system(), sysinfo.release(), sysinfo.version(), sysinfo.processor(), bool(sysinfo.node()),
86                    sysinfo.platform_string())
87        self.assertEqual(self.run_in(env, facts, 22631),
88                         ("Windows", "11", "10.0.22631", "Intel64 Family 6 Model 183", True, "Windows-11-10.0.22631"))
89        self.assertEqual(self.run_in(env, facts, 19045)[1], "10")
90
91    def test_the_engine_lookup_of_a_run_config_does_not_reach_wmi(self):
92        # the very path of the report: engine_component.resolve() -> host_platform()
93        env = {"PROCESSOR_ARCHITECTURE": "AMD64", "PROCESSOR_ARCHITEW6432": ""}
94
95        def look():
96            with tempfile.TemporaryDirectory() as folder:
97                try:
98                    engine_component.resolve(Path(folder), backend="cpu")
99                except engine_component.EngineMissing:
100                    return "missing"
101        self.assertEqual(self.run_in(env, look), "missing")
102
103
104class OtherSystemsKeepTheirAnswers(unittest.TestCase):
105    def test_macos_and_linux_use_the_platform_module(self):
106        with mock.patch.object(sys, "platform", "darwin"), mock.patch.object(sysinfo.platform, "system", return_value="Darwin"), \
107                mock.patch.object(sysinfo.platform, "machine", return_value="arm64"):
108            self.assertEqual(targets.host_platform(), "macos-arm64")
109        with mock.patch.object(sys, "platform", "linux"), mock.patch.object(sysinfo.platform, "system", return_value="Linux"), \
110                mock.patch.object(sysinfo.platform, "machine", return_value="aarch64"):
111            self.assertEqual(targets.host_platform(), "linux-aarch64")
112
113    def test_the_answer_is_a_key_of_the_backend_matrix(self):
114        self.assertIn(targets.host_platform(), {t for ts in targets.BACKEND_MATRIX.values() for t in ts})
115
116    def test_no_control_module_calls_the_uname_based_platform_functions_directly(self):
117        # the callers that can run on Windows were moved to sysinfo; a new direct call would bring the hang back
118        root = Path(__file__).resolve().parents[2]
119        bad = []
120        for rel in ("strata_control", "strata_cli", "serve"):
121            for path in (root / rel).rglob("*.py"):
122                # mac_fit.py is macOS only; engine_component's one call is behind sys.platform.startswith("linux") on the same line
123                if path.name.startswith("test_") or path.name in ("sysinfo.py", "mac_fit.py"):
124                    continue
125                for number, line in enumerate(path.read_text(encoding="utf-8", errors="replace").splitlines(), 1):
126                    if line.lstrip().startswith("#") or "`platform." in line:
127                        continue
128                    if re.search(r"(?<![\w.])platform\.(system|machine|release|version|processor|node|platform|uname)\(\)", line) \
129                            and "linux" not in line:
130                        bad.append(f"{path.relative_to(root)}:{number}: {line.strip()}")
131        self.assertEqual(bad, [])
132
133
134if __name__ == "__main__":
135    unittest.main()