Files
mandy/tests/test_ctest_registration.py

342 lines
16 KiB
Python

"""Every test executable the runtime builds must be registered with ctest.
``add_executable(foo_test ...)`` without an ``add_test(... COMMAND foo_test)`` builds
the test but never runs it -- in ``ctest``, in the Windows runtime job or under Wine.
This happened to ``d3d12_indirect_rt_test``; the only intentional exception is
``d3d12_clear_test`` (see the comment next to its target in runtime/CMakeLists.txt).
"""
import os
import re
import tempfile
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
CMAKE = Path(os.environ.get("LEONIDA_RUNTIME_CMAKE", str(ROOT / "runtime" / "CMakeLists.txt")))
SOURCE = Path(os.environ.get("LEONIDA_RUNTIME_TEST_SOURCE",
str(ROOT / "runtime" / "test" / "d3d12_indirect_rt_test.cpp")))
# d3d12_clear_test is deliberately run by hand until #521's tie rounding lands.
# vk_compute_test, vk_sampler_test, and vk_store_test are shader-runner tools invoked by scripts/run_gpu_tests.py.
NOT_IN_CTEST = {"d3d12_clear_test", "vk_compute_test", "vk_sampler_test", "vk_store_test"}
# Every runtime/test/*_test.cpp on disk must be wired into runtime/CMakeLists.txt.
UNWIRED_TEST_SOURCES = set()
def strip_cmake_comments(text):
"""Replace CMake line and bracket comments with whitespace, leaving arguments intact."""
# Match escaped characters, quoted arguments and bracket arguments before line comments so a
# literal # in those arguments is not mistaken for the start of a comment. Bracket comments
# and arguments can contain closing brackets with a different number of '=' characters.
tokens = re.compile(r'\\.|"(?:\\.|[^"\\])*"|#?\[(?P<eq>=*)\[.*?\](?P=eq)\]|#[^\r\n]*', re.S)
def replace(match):
token = match.group()
return re.sub(r"[^\r\n]", " ", token) if token.startswith("#") else token
return tokens.sub(replace, text)
def expand_cmake_foreach(text):
"""Expand literal-item foreach(...)/endforeach() blocks in comment-stripped CMake text."""
pattern = re.compile(r"\b(foreach|endforeach)\s*\(([^)]*)\)", re.IGNORECASE | re.S)
stack = [(None, [])]
pos = 0
for match in pattern.finditer(text):
stack[-1][1].append(text[pos:match.start()])
pos = match.end()
kind = match.group(1).lower()
if kind == "foreach":
stack.append((match.group(2), []))
continue
if len(stack) == 1:
stack[0][1].append(match.group(0))
continue
header, body_parts = stack.pop()
body = "".join(body_parts)
args = re.findall(r'"(?:\\.|[^"\\])*"|\S+', header)
if not args:
stack[-1][1].append(body)
continue
var, rest = args[0], args[1:]
if not re.fullmatch(r"[A-Za-z0-9_]+", var):
stack[-1][1].append(body)
continue
upper_rest = [tok.upper() for tok in rest]
if upper_rest and upper_rest[0] == "RANGE":
stack[-1][1].append(body)
continue
if upper_rest and upper_rest[0] == "IN":
if len(upper_rest) >= 2 and upper_rest[1] == "ITEMS":
items = [tok.strip('"') for tok in rest[2:]]
else:
stack[-1][1].append(body)
continue
else:
items = [tok.strip('"') for tok in rest]
placeholder = f"${{{var}}}"
for item in items:
stack[-1][1].append(body.replace(placeholder, item))
stack[-1][1].append(text[pos:])
while len(stack) > 1:
_, body_parts = stack.pop()
stack[-1][1].extend(body_parts)
return "".join(stack[0][1])
def referenced_test_sources(text):
"""Relative ``test/.../*_test.cpp`` paths wired into build targets in CMakeLists.txt."""
expanded = expand_cmake_foreach(strip_cmake_comments(text))
sources = set()
for match in re.finditer(r"\b(?:add_executable|add_library|target_sources)\s*\(([^)]*)\)",
expanded, re.IGNORECASE | re.S):
for src in re.findall(r"(?:^|[\s\"'/])(test/[A-Za-z0-9_./-]*_test\.cpp)\b", match.group(1)):
sources.add(src)
return sources
def disk_test_sources(runtime_dir):
"""Relative ``test/.../*_test.cpp`` paths present on disk under ``runtime_dir / 'test'``."""
test_dir = Path(runtime_dir) / "test"
if not test_dir.is_dir():
return set()
return {p.relative_to(runtime_dir).as_posix() for p in test_dir.rglob("*_test.cpp")}
def built_test_executables(text):
expanded = expand_cmake_foreach(strip_cmake_comments(text))
return {name for name in re.findall(r"add_executable\(\s*([A-Za-z0-9_]+)", expanded)
if name.endswith("_test")}
def registered_commands(text):
# add_test may span lines, e.g. add_test(NAME x\n COMMAND foo_test ...).
expanded = expand_cmake_foreach(strip_cmake_comments(text))
return set(re.findall(r"add_test\([^)]*?\bCOMMAND\s+\"?([A-Za-z0-9_]+)", expanded, re.S))
class CTestRegistrationTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.cmake = strip_cmake_comments(CMAKE.read_text(encoding="utf-8"))
def test_all_test_executables_have_an_add_test(self):
missing = built_test_executables(self.cmake) - registered_commands(self.cmake) - NOT_IN_CTEST
self.assertEqual(missing, set(), f"built but never run by ctest: {sorted(missing)}")
def test_the_exception_is_still_the_only_one(self):
# An allowlist that grows unnoticed is how this bug happens again.
self.assertEqual(
NOT_IN_CTEST & built_test_executables(self.cmake),
{"d3d12_clear_test", "vk_compute_test", "vk_sampler_test", "vk_store_test"},
)
def test_all_test_sources_on_disk_are_wired_in_cmake(self):
on_disk = disk_test_sources(ROOT / "runtime")
self.assertTrue(on_disk, "expected runtime/test/*_test.cpp files on disk")
wired = referenced_test_sources(self.cmake)
unwired = on_disk - wired - UNWIRED_TEST_SOURCES
self.assertEqual(
unwired,
set(),
f"runtime/test/*_test.cpp files not wired in runtime/CMakeLists.txt: {sorted(unwired)}",
)
def test_referenced_test_sources_handles_foreach_and_ignores_comments(self):
text = (
"add_executable(direct_test test/direct_test.cpp)\n"
"target_sources(direct_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/test/extra_test.cpp)\n"
"foreach(_context_test alpha beta)\n"
" add_executable(${_context_test}_test test/${_context_test}_test.cpp)\n"
"endforeach()\n"
"foreach(target IN ITEMS gamma_test delta_test)\n"
" add_executable(${target} test/${target}.cpp)\n"
"endforeach()\n"
"# add_executable(commented_test test/commented_test.cpp)\n"
'message(STATUS "test/message_only_test.cpp")\n'
)
self.assertEqual(
referenced_test_sources(text),
{
"test/direct_test.cpp",
"test/extra_test.cpp",
"test/alpha_test.cpp",
"test/beta_test.cpp",
"test/gamma_test.cpp",
"test/delta_test.cpp",
},
)
with tempfile.TemporaryDirectory() as tmp:
tdir = Path(tmp) / "test"
tdir.mkdir()
(tdir / "direct_test.cpp").write_text("int main() { return 0; }\n", encoding="utf-8", newline="\n")
(tdir / "orphan_test.cpp").write_text("int main() { return 0; }\n", encoding="utf-8", newline="\n")
self.assertEqual(
disk_test_sources(Path(tmp)) - referenced_test_sources(text),
{"test/orphan_test.cpp"},
)
def test_foreach_built_test_without_add_test_is_caught(self):
text = (
"foreach(x IN ITEMS mandy_registration_probe)\n"
" add_executable(${x}_test test/${x}_test.cpp)\n"
"endforeach()\n"
"foreach(y alpha beta)\n"
" add_executable(${y}_test test/${y}_test.cpp)\n"
" add_test(NAME ${y} COMMAND ${y}_test)\n"
"endforeach()\n"
)
self.assertEqual(
built_test_executables(text) - registered_commands(text),
{"mandy_registration_probe_test"},
)
def test_comments_do_not_build_or_register_tests(self):
text = (
"add_executable(registered_test test/registered_test.cpp)\n"
"add_test(NAME registered COMMAND registered_test)\n"
"add_executable(orphan_test test/orphan_test.cpp)\n"
"# add_test(NAME orphan COMMAND orphan_test)\n"
"# add_executable(disabled_test test/disabled_test.cpp)\n"
"#[=[ Block comment containing ]]\n"
"add_test(NAME orphan COMMAND orphan_test)\n"
"add_executable(blocked_test test/blocked_test.cpp)\n"
"]=]\n"
)
self.assertEqual(built_test_executables(text), {"registered_test", "orphan_test"})
self.assertEqual(registered_commands(text), {"registered_test"})
def test_comments_inside_multiline_commands_are_ignored(self):
text = (
"add_executable(\n"
" # formerly old_test\n"
" real_test test/real_test.cpp)\n"
"add_test(NAME real\n"
" # COMMAND old_test\n"
" #[[ COMMAND old_test ]]\n"
" COMMAND real_test)\n"
)
self.assertEqual(built_test_executables(text), {"real_test"})
self.assertEqual(registered_commands(text), {"real_test"})
def test_hashes_inside_arguments_are_not_comments(self):
text = ('message("literal # with an escaped \\"quote\\"")\n'
'message([=[literal # and ]] inside a bracket argument]=])\n'
'message(escaped\\#hash)\n')
self.assertEqual(strip_cmake_comments(text), text)
def test_commented_skip_code_does_not_enable_the_skip_check(self):
text = ("add_executable(a_test test/a_test.cpp)\nadd_test(NAME a COMMAND a_test)\n"
"# set_tests_properties(a PROPERTIES SKIP_RETURN_CODE 77)\n")
with tempfile.TemporaryDirectory() as tmp:
src = Path(tmp) / "test" / "a_test.cpp"
src.parent.mkdir()
src.write_text('std::printf("SKIP: none\\n");\nreturn 0;\n', encoding="utf-8", newline="\n")
self.assertEqual(whole_test_skips_not_77(text, Path(tmp)), [])
def test_indirect_rt_skips_with_the_ctest_skip_code(self):
self.assertTrue(
"add_test(NAME d3d12_indirect_rt COMMAND d3d12_indirect_rt_test)" in self.cmake,
"d3d12_indirect_rt_test is built but not registered with ctest",
)
self.assertTrue(
"set_tests_properties(d3d12_indirect_rt PROPERTIES SKIP_RETURN_CODE 77)" in self.cmake,
"d3d12_indirect_rt must skip with 77 on a machine without a Vulkan GPU",
)
lines = SOURCE.read_text(encoding="utf-8").splitlines()
skips = []
for i, line in enumerate(lines):
if 'std::printf("SKIP:' in line:
# The path's own return, not a conditional one inside it (a LEONIDA_VK_DEVICE filter that matches
# nothing fails with `if (!filter.empty()) return 1;` just before the skip's `return 77;`).
codes = [int(m) for l in lines[i:i + 7] if "if (" not in l for m in re.findall(r"return (\d+);", l)]
skips.append(codes[0] if codes else None)
# no loader, no ICD, no Vulkan 1.3 GPU -- all three are a ctest SKIP, not a failure.
self.assertEqual(len(skips), 3, f"expected three whole-test SKIP paths, got {len(skips)}")
self.assertEqual(skips, [77, 77, 77], "SKIP paths must return 77 for SKIP_RETURN_CODE 77")
def test_xdxr_postbuild_readback_skips_with_the_ctest_skip_code(self):
self.assertIn(
"add_test(NAME vk_xdxr_postbuild_readback COMMAND vk_xdxr_postbuild_readback_test)",
self.cmake,
"vk_xdxr_postbuild_readback_test is built but not registered with ctest",
)
self.assertIn(
"set_tests_properties(vk_xdxr_postbuild_readback PROPERTIES SKIP_RETURN_CODE 77)",
self.cmake,
"vk_xdxr_postbuild_readback must skip with 77 on a runner without a Vulkan GPU",
)
src = (ROOT / "runtime" / "test" / "vk_xdxr_postbuild_readback_test.cpp").read_text(encoding="utf-8")
lines = src.splitlines()
skips = [
int(m.group(1))
for i, line in enumerate(lines)
if ": skipped (" in line and i + 1 < len(lines)
for m in [re.match(r"\s*return\s+(\d+)\s*;", lines[i + 1])]
if m
]
self.assertEqual(skips, [77], "vk_xdxr_postbuild_readback skip path must return 77")
def test_whole_test_skips_return_the_skip_code(self):
# A test registered with SKIP_RETURN_CODE 77 that prints SKIP and returns 0 is counted as passed although it
# checked nothing: bink_audio_test did that for a movie without audio tracks after #1580.
wrong = whole_test_skips_not_77(self.cmake, ROOT / "runtime")
self.assertEqual(wrong, [], f"SKIP followed by a return code other than 77: {wrong}")
def test_a_named_skip_code_counts_by_its_value(self):
cmake = ("add_executable(a_test test/a_test.cpp)\nadd_test(NAME a COMMAND a_test)\n"
"set_tests_properties(a PROPERTIES SKIP_RETURN_CODE 77)\n")
with tempfile.TemporaryDirectory() as tmp:
src = Path(tmp) / "test" / "a_test.cpp"
src.parent.mkdir()
for value, want in (("77", []), ("0", [("test/a_test.cpp:3", "kSkip")])):
src.write_text(f"constexpr int kSkip = {value};\nstd::printf(\"SKIP: none\\n\");\nreturn kSkip;\n",
encoding="utf-8", newline="\n")
self.assertEqual(whole_test_skips_not_77(cmake, Path(tmp)), want, value)
src.write_text('std::printf("SKIP: none\\n");\nreturn kUnknown;\n', encoding="utf-8", newline="\n")
self.assertEqual(whole_test_skips_not_77(cmake, Path(tmp)), [("test/a_test.cpp:2", "kUnknown")])
def test_host_parity_and_storage_tests_have_timeouts(self):
for test_name in ("dstorage", "dxgi_host_parity", "dxgi_waitable_latency"):
m = re.search(
r"set_tests_properties\(\s*" + test_name + r"\b[^)]*TIMEOUT\s+[1-9]\d*",
self.cmake,
re.S,
)
self.assertIsNotNone(m, f"{test_name} must have an explicit TIMEOUT property")
def whole_test_skips_not_77(cmake_text, runtime_dir):
"""[(source:line, code)] for a SKIP print directly followed by `return N;` (N != 77) in the sources of a test
registered with SKIP_RETURN_CODE 77. A SKIP print with no return right after it skips one section, not the test.
A named code (`return kSkip;`) counts by the value of its `constexpr int` in the same source."""
cmake_text = strip_cmake_comments(cmake_text)
skip_tests = set(re.findall(r"set_tests_properties\(\s*([A-Za-z0-9_]+)\s+PROPERTIES[^)]*SKIP_RETURN_CODE\s+77",
cmake_text))
commands = dict(re.findall(r"add_test\(\s*NAME\s+([A-Za-z0-9_]+)\s+COMMAND\s+\"?([A-Za-z0-9_]+)", cmake_text))
wrong = []
for test in sorted(skip_tests):
exe = commands.get(test)
m = exe and re.search(r"add_executable\(\s*" + re.escape(exe) + r"\b([^)]*)\)", cmake_text)
if not m:
continue
for src in re.findall(r"(test/[A-Za-z0-9_./]+\.cpp)", m.group(1)):
path = runtime_dir / src
if not path.is_file():
continue
text = path.read_text(encoding="utf-8", errors="replace")
named = dict(re.findall(r"\bconstexpr\s+int\s+(\w+)\s*=\s*(\d+)\s*;", text))
lines = text.splitlines()
for i, line in enumerate(lines):
if not re.search(r'(printf|puts)\(\s*"SKIP', line):
continue
after = re.match(r"\s*return\s+(\w+)\s*;", lines[i + 1]) if i + 1 < len(lines) else None
if after and named.get(after.group(1), after.group(1)) != "77":
wrong.append((f"{src}:{i + 2}", after.group(1)))
return wrong
if __name__ == "__main__":
unittest.main()