Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 32 additions & 2 deletions runtime/test/check_device_filter_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,12 @@
python -I check_device_filter_tools.py <vk_descriptor_bench> <vk_sandbox> <work dir>

Exit 0 when both tools refuse the filter, 1 when one does not or when the device list fails for another reason, and
77 (skip) on a machine with no Vulkan loader, driver or device, where no tool can choose one. Standard library only.
77 (skip) on a machine with no Vulkan loader, driver or device, where no tool can choose one, or with no wine to
run the cross-compiled tools at all (the Windows build of this tree on Linux). Standard library only.
"""
import os
import re
import shutil
import struct
import subprocess
import sys
Expand All @@ -19,8 +21,31 @@
UNSUPPORTED = 77


def is_pe(path):
"""True when `path` is a PE executable (its MZ header)."""
if not os.path.isfile(path):
return False
try:
with open(path, "rb") as handle:
return handle.read(2) == b"MZ"
except OSError:
return False


def launch_runner(path):
"""The argv that starts the harness at `path`: ["wine"] for a PE executable on a host that cannot run one,
[] to run it as-is. The Windows tree of this repo is cross-compiled on Linux (docs/testing.md), so the tools
this checker is pointed at are PE executables there; they go through the wine that runs the suite, the same
WINE override scripts/run_wine_tests.py takes, else the wine on PATH."""
if os.name == "nt" or not is_pe(path):
return []
wine = os.environ.get("WINE") or shutil.which("wine")
return [wine] if wine else []


def run(cmd, env=None):
p = subprocess.run(cmd, capture_output=True, text=True, errors="replace", env=env, timeout=120)
p = subprocess.run(launch_runner(cmd[0]) + cmd, capture_output=True, text=True, errors="replace", env=env,
timeout=120)
return p.returncode, p.stdout + p.stderr


Expand All @@ -43,6 +68,11 @@ def main(argv):
return 2
bench, sandbox, work = argv[1:]
os.makedirs(work, exist_ok=True)
# The cross build's tools cannot run at all without wine: the machine cannot judge them, as when it has no
# Vulkan device.
if os.name != "nt" and is_pe(bench) and not launch_runner(bench):
print(f"SKIP: {bench} is a PE executable and no wine (WINE or PATH) was found to run it")
return UNSUPPORTED

# The device list ignores the filter, so it shows whether there is any device to choose from.
plain = {k: v for k, v in os.environ.items() if k != "LEONIDA_VK_DEVICE"}
Expand Down
107 changes: 107 additions & 0 deletions tests/test_check_device_filter_tools.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
"""check_device_filter_tools.py runs the cross build's PE harnesses through wine.

On Linux the Windows build's vk_descriptor_bench and vk_sandbox are PE executables: the checker used to start
them directly, so subprocess raised ``OSError: [Errno 8] Exec format error`` and the ctest entry
``vk_device_filter_tools`` failed wherever it could have said anything at all. This test drives the checker with
fake tools and a stub wine, without a Windows build or a Vulkan device.

python -I tests/test_check_device_filter_tools.py
"""
import contextlib
import importlib.util
import io
import os
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
from unittest import mock

ROOT = Path(__file__).resolve().parents[1]
CHECK = ROOT / "runtime" / "test" / "check_device_filter_tools.py"

if __name__ == "__main__" and __package__ is None:
sys.path.insert(0, str(ROOT))


def load_check():
spec = importlib.util.spec_from_file_location("check_device_filter_tools", CHECK)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module


class CheckDeviceFilterToolsTests(unittest.TestCase):
def setUp(self):
self.directory = tempfile.TemporaryDirectory()
self.addCleanup(self.directory.cleanup)
self.check = load_check()

def tool(self, name, header):
path = Path(self.directory.name) / name
path.write_bytes(header + b"\x00" * 64)
return str(path)

def test_a_pe_on_a_non_windows_host_goes_through_wine(self):
exe = self.tool("bench.exe", b"MZ")
env = {"WINE": "stub-wine"}
with mock.patch.object(os, "name", "posix"), mock.patch.dict(os.environ, env):
self.assertEqual(self.check.launch_runner(exe), ["stub-wine"])

def test_wine_comes_from_path_when_wine_is_not_set(self):
exe = self.tool("bench.exe", b"MZ")
with mock.patch.object(os, "name", "posix"), \
mock.patch.dict(os.environ, {}, clear=True), \
mock.patch.object(self.check.shutil, "which", lambda name: "/usr/bin/stub-wine"):
self.assertEqual(self.check.launch_runner(exe), ["/usr/bin/stub-wine"])

def test_native_binaries_and_windows_hosts_run_the_tool_directly(self):
elf = self.tool("harness", b"\x7fELF")
exe = self.tool("bench.exe", b"MZ")
with mock.patch.dict(os.environ, {"WINE": "stub-wine"}):
self.assertEqual(self.check.launch_runner(elf), []) # this host runs it as-is
self.assertEqual(self.check.launch_runner("nonexistent"), [])
with mock.patch.object(os, "name", "nt"), mock.patch.dict(os.environ, {"WINE": "stub-wine"}):
self.assertEqual(self.check.launch_runner(exe), []) # Windows runs a PE as-is

def invoke(self, bench, sandbox, work):
"""main() through a recorder that stands in for the harnesses: the device list answers the bench, a
filtered run names the filter and fails, as a harness that refuses the filter does."""
seen = []

def fake_run(cmd, env=None, **kwargs):
seen.append(cmd)
if "--list-devices" in cmd:
return subprocess.CompletedProcess(cmd, 0, stdout="[0] stub gpu\n", stderr="")
return subprocess.CompletedProcess(
cmd, 1, stdout="", stderr=f"LEONIDA_VK_DEVICE={self.check.FILTER}: no GPU matches the filter\n")

out = io.StringIO()
with mock.patch.object(self.check.subprocess, "run", fake_run), contextlib.redirect_stdout(out):
code = self.check.main(["check", bench, sandbox, work])
return code, seen, out.getvalue()

def test_pe_tools_are_launched_through_wine(self):
bench, sandbox = self.tool("bench.exe", b"MZ"), self.tool("sandbox.exe", b"MZ")
work = str(Path(self.directory.name) / "work")
with mock.patch.object(os, "name", "posix"), mock.patch.dict(os.environ, {"WINE": "stub-wine"}):
code, seen, output = self.invoke(bench, sandbox, work)
self.assertEqual(code, 0, output)
for cmd in seen:
self.assertEqual(cmd[0], "stub-wine", f"the tool was not started through wine: {cmd}")

def test_no_wine_for_pe_tools_is_a_skip_not_a_crash(self):
bench, sandbox = self.tool("bench.exe", b"MZ"), self.tool("sandbox.exe", b"MZ")
work = str(Path(self.directory.name) / "work")
with mock.patch.object(os, "name", "posix"), \
mock.patch.dict(os.environ, {}, clear=True), \
mock.patch.object(self.check.shutil, "which", lambda name: None):
code, seen, output = self.invoke(bench, sandbox, work)
self.assertEqual(code, 77, output)
self.assertEqual(seen, [])
self.assertIn("no wine", output)


if __name__ == "__main__":
unittest.main()
Loading