diff --git a/tests/test_amd_swizzle.py b/tests/test_amd_swizzle.py index bd7f86ce5c..8ea62dac6c 100644 --- a/tests/test_amd_swizzle.py +++ b/tests/test_amd_swizzle.py @@ -6,6 +6,7 @@ import os import pathlib import sys +import subprocess import tempfile import types import unittest @@ -23,7 +24,7 @@ try: import amd_swizzle as A # noqa: E402 - HAVE_NUMPY = True + HAVE_NUMPY = A.np is not None except ModuleNotFoundError as e: if e.name != "numpy": raise @@ -39,6 +40,26 @@ def needs_numpy(fn): return fn + + +def _numpy_visible_to_the_tool() -> bool: + """Whether the tool itself can import numpy: it runs with -I, which hides the user site, and this process does + not. The two disagree when numpy came from `pip install --user`, which is exactly when the gate matters.""" + probe = subprocess.run([sys.executable, "-I", "-c", "import numpy"], capture_output=True) + return probe.returncode == 0 + + +needs_numpy_in_subprocess = (pytest.mark.skipif(not _numpy_visible_to_the_tool(), + reason="the tool runs with -I, which cannot see this numpy") + if pytest is not None else lambda fn: fn) +needs_pillow_in_subprocess = ( + pytest.mark.skipif( + subprocess.run([sys.executable, "-I", "-c", "from PIL import Image"], capture_output=True).returncode != 0, + reason="the tool runs with -I, which cannot import Pillow", + ) if pytest is not None else lambda fn: fn +) + + def table(name, rows): body = "\n".join(" {" + ", ".join(r) + ", }, // " + str(i) for i, r in enumerate(rows)) return f"const UINT_64 GFX10_SW_PATTERN_{name}[][{len(rows[0])}] =\n{{\n{body}\n}};\n" @@ -167,6 +188,7 @@ def _run_with_save_side_effect(self, tmp, out_name, side_effect): fake_tables = {"GFX10_SW_64K_S_PATINFO": [(0, 0, 0, 0, 0, "1 pipes 8 bpe")]} with mock.patch.dict(sys.modules, {"PIL": fake_pil, "PIL.Image": fake_pil_image}), \ + mock.patch.object(self.mod, "_require_numpy"), \ mock.patch.object(self.mod, "load", return_value=({}, fake_tables)), \ mock.patch.object(self.mod, "equation", return_value=[]), \ mock.patch.object(self.mod, "detile", return_value=fake_lin), \ @@ -256,6 +278,8 @@ def test_uncompressed_feature_uses_raw_rgb_bytes(): (2, bytes((17, 33, 63, 94, 129, 159, 245, 200)), [(17, 33, 0), (63, 94, 0), (129, 159, 0), (245, 200, 0)]), ], ids=["r8", "rg8"]) @needs_numpy +@needs_numpy_in_subprocess +@needs_pillow_in_subprocess def test_cli_previews_uncompressed_r8_and_rg8( tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch, bpe: int, texels: bytes, pixels: list[tuple[int, int, int]], ) -> None: @@ -287,6 +311,7 @@ def test_cli_previews_uncompressed_r8_and_rg8( @needs_numpy +@needs_numpy_in_subprocess def test_cli_detiles_4k_tables_with_4k_blocks(): # A 128x128 RGBA gradient tiled in 4 KB blocks (32x32 elements, row-major). The same pattern entry under # a 64K table name must not be picked by --modes 4K, and the 4K table must detile with 12-bit, 4 KB blocks. @@ -325,6 +350,8 @@ def test_cli_detiles_4k_tables_with_4k_blocks(): @needs_numpy +@needs_numpy_in_subprocess +@needs_pillow_in_subprocess def test_preview_keeps_partial_bc_blocks(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: import struct @@ -408,6 +435,7 @@ def test_rejects_offset_past_the_end(tmp_path, monkeypatch): assert "past the end" in result.stderr, result.stderr +@needs_numpy_in_subprocess def test_reports_when_no_pattern_matches(tmp_path, monkeypatch): # Before: a --modes value that matches no table printed nothing and still exited 0. synthetic_case(tmp_path, monkeypatch) @@ -433,6 +461,8 @@ def test_reports_a_missing_or_malformed_header(tmp_path, monkeypatch): @needs_numpy +@needs_numpy_in_subprocess +@needs_pillow_in_subprocess def test_a_valid_run_still_succeeds(tmp_path, monkeypatch): synthetic_case(tmp_path, monkeypatch) result = cli(tmp_path, "--width", "4", "--height", "4", "--out", str(tmp_path / "out.png")) diff --git a/tools/amd_swizzle.py b/tools/amd_swizzle.py index 5f0cd42f0e..9096049b56 100644 --- a/tools/amd_swizzle.py +++ b/tools/amd_swizzle.py @@ -16,7 +16,20 @@ import re import sys -import numpy as np +# numpy is imported late on purpose: argument and header validation must report their own errors on a machine where +# numpy is missing or hidden, and only the computation needs it. +try: + import numpy as np +except ModuleNotFoundError as exc: + if exc.name != "numpy": + raise + np = None + + +def _require_numpy(): + """Exits with the actionable message when the computation needs numpy and it is not importable.""" + if np is None: + raise SystemExit("ERROR: amd_swizzle.py needs numpy (python -m pip install numpy)") HEADER = os.environ.get("AMD_SWIZZLE_HEADER", r"\mesa-addrlib\gfx10SwizzlePattern.h") BPE_INDEX = {1: 0, 2: 1, 4: 2, 8: 3, 16: 4} @@ -241,6 +254,7 @@ def main(argv=None): except (AttributeError, ValueError) as e: print(f"ERROR: {HEADER!r} does not look like addrlib's gfx10SwizzlePattern.h ({e})", file=sys.stderr) return 2 + _require_numpy() # every check above must report its own error without numpy # BC formats cover 4x4 pixels per element; uncompressed 1/2/4 bpe formats have one pixel per element. block = 4 if a.bpe in (8, 16) else 1 wb = (a.width + block - 1) // block