conformance run.ps1: propagate exit status and guard blank or root output

This commit is contained in:
kirigayakazima
2026-11-26 22:04:57 +08:00
parent 73516a2902
commit 6873202cfb
3 changed files with 129 additions and 13 deletions

View File

@ -0,0 +1,89 @@
"""Tests for tools/conformance/native/scripts/run.ps1 exit propagation and path safety.
python -I tests/test_conformance_run_exit.py
"""
from __future__ import annotations
import os
import shutil
import subprocess
import tempfile
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
SCRIPT = ROOT / "tools" / "conformance" / "native" / "scripts" / "run.ps1"
class ConformanceRunExitTests(unittest.TestCase):
def test_static_exit_propagation_and_guards(self) -> None:
text = SCRIPT.read_text(encoding="utf-8")
self.assertIn("IsNullOrWhiteSpace", text)
self.assertIn("is the native conformance folder", text)
self.assertIn("exit $rc", text)
@unittest.skipUnless(os.name == "nt" and shutil.which("powershell.exe"), "requires Windows PowerShell")
def test_propagates_renderer_exit_code_and_refuses_blank_or_root_output(self) -> None:
with tempfile.TemporaryDirectory() as td:
base = Path(td)
native = base / "tools" / "conformance" / "native"
scripts = native / "scripts"
exe_dir = native / "build" / "Release"
scripts.mkdir(parents=True)
exe_dir.mkdir(parents=True)
shutil.copy2(SCRIPT, scripts / "run.ps1")
exe_path = exe_dir / "conform_native.exe"
ps_exe = "powershell.exe"
ps_base = [ps_exe, "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass"]
compile_cmd = (
"$ErrorActionPreference = 'Stop'; "
"Add-Type -OutputAssembly $env:STUB_EXE -OutputType ConsoleApplication -TypeDefinition @'\n"
"using System;\n"
"public class Program {\n"
" public static int Main(string[] args) {\n"
" string v = Environment.GetEnvironmentVariable(\"LEONIDA_TEST_EXIT\");\n"
" return string.IsNullOrEmpty(v) ? 0 : int.Parse(v);\n"
" }\n"
"}\n'@"
)
env = {**os.environ, "STUB_EXE": str(exe_path)}
env["PSModulePath"] = str(Path(os.environ["SystemRoot"]) / "System32/WindowsPowerShell/v1.0/Modules")
subprocess.run([*ps_base, "-Command", compile_cmd], env=env, check=True, timeout=60)
out_dir = base / "out_ok"
for code in (0, 7):
with self.subTest(code=code):
res = subprocess.run(
[*ps_base, "-File", str(scripts / "run.ps1"), "-Output", str(out_dir)],
env={**env, "LEONIDA_TEST_EXIT": str(code)},
capture_output=True,
text=True,
timeout=30,
)
self.assertEqual(res.returncode, code, res.stdout + res.stderr)
self.assertIn(f"EXITCODE {code}", res.stdout)
blank = subprocess.run(
[*ps_base, "-File", str(scripts / "run.ps1"), "-Output", " "],
env={**env, "LEONIDA_TEST_EXIT": "0"},
capture_output=True,
text=True,
timeout=30,
)
self.assertEqual(blank.returncode, 2, blank.stdout + blank.stderr)
self.assertIn("is blank", blank.stdout)
root_res = subprocess.run(
[*ps_base, "-File", str(scripts / "run.ps1"), "-Output", str(native)],
env={**env, "LEONIDA_TEST_EXIT": "0"},
capture_output=True,
text=True,
timeout=30,
)
self.assertEqual(root_res.returncode, 2, root_res.stdout + root_res.stderr)
self.assertIn("is the native conformance folder", root_res.stdout)
if __name__ == "__main__":
unittest.main()

View File

@ -2,8 +2,8 @@
touching -Output, and refuses (exit 2) an -Output that is a file, a link or junction, or a folder holding anything
but <scene>.png and manifest.json. Before, `Remove-Item $Output -Recurse -Force` ran first on whatever was passed.
The script runs from a copy of tools/conformance/native in a temporary folder, with where.exe standing in for
conform_native.exe: it exits at once and writes nothing, which is all these checks need. Windows only."""
The script runs from a copy of tools/conformance/native in a temporary folder, with a synthetic stub standing in for
conform_native.exe: it exits 0 at once and writes nothing, which is all these checks need. Windows only."""
import os
from pathlib import Path
import shutil
@ -13,12 +13,32 @@ import unittest
SCRIPT = Path(__file__).resolve().parents[1] / "tools" / "conformance" / "native" / "scripts" / "run.ps1"
STAND_IN = Path(os.environ.get("SystemRoot", r"C:\Windows")) / "System32" / "where.exe"
@unittest.skipUnless(os.name == "nt" and shutil.which("powershell.exe") and STAND_IN.is_file(),
"requires Windows PowerShell")
@unittest.skipUnless(os.name == "nt" and shutil.which("powershell.exe"), "requires Windows PowerShell")
class RunScriptTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.stub_dir = tempfile.TemporaryDirectory()
cls.stub_exe = Path(cls.stub_dir.name) / "conform_native_stub.exe"
env = {**os.environ, "STUB_EXE": str(cls.stub_exe)}
env["PSModulePath"] = str(Path(os.environ.get("SystemRoot", r"C:\Windows")) / "System32/WindowsPowerShell/v1.0/Modules")
compile_cmd = (
"$ErrorActionPreference = 'Stop'; "
"Add-Type -OutputAssembly $env:STUB_EXE -OutputType ConsoleApplication -TypeDefinition "
"'public class Stub { public static int Main() { return 0; } }'"
)
subprocess.run(
["powershell.exe", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", compile_cmd],
env=env,
check=True,
timeout=60,
)
@classmethod
def tearDownClass(cls):
cls.stub_dir.cleanup()
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
@ -31,7 +51,7 @@ class RunScriptTest(unittest.TestCase):
def build(self):
self.exe.parent.mkdir(parents=True)
shutil.copy(STAND_IN, self.exe)
shutil.copy(self.stub_exe, self.exe)
def run_script(self, output):
result = subprocess.run(

View File

@ -9,6 +9,14 @@ param(
# when the renderer has not been built.
$ErrorActionPreference = 'Continue'
$root = Split-Path -Parent $PSScriptRoot
function Refuse-Output([string]$Why) {
Write-Output "-Output $Output $Why; not deleting it. Pass an empty folder or a previous run's output folder."
Write-Output 'EXITCODE 2'
exit 2
}
if ($Output.Length -gt 0 -and [string]::IsNullOrWhiteSpace($Output)) { Refuse-Output 'is blank' }
if ([string]::IsNullOrEmpty($Output)) { $Output = Join-Path $root 'out/run1' }
$exe = Join-Path $root 'build/Release/conform_native.exe'
if (-not (Test-Path -LiteralPath $exe -PathType Leaf)) {
@ -17,18 +25,15 @@ if (-not (Test-Path -LiteralPath $exe -PathType Leaf)) {
exit 1
}
function Refuse-Output([string]$Why) {
Write-Output "-Output $Output $Why; not deleting it. Pass an empty folder or a previous run's output folder."
Write-Output 'EXITCODE 2'
exit 2
}
if (Test-Path -LiteralPath $Output) {
$item = Get-Item -LiteralPath $Output -Force
if (-not $item.PSIsContainer) { Refuse-Output 'is a file' }
# A junction or symbolic link: a recursive Remove-Item on it can delete the contents of the folder it points to.
if ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) { Refuse-Output 'is a link or junction' }
if ($null -eq $item.Parent) { Refuse-Output 'is a drive root' }
if ([IO.Path]::GetFullPath($item.FullName).TrimEnd('\', '/') -ieq [IO.Path]::GetFullPath($root).TrimEnd('\', '/')) {
Refuse-Output 'is the native conformance folder'
}
$foreign = @(Get-ChildItem -LiteralPath $item.FullName -Force |
Where-Object { $_.PSIsContainer -or -not ($_.Name -eq 'manifest.json' -or $_.Extension -eq '.png') })
if ($foreign.Count -gt 0) {
@ -38,4 +43,6 @@ if (Test-Path -LiteralPath $Output) {
Remove-Item -LiteralPath $item.FullName -Recurse -Force
}
& $exe $Output @Extra
Write-Output "EXITCODE $LASTEXITCODE"
$rc = $LASTEXITCODE
Write-Output "EXITCODE $rc"
exit $rc