"""CPU checks for tools/image_fuzz.py: the oracle, the texel mapping and the generated shader, no GPU. The GPU side (vk_image_fuzz, rdna2spirv.py) is what the fuzzer compares against; these tests make sure the oracle it compares with is right, so a mismatch is the translator's and not the fuzzer's. """ import json import os from pathlib import Path import random import signal import struct import subprocess import sys import pytest HERE = os.path.dirname(os.path.abspath(__file__)) ROOT = os.path.dirname(HERE) sys.path.insert(0, os.path.join(ROOT, "tools")) import image_fuzz as imf # noqa: E402 def test_empty_format_selection_is_a_usage_error(tmp_path): work = tmp_path / "work" result = subprocess.run([sys.executable, "-I", imf.__file__, "--formats", " , ", "--work", str(work)], capture_output=True, text=True, timeout=60) assert result.returncode == 2, result.stderr assert "--formats must select at least one format" in result.stderr assert "Traceback" not in result.stderr assert not work.exists() def test_work_that_is_a_file_is_a_usage_error(tmp_path): work = tmp_path / "work.txt" work.write_text("keep me", encoding="utf-8") result = subprocess.run([sys.executable, "-I", imf.__file__, "--formats", "R8G8B8A8_UNORM", "--programs", "1", "--work", str(work)], capture_output=True, text=True, timeout=60) assert result.returncode == 2, result.stderr assert "ERROR: --work is not a folder" in result.stderr assert "Traceback" not in result.stderr assert work.read_text(encoding="utf-8") == "keep me" def test_work_under_a_file_is_a_usage_error(tmp_path): blocker = tmp_path / "blocker.txt" blocker.write_text("x", encoding="utf-8") result = subprocess.run([sys.executable, "-I", imf.__file__, "--formats", "R8G8B8A8_UNORM", "--programs", "1", "--work", str(blocker / "work")], capture_output=True, text=True, timeout=60) assert result.returncode == 2, result.stderr assert "ERROR: --work is not a folder" in result.stderr assert "Traceback" not in result.stderr assert blocker.read_text(encoding="utf-8") == "x" def test_work_that_is_a_dangling_symlink_is_a_usage_error(tmp_path): link = tmp_path / "link" try: os.symlink(tmp_path / "missing", link, target_is_directory=True) except (OSError, NotImplementedError): pytest.skip("cannot create a symlink here") result = subprocess.run([sys.executable, "-I", imf.__file__, "--formats", "R8G8B8A8_UNORM", "--programs", "1", "--work", str(link)], capture_output=True, text=True, timeout=60) assert result.returncode == 2, result.stderr assert "ERROR: --work is not a folder" in result.stderr assert "Traceback" not in result.stderr def test_format_codes_match_the_translator_table(): with open(os.path.join(imf.TOOLS, "gfx10_formats.json"), encoding="utf-8") as f: by_name = {name: int(code) for code, name in json.load(f).items()} gfx10_names = { "R8G8B8A8_UNORM": "GFX10_FORMAT_8_8_8_8_UNORM", "R16G16B16A16_SFLOAT": "GFX10_FORMAT_16_16_16_16_FLOAT", "R32G32B32A32_SFLOAT": "GFX10_FORMAT_32_32_32_32_FLOAT", "R32_SFLOAT": "GFX10_FORMAT_32_FLOAT", "R8G8B8A8_UINT": "GFX10_FORMAT_8_8_8_8_UINT", "R8G8B8A8_SINT": "GFX10_FORMAT_8_8_8_8_SINT", } assert set(gfx10_names) == set(imf.FORMATS) for name, (_, code, bpp, model) in imf.FORMATS.items(): assert by_name[gfx10_names[name]] == code, name assert bpp in (4, 8, 16) and model in ("unorm8", "half4", "float4", "float1", "uint8", "sint8"), name def test_unorm_oracle_divides_by_255(): texels = bytes([0, 1, 127, 255, 10, 20, 30, 40]) got = imf.oracle("R8G8B8A8_UNORM", texels, 2, 1) assert got[0] == [0.0, imf.f32(1 / 255.0), imf.f32(127 / 255.0), 1.0] assert got[1] == [imf.f32(v / 255.0) for v in (10, 20, 30, 40)] def test_half_oracle_reads_four_binary16(): wanted = [-2.0, -0.0, 0.5, 65504.0] texels = b"".join(struct.pack(" None: work = tmp_path / "work" work.mkdir() build = tmp_path / "build" build.mkdir() harness = build / (imf.HARNESS + (".exe" if os.name == "nt" else "")) harness.touch() monkeypatch.setattr(imf, "assemble", lambda *_args: None) def run(cmd: list[str], **_kwargs: object) -> subprocess.CompletedProcess[str]: if cmd[0] == str(harness): return subprocess.CompletedProcess(cmd, 77, "unsupported: no Vulkan 1.2 device", "") out = work / "spirv" out.mkdir() (out / "vs_ids.spv").touch() return subprocess.CompletedProcess(cmd, 0, "2 shaders: 1 translated, 1 pass spirv-val\n 1 s_trap", "") monkeypatch.setattr(imf.subprocess, "run", run) with pytest.raises(SystemExit, match=r"(?s)ps_image_load\.spv.*s_trap"): imf.run_case("R8G8B8A8_UNORM", 4, 4, random.Random(1), str(work), str(build), False, False) def test_unsupported_without_a_reason_line_still_skips(monkeypatch, tmp_path, capsys): assert run_case_with_harness_result(monkeypatch, tmp_path, 77, "device: X\n") is None assert "SKIP (the device does not support the set)" in capsys.readouterr().out def test_a_harness_error_is_a_failure_not_a_skip(monkeypatch, tmp_path, capsys): assert run_case_with_harness_result(monkeypatch, tmp_path, 1, "device: X\nvkCreateDevice failed\n") is False out = capsys.readouterr().out assert "FAIL (vk_image_fuzz exit 1: vkCreateDevice failed)" in out and "SKIP" not in out assert " device: X" in out # the earlier lines are printed too def test_a_crash_names_the_signal_and_prints_stderr(monkeypatch, tmp_path, capsys): # #1429: ANV segfaulted in vkCreateGraphicsPipelines and the fuzzer printed only "FAIL (harness error)". stderr = "validation: pipeline layout ok\ncreating graphics pipeline\n" assert run_case_with_harness_result(monkeypatch, tmp_path, -signal.SIGSEGV, "device: X\n", stderr) is False out = capsys.readouterr().out assert "FAIL (vk_image_fuzz killed by SIGSEGV: creating graphics pipeline)" in out assert " vk_image_fuzz stderr:\n validation: pipeline layout ok\n creating graphics pipeline\n" in out assert "harness error" not in out def test_a_silent_crash_still_says_how_the_harness_ended(monkeypatch, tmp_path, capsys): assert run_case_with_harness_result(monkeypatch, tmp_path, 0xC0000005, "") is False out = capsys.readouterr().out assert "FAIL (vk_image_fuzz exit 0xc0000005 (access violation), no output)" in out def test_a_long_stderr_prints_only_its_tail(monkeypatch, tmp_path, capsys): stderr = "".join(f"line {i}\n" for i in range(50)) assert run_case_with_harness_result(monkeypatch, tmp_path, 3, "", stderr) is False out = capsys.readouterr().out assert f"stderr (last {imf.STDERR_TAIL} of 50 lines):" in out assert " line 49" in out and f" line {50 - imf.STDERR_TAIL}\n" in out assert f" line {49 - imf.STDERR_TAIL}\n" not in out @pytest.mark.parametrize("returncode,want", [ (1, "exit 1"), (2, "exit 2"), (-signal.SIGABRT, "killed by SIGABRT"), (-99, "killed by signal 99"), (0xC0000409, "exit 0xc0000409 (stack buffer overrun)"), (0xC0001234, "exit 0xc0001234"), ]) def test_exit_status(returncode, want): assert imf.exit_status(returncode) == want def test_self_test_runs(): r = subprocess.run([sys.executable, "-I", os.path.join(ROOT, "tools", "image_fuzz.py"), "--self-test"], capture_output=True, text=True) assert r.returncode == 0, r.stderr assert "self-test: ok" in r.stdout def build_dir_main_uses(monkeypatch, argv): """The build folder main() hands run_case for `argv`, with run_case stubbed to a pass.""" seen = [] monkeypatch.setattr(imf, "run_case", lambda *args, **_kw: seen.append(args[5]) or True) monkeypatch.setattr(sys, "argv", ["image_fuzz.py", "--programs", "1"] + argv) assert imf.main() == 0 return seen[0] def test_default_build_is_runtime_build_on_every_platform(monkeypatch, tmp_path): # It was runtime/build/linux, which only a Linux build following docs/testing.md has: on Windows (and on Linux # following docs/shader_validation.md) every run stopped with "vk_image_fuzz not found" unless --build was given. monkeypatch.setattr(imf, "find_test_program", lambda build, name: None) assert build_dir_main_uses(monkeypatch, ["--work", str(tmp_path)]) == os.path.join(imf.ROOT, "runtime", "build") def test_visual_studio_config_subfolder_is_found(monkeypatch, tmp_path): build = tmp_path / "build" (build / "RelWithDebInfo").mkdir(parents=True) (build / "RelWithDebInfo" / (imf.HARNESS + (".exe" if os.name == "nt" else ""))).touch() got = build_dir_main_uses(monkeypatch, ["--build", str(build), "--work", str(tmp_path / "w")]) assert got == str(build / "RelWithDebInfo") def test_translate_forwards_pc_tail_ubo(monkeypatch, tmp_path): cmds = [] def fake_run(cmd, **_kw): cmds.append(list(cmd)) out = cmd[cmd.index("--out") + 1] # translate() now checks the two programs were emitted os.makedirs(out, exist_ok=True) for name in ("vs_ids.spv", "ps_image_load.spv"): open(os.path.join(out, name), "wb").close() return subprocess.CompletedProcess(cmd, 0, "", "") monkeypatch.setattr(imf.subprocess, "run", fake_run) imf.translate(str(tmp_path)) imf.translate(str(tmp_path), pc_tail=True) assert "--pc-tail-ubo" not in cmds[0] assert "--pc-tail-ubo" in cmds[1] def test_run_case_passes_pc_tail_to_translator_and_harness(monkeypatch, tmp_path): build = tmp_path / "build" build.mkdir() (build / (imf.HARNESS + (".exe" if os.name == "nt" else ""))).touch() seen_translate = [] seen_env = [] monkeypatch.setattr(imf, "assemble", lambda *_args: None) monkeypatch.setattr(imf, "translate", lambda work, pc_tail=False: seen_translate.append(pc_tail) or str(tmp_path / "spirv")) def fake_run(cmd, **kw): seen_env.append(kw.get("env")) return subprocess.CompletedProcess(cmd, 77, "unsupported: test\n", "") monkeypatch.setattr(imf.subprocess, "run", fake_run) imf.run_case("R8G8B8A8_UNORM", 4, 4, random.Random(1), str(tmp_path), str(build), False, False, pc_tail=True) assert seen_translate == [True] assert seen_env[0]["LEONIDA_PC_TAIL_UBO"] == "1" def test_main_enables_pc_tail_ubo_from_flag_or_env(monkeypatch, tmp_path): for argv, env_val, want in ( ([], "", False), (["--pc-tail-ubo"], "", True), ([], "1", True), ([], "true", True), ([], "0", False), ): seen = [] monkeypatch.setenv("LEONIDA_PC_TAIL_UBO", env_val) monkeypatch.setattr(imf, "run_case", lambda *args, **kw: seen.append(kw.get("pc_tail", False)) or True) monkeypatch.setattr(sys, "argv", ["image_fuzz.py", "--programs", "1", "--work", str(tmp_path)] + argv) assert imf.main() == 0 assert seen == [want], (argv, env_val)