diff --git a/scripts/windows-boot/boot.ps1 b/scripts/windows-boot/boot.ps1 index db11e4e76a..e73b69c97e 100644 --- a/scripts/windows-boot/boot.ps1 +++ b/scripts/windows-boot/boot.ps1 @@ -80,7 +80,7 @@ Launch with the offline first-run UI profile instead of the generic runtime profile. .PARAMETER Python - Python 3.12+ used for tools/boot_trace.py. Default: python, else py -3. + Python 3.12+ used for tools/boot_trace.py. Default: python, else py -3, the first that starts and is 3.12+. .PARAMETER SummaryLines How many lines of the boot_trace.py report to print. Default 40; 0 prints none. @@ -179,11 +179,30 @@ function Test-InsideFolder { return $p.StartsWith($f, [System.StringComparison]::OrdinalIgnoreCase) } +function Test-Python { + # Get-Command also finds the Microsoft Store's python.exe alias in WindowsApps, which only says how to install + # Python and exits 9009, and the repository needs 3.12+ (README.md): take a candidate that starts and is 3.12+, + # within 15 s, so that one that hangs cannot hold the script after the game has stopped. + param([string[]]$Command) + $ErrorActionPreference = "Continue" + $exe = Get-Command $Command[0] -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1 + if (-not $exe) { return $false } + $arguments = @($Command | Select-Object -Skip 1) + @("-I", "-c", '"import sys; sys.exit(sys.version_info < (3, 12))"') + try { $p = Start-Process -FilePath $exe.Source -ArgumentList $arguments -WindowStyle Hidden -PassThru } catch { return $false } + $null = $p.Handle # Windows PowerShell 5.1 reports no ExitCode unless the handle was opened while it ran + if (-not $p.WaitForExit(15000)) { + & taskkill.exe /T /F /PID $p.Id 2>&1 | Out-Null + return $false + } + return ($p.ExitCode -eq 0) +} + function Resolve-Python { param([string]$Requested) if ($Requested) { return @($Requested) } - if (Get-Command python -ErrorAction SilentlyContinue) { return @("python") } - if (Get-Command py -ErrorAction SilentlyContinue) { return @("py", "-3") } + foreach ($candidate in @(@("python"), @("py", "-3"))) { + if (Test-Python $candidate) { return $candidate } + } return @() } @@ -385,7 +404,7 @@ if ($py.Count) { & $py[0] @pyArgs 2>&1 | ForEach-Object { "$_" } | Out-File -FilePath $SummaryFile -Encoding utf8 $ErrorActionPreference = "Stop" } else { - "no python found for tools/boot_trace.py" | Out-File -FilePath $SummaryFile -Encoding utf8 + "no usable Python 3.12+ found for tools/boot_trace.py (checked 'python' and 'py -3'; specify -Python to use another interpreter)" | Out-File -FilePath $SummaryFile -Encoding utf8 } $peekRx = [regex]'\[rt\] peek t=(\d+)s:(.*)$' diff --git a/tests/test_boot_ps1_python.py b/tests/test_boot_ps1_python.py new file mode 100644 index 0000000000..c049e661d8 --- /dev/null +++ b/tests/test_boot_ps1_python.py @@ -0,0 +1,98 @@ +"""scripts/windows-boot/boot.ps1: Resolve-Python takes a Python that starts and is 3.12+, not just one on PATH. + + python -I tests/test_boot_ps1_python.py -v + +The Microsoft Store's python.exe alias in WindowsApps is found by Get-Command but only says how to install Python and +exits 9009; when it was taken, tools/boot_trace.py never ran and .summary.txt held only that message. The test +runs the script's own Test-Python and Resolve-Python against stand-in python.cmd and py.cmd. No game data. +""" +import os +from pathlib import Path +import re +import subprocess +import sys +import tempfile +import time +import unittest +import uuid + +BOOT = Path(__file__).resolve().parents[1] / "scripts" / "windows-boot" / "boot.ps1" + +# Stand-ins: the Store alias, the real interpreter running these tests (3.12+), and one that reports another version. +STORE_ALIAS = "@echo off\r\necho Python was not found; run without arguments to install from the Microsoft Store\r\nexit /b 9009\r\n" +REAL = f'@"{sys.executable}" %*\r\n' +REAL_PY = f'@if "%1"=="-3" shift\r\n@"{sys.executable}" %1 %2 %3\r\n' + + +def reports(version): + """A python.cmd that runs Test-Python's check (its third argument) with sys.version_info set to version.""" + return f'@"{sys.executable}" -I -c "import sys; sys.version_info = {version!r}; exec(sys.argv[1])" %3\r\n' + + +def hangs(tag): + """A python.cmd that sleeps for 2 minutes in a child process whose command line holds tag.""" + return f'@"{sys.executable}" -I -c "import time; time.sleep(120)" {tag}\r\n' + + +def processes_with(tag): + # The tag is split so that this PowerShell's own command line does not hold it. + half = len(tag) // 2 + script = (f"$t = '{tag[:half]}' + '{tag[half:]}'; " + "@(Get-CimInstance Win32_Process | Where-Object { $_.CommandLine -like \"*$t*\" }).Count") + result = subprocess.run(["powershell.exe", "-NoProfile", "-NonInteractive", "-Command", script], + capture_output=True, text=True, timeout=60) + return int(result.stdout.strip()) + + +def functions(): + text = BOOT.read_text("utf-8") + found = [re.search(r"^function %s \{.*?^\}" % name, text, re.S | re.M) for name in ("Test-Python", "Resolve-Python")] + assert all(found), "Test-Python and Resolve-Python are no longer in boot.ps1" + return "\n\n".join(m.group(0) for m in found) + + +@unittest.skipUnless(os.name == "nt", "Windows PowerShell") +class ResolvePythonTests(unittest.TestCase): + def resolve(self, files, requested=""): + # A stand-in left running holds the folder; the hang test then says so instead of failing on the cleanup. + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: + for name, body in files.items(): + Path(tmp, name).write_text(body, encoding="ascii", newline="") + system32 = str(Path(os.environ["SystemRoot"], "System32")) + env = {**os.environ, "PATH": tmp + os.pathsep + system32} + script = (f"$ErrorActionPreference = 'Stop'\n{functions()}\n" + f"(@(Resolve-Python '{requested}') -join ' ')") + result = subprocess.run(["powershell.exe", "-NoProfile", "-NonInteractive", "-Command", script], + cwd=tmp, env=env, capture_output=True, text=True, timeout=60) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + return result.stdout.strip() + + def test_the_store_alias_is_passed_over_for_py(self): + self.assertEqual(self.resolve({"python.cmd": STORE_ALIAS, "py.cmd": REAL_PY}), "py -3") + + def test_a_working_python_is_taken(self): + self.assertEqual(self.resolve({"python.cmd": REAL, "py.cmd": REAL_PY}), "python") + + def test_a_python_older_than_3_12_is_passed_over(self): + self.assertEqual(self.resolve({"python.cmd": reports((3, 11, 9)), "py.cmd": REAL_PY}), "py -3") + + def test_python_3_12_is_taken(self): + self.assertEqual(self.resolve({"python.cmd": reports((3, 12, 0)), "py.cmd": REAL_PY}), "python") + + def test_a_python_that_hangs_is_given_up_on(self): + tag = "boot-ps1-hang-" + uuid.uuid4().hex + start = time.monotonic() + self.assertEqual(self.resolve({"python.cmd": hangs(tag), "py.cmd": REAL_PY}), "py -3") + self.assertLess(time.monotonic() - start, 45) # 15 s for python, then py; the stand-in would hang 2 min + self.assertEqual(processes_with(tag), 0, "the hanging stand-in's child outlived Test-Python") + + def test_none_that_works_gives_none(self): + self.assertEqual(self.resolve({"python.cmd": STORE_ALIAS}), "") + + def test_a_named_python_is_used_as_given(self): + self.assertEqual(self.resolve({"python.cmd": STORE_ALIAS}, requested="C:\\Python312\\python.exe"), + "C:\\Python312\\python.exe") + + +if __name__ == "__main__": + unittest.main()