"""Unit test suite covering make_game.py prerequisite checking, version string parsing, and toolchain detection. python -I tests/test_make_game_preflight.py python -m unittest discover -s tests -v Tests use synthetic manifests, mock environments, and isolated temporary directories so they are deterministic, fast, and contain zero game data. """ from collections import namedtuple import ctypes import functools import io import json import os import re import shutil import subprocess import sys import tempfile import unittest from unittest import mock ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) if ROOT not in sys.path: sys.path.insert(0, ROOT) import make_game # noqa: E402 Usage = namedtuple("Usage", ["total", "used", "free"]) class PreflightTestBase(unittest.TestCase): def assert_fails(self, fn, *args, match=None, **kwargs): stderr_buf = io.StringIO() with mock.patch("sys.stderr", stderr_buf): with self.assertRaises(SystemExit) as ctx: fn(*args, **kwargs) self.assertEqual(ctx.exception.code, 1) err = stderr_buf.getvalue() if match: self.assertIn(match, err) return err class VersionParsingAndMatchingTest(PreflightTestBase): def test_versions_loads_valid_manifest(self): manifests = make_game.versions() self.assertGreaterEqual(len(manifests), 1) v = manifests[0] self.assertIn("title", v) self.assertIn("version", v) self.assertIn("files", v) self.assertIn("expected_exe", v) self.assertEqual(v["version"], "1.0.2.1") self.assertEqual(v["expected_exe"], "game_scarlett_master.exe") def test_version_string_parsing_and_ordering(self): manifests = make_game.versions() parsed = [tuple(map(int, v["version"].split("."))) for v in manifests] self.assertIn((1, 0, 2, 1), parsed) self.assertGreater((1, 0, 2, 1), (1, 0, 2, 0)) self.assertGreater((1, 0, 2, 0), (1, 0, 1, 9)) self.assertGreater((2, 0, 0, 0), (1, 9, 9, 9)) def test_versions_custom_directory_and_json_filtering(self): with tempfile.TemporaryDirectory() as tmp: v1_path = os.path.join(tmp, "b_1.0.0.json") v2_path = os.path.join(tmp, "a_2.0.0.json") txt_path = os.path.join(tmp, "readme.txt") with open(v1_path, "w", encoding="utf-8") as f: json.dump({"title": "Custom B", "version": "1.0.0", "files": {}, "expected_exe": "b.exe"}, f) with open(v2_path, "w", encoding="utf-8") as f: json.dump({"title": "Custom A", "version": "2.0.0", "files": {}, "expected_exe": "a.exe"}, f) with open(txt_path, "w", encoding="utf-8") as f: f.write("ignored") with mock.patch.object(make_game, "VERSIONS", tmp): loaded = make_game.versions() self.assertEqual(len(loaded), 2) # sorted by filename in os.listdir self.assertEqual(loaded[0]["version"], "2.0.0") self.assertEqual(loaded[1]["version"], "1.0.0") def test_match_version_success_on_probes(self): with tempfile.TemporaryDirectory() as tmp: manifest = make_game.versions()[0] for probe_name in make_game.PROBES: size = manifest["files"][probe_name]["size"] probe_path = os.path.join(tmp, probe_name) with open(probe_path, "wb") as f: f.truncate(size) matched = make_game.match_version(tmp) self.assertIsNotNone(matched) self.assertEqual(matched["version"], manifest["version"]) def test_match_version_missing_probe_returns_none(self): with tempfile.TemporaryDirectory() as tmp: manifest = make_game.versions()[0] # Create 2 probes, skip appdata0.rpf for probe_name in ("MicrosoftGame.Config", "Catalog000.bin"): size = manifest["files"][probe_name]["size"] probe_path = os.path.join(tmp, probe_name) with open(probe_path, "wb") as f: f.truncate(size) self.assertIsNone(make_game.match_version(tmp)) def test_match_version_wrong_probe_size_returns_none(self): with tempfile.TemporaryDirectory() as tmp: manifest = make_game.versions()[0] for probe_name in make_game.PROBES: size = manifest["files"][probe_name]["size"] probe_path = os.path.join(tmp, probe_name) with open(probe_path, "wb") as f: f.truncate(size + 1 if probe_name == "MicrosoftGame.Config" else size) self.assertIsNone(make_game.match_version(tmp)) def test_match_version_empty_directory_returns_none(self): with tempfile.TemporaryDirectory() as tmp: self.assertIsNone(make_game.match_version(tmp)) def test_load_version_success(self): with tempfile.TemporaryDirectory() as tmp: manifest = make_game.versions()[0] for probe_name in make_game.PROBES: size = manifest["files"][probe_name]["size"] probe_path = os.path.join(tmp, probe_name) with open(probe_path, "wb") as f: f.truncate(size) loaded = make_game.load_version(tmp) self.assertEqual(loaded["version"], manifest["version"]) def test_load_version_failure_reports_supported_versions(self): with tempfile.TemporaryDirectory() as tmp: err = self.assert_fails(make_game.load_version, tmp, match="This doesn't look like a supported version of the game") self.assertIn("Supported:", err) self.assertIn("1.0.2.1", err) for name in make_game.PROBES: self.assertIn(f"Missing {name}.", err) def test_a_probe_whose_name_differs_only_in_case_is_named(self): with tempfile.TemporaryDirectory() as tmp: manifest = make_game.versions()[0] for probe_name in make_game.PROBES: with open(os.path.join(tmp, probe_name.lower()), "wb") as f: f.truncate(manifest["files"][probe_name]["size"]) if os.path.exists(os.path.join(tmp, "MicrosoftGame.Config")): self.skipTest("case-insensitive file system: the lower-cased names open under the package's") mismatches = make_game.probe_mismatches(tmp, manifest) self.assertIn("Missing MicrosoftGame.Config: there is microsoftgame.config, but file names are " "case-sensitive", mismatches[0]) self.assertIn("Rename it to MicrosoftGame.Config", mismatches[0]) self.assertIn("Missing Catalog000.bin: there is catalog000.bin", mismatches[1]) self.assertEqual(len(mismatches), 2) # appdata0.rpf is lower case in the package too: it matches def test_other_case_ignores_the_exact_name_and_unrelated_files(self): with tempfile.TemporaryDirectory() as tmp: for name in ("Catalog000.bin.bak", "Catalog000.bin"): open(os.path.join(tmp, name), "wb").close() self.assertIsNone(make_game.other_case(tmp, "Catalog000.bin")) self.assertIsNone(make_game.other_case(os.path.join(tmp, "absent"), "Catalog000.bin")) class PartialVersionMatchTest(PreflightTestBase): """A copy that misses a probe file but holds most of one version's manifest is named as an incomplete copy of that version, with what is missing (BUILD-2835). Synthetic manifests and empty files only.""" FILES = { "MicrosoftGame.Config": 12, "Catalog000.bin": 8, "appdata0.rpf": 16, "a.dll": 3, "b.dll": 4, "data/c.rpf": 5, "data/d.rpf": 6, "pack/e/f.rpf": 7, } def setUp(self): self.tmp = tempfile.TemporaryDirectory() self.addCleanup(self.tmp.cleanup) self.manifests = os.path.join(self.tmp.name, "versions") self.game = os.path.join(self.tmp.name, "game") os.makedirs(self.manifests) os.makedirs(self.game) manifest = {"title": "Synthetic package", "version": "9.8.7.6", "expected_exe": "a.exe", "files": {name: {"size": size} for name, size in self.FILES.items()}} with open(os.path.join(self.manifests, "synthetic.json"), "w", encoding="utf-8", newline="\n") as f: json.dump(manifest, f) patcher = mock.patch.object(make_game, "VERSIONS", self.manifests) patcher.start() self.addCleanup(patcher.stop) def write(self, name, size=None): path = os.path.join(self.game, *name.split("/")) os.makedirs(os.path.dirname(path), exist_ok=True) with open(path, "wb") as f: f.truncate(self.FILES[name] if size is None else size) def test_incomplete_copy_names_the_version_and_what_is_missing(self): for name in self.FILES: if name not in ("appdata0.rpf", "data/d.rpf"): self.write(name, 1 if name == "b.dll" else None) err = self.assert_fails(make_game.load_version, self.game, match="incomplete copy of Synthetic package 9.8.7.6") self.assertNotIn("doesn't look like a supported version", err) self.assertIn("5 of 8 manifest files are present with matching sizes", err) self.assertIn("2 file(s) missing (22 bytes)", err) self.assertIn(" missing appdata0.rpf", err) self.assertIn(" missing data/d.rpf", err) self.assertIn(" wrong size b.dll (expected 4 bytes)", err) self.assertNotIn("missing a.dll", err) def test_copy_with_less_than_half_keeps_the_unsupported_message(self): for name in ("MicrosoftGame.Config", "a.dll", "b.dll"): self.write(name) err = self.assert_fails(make_game.load_version, self.game, match="This doesn't look like a supported version of the game") self.assertNotIn("incomplete copy", err) self.assertIn("Missing appdata0.rpf.", err) def test_copy_matching_nothing_keeps_the_unsupported_message(self): with open(os.path.join(self.game, "something_else.bin"), "wb") as f: f.write(b"x") err = self.assert_fails(make_game.load_version, self.game, match="This doesn't look like a supported version of the game") self.assertNotIn("incomplete copy", err) def test_a_folder_in_place_of_a_file_counts_as_missing(self): for name in self.FILES: if name != "appdata0.rpf": self.write(name) os.mkdir(os.path.join(self.game, "appdata0.rpf")) err = self.assert_fails(make_game.load_version, self.game, match="7 of 8 manifest files") self.assertIn(" missing appdata0.rpf", err) def test_a_probe_that_cannot_be_read_is_not_reported_as_missing(self): # A file whose metadata can't be read exists: it is listed apart, as probe_mismatches() does, and the # message does not say to finish a download that is not unfinished. for name in self.FILES: self.write(name) blocked = os.path.join(self.game, "appdata0.rpf") real_stat = os.stat def fake_stat(path, *args, **kwargs): if os.fspath(path) == blocked: raise PermissionError(13, "Permission denied", blocked) return real_stat(path, *args, **kwargs) with mock.patch.object(make_game.os, "stat", fake_stat): err = self.assert_fails(make_game.load_version, self.game, match="7 of 8 manifest files") self.assertIn(" cannot read appdata0.rpf (Permission denied)", err) self.assertNotIn("missing appdata0.rpf", err) self.assertNotIn("file(s) missing", err) self.assertNotIn("incomplete copy", err) self.assertNotIn("Finish the download", err) def test_a_complete_copy_of_another_build_keeps_the_unsupported_message(self): # Every file there, only the probes with other sizes: another package, not an unfinished download. for name in self.FILES: self.write(name, self.FILES[name] + 1 if name in make_game.PROBES else None) err = self.assert_fails(make_game.load_version, self.game, match="This doesn't look like a supported version of the game") self.assertIn("Wrong size for MicrosoftGame.Config (13 bytes, expected 12).", err) self.assertNotIn("incomplete copy", err) self.assertNotIn("Finish the download", err) def test_missing_files_with_matching_probes_still_name_the_incomplete_copy(self): # The probes that are there have their sizes; appdata0.rpf and one archive are missing. for name in self.FILES: if name not in ("appdata0.rpf", "pack/e/f.rpf"): self.write(name) err = self.assert_fails(make_game.load_version, self.game, match="incomplete copy of Synthetic package 9.8.7.6") self.assertIn(" missing appdata0.rpf", err) self.assertIn(" missing pack/e/f.rpf", err) self.assertIn("Finish the download", err) def test_missing_files_and_a_probe_with_another_size_keep_the_unsupported_message(self): # Mixed: files missing, and MicrosoftGame.Config there with another size. The probe size says which package # this is, so another size means another build, whatever else is missing: the old message, with the size. for name in self.FILES: if name not in ("appdata0.rpf", "data/d.rpf"): self.write(name, 99 if name == "MicrosoftGame.Config" else None) err = self.assert_fails(make_game.load_version, self.game, match="This doesn't look like a supported version of the game") self.assertIn("Wrong size for MicrosoftGame.Config (99 bytes, expected 12).", err) self.assertIn("Missing appdata0.rpf.", err) self.assertNotIn("incomplete copy", err) self.assertNotIn("Finish the download", err) def test_a_complete_copy_still_loads(self): for name in self.FILES: self.write(name) self.assertEqual(make_game.load_version(self.game)["version"], "9.8.7.6") class GameCheckTest(PreflightTestBase): def test_check_nonexistent_directory_fails(self): self.assert_fails(make_game.check, "nonexistent_dir_0xdeadbeef", full=False, match="Game folder not found: nonexistent_dir_0xdeadbeef") def test_check_option_reports_each_version_probe_mismatch(self): with tempfile.TemporaryDirectory() as tmp: with open(os.path.join(tmp, "MicrosoftGame.Config"), "wb") as config: config.write(b"test") os.mkdir(os.path.join(tmp, "Catalog000.bin")) manifests = [ {"title": "Synthetic", "version": version, "files": { "MicrosoftGame.Config": {"size": size}, "Catalog000.bin": {"size": 8}, "appdata0.rpf": {"size": 16}, }} for version, size in [("1.0", 6), ("2.0", 10)] ] with mock.patch.object(make_game, "versions", return_value=manifests), \ mock.patch.object(sys, "argv", ["make_game.py", "--check", "--game", tmp]): err = self.assert_fails(make_game.main) self.assertIn("Synthetic 1.0\n Wrong size for MicrosoftGame.Config (4 bytes, expected 6).", err) self.assertIn("Synthetic 2.0\n Wrong size for MicrosoftGame.Config (4 bytes, expected 10).", err) self.assertEqual(err.count("Catalog000.bin is not a regular file."), 2) self.assertEqual(err.count("Missing appdata0.rpf."), 2) def test_check_synthetic_game_all_files_present_with_exe(self): with tempfile.TemporaryDirectory() as tmp: manifest_dir = os.path.join(tmp, "manifests") game_dir = os.path.join(tmp, "game") os.makedirs(manifest_dir) os.makedirs(game_dir) v_info = { "title": "Synthetic Port Test", "version": "9.9.9.9", "expected_exe": "test_game.exe", "files": { "MicrosoftGame.Config": {"size": 16}, "Catalog000.bin": {"size": 32}, "appdata0.rpf": {"size": 64}, "sub/data.bin": {"size": 128}, }, } with open(os.path.join(manifest_dir, "custom.json"), "w", encoding="utf-8") as f: json.dump(v_info, f) for rel, info in v_info["files"].items(): p = os.path.join(game_dir, rel) os.makedirs(os.path.dirname(p), exist_ok=True) with open(p, "wb") as f: f.truncate(info["size"]) exe_p = os.path.join(game_dir, v_info["expected_exe"]) with open(exe_p, "wb") as f: f.truncate(256) stdout_buf = io.StringIO() with mock.patch.object(make_game, "VERSIONS", manifest_dir): with mock.patch("sys.stdout", stdout_buf): res = make_game.check(game_dir, full=False) self.assertEqual(res["version"], "9.9.9.9") self.assertIn("all files present", stdout_buf.getvalue()) self.assertIn("Executable found.", stdout_buf.getvalue()) def test_check_missing_files_fails(self): with tempfile.TemporaryDirectory() as tmp: manifest_dir = os.path.join(tmp, "manifests") game_dir = os.path.join(tmp, "game") os.makedirs(manifest_dir) os.makedirs(game_dir) v_info = { "title": "Synthetic Missing Test", "version": "9.9.9.9", "expected_exe": "test_game.exe", "files": { "MicrosoftGame.Config": {"size": 16}, "Catalog000.bin": {"size": 32}, "appdata0.rpf": {"size": 64}, "missing.bin": {"size": 100}, }, } with open(os.path.join(manifest_dir, "custom.json"), "w", encoding="utf-8") as f: json.dump(v_info, f) for rel in ("MicrosoftGame.Config", "Catalog000.bin", "appdata0.rpf"): p = os.path.join(game_dir, rel) with open(p, "wb") as f: f.truncate(v_info["files"][rel]["size"]) with mock.patch.object(make_game, "VERSIONS", manifest_dir): self.assert_fails(make_game.check, game_dir, full=False, match="1 file(s) missing or different") def test_check_wrong_size_file_fails(self): with tempfile.TemporaryDirectory() as tmp: manifest_dir = os.path.join(tmp, "manifests") game_dir = os.path.join(tmp, "game") os.makedirs(manifest_dir) os.makedirs(game_dir) v_info = { "title": "Synthetic Size Test", "version": "9.9.9.9", "expected_exe": "test_game.exe", "files": { "MicrosoftGame.Config": {"size": 16}, "Catalog000.bin": {"size": 32}, "appdata0.rpf": {"size": 64}, "extra.bin": {"size": 100}, }, } with open(os.path.join(manifest_dir, "custom.json"), "w", encoding="utf-8") as f: json.dump(v_info, f) for rel, info in v_info["files"].items(): p = os.path.join(game_dir, rel) with open(p, "wb") as f: f.truncate(info["size"] + 5 if rel == "extra.bin" else info["size"]) with mock.patch.object(make_game, "VERSIONS", manifest_dir): self.assert_fails(make_game.check, game_dir, full=False, match="1 file(s) missing or different") def test_check_missing_exe_logs_warning_and_proceeds(self): with tempfile.TemporaryDirectory() as tmp: manifest_dir = os.path.join(tmp, "manifests") game_dir = os.path.join(tmp, "game") os.makedirs(manifest_dir) os.makedirs(game_dir) v_info = { "title": "Synthetic No Exe", "version": "9.9.9.9", "expected_exe": "custom_loader.exe", "files": { "MicrosoftGame.Config": {"size": 16}, "Catalog000.bin": {"size": 32}, "appdata0.rpf": {"size": 64}, }, } with open(os.path.join(manifest_dir, "custom.json"), "w", encoding="utf-8") as f: json.dump(v_info, f) for rel, info in v_info["files"].items(): p = os.path.join(game_dir, rel) with open(p, "wb") as f: f.truncate(info["size"]) stdout_buf = io.StringIO() with mock.patch.object(make_game, "VERSIONS", manifest_dir): with mock.patch("sys.stdout", stdout_buf): res = make_game.check(game_dir, full=False) self.assertEqual(res["version"], "9.9.9.9") self.assertIn("custom_loader.exe is not in the folder", stdout_buf.getvalue()) class ToolchainDetectionTest(PreflightTestBase): def test_tool_available_direct_file(self): self.assertTrue(make_game.tool_available(sys.executable)) def test_tool_available_quoted_string(self): self.assertTrue(make_game.tool_available(f'"{sys.executable}"')) def test_tool_available_command_with_arguments(self): self.assertTrue(make_game.tool_available(f'"{sys.executable}" -I')) def test_tool_available_shutil_which_lookup(self): with mock.patch("shutil.which", return_value=r"C:\bin\custom_tool.exe"): self.assertTrue(make_game.tool_available("custom_tool")) def test_tool_available_nonexistent_command(self): self.assertFalse(make_game.tool_available("nonexistent_compiler_xyz_789")) def test_tool_available_empty_and_whitespace(self): self.assertFalse(make_game.tool_available("")) self.assertFalse(make_game.tool_available(" ")) self.assertFalse(make_game.tool_available('""')) def test_tool_available_quoted_path_with_spaces_and_arguments(self): with tempfile.TemporaryDirectory() as tmp: exe = os.path.join(tmp, "my tools", "tool.exe") os.makedirs(os.path.dirname(exe)) with open(exe, "wb"): pass self.assertTrue(make_game.tool_available(exe)) self.assertTrue(make_game.tool_available(f'"{exe}"')) self.assertTrue(make_game.tool_available(f'"{exe}" --version')) def test_tool_available_unmatched_quote_returns_false(self): self.assertFalse(make_game.tool_available('"unclosed path')) APPDATA_ENV = {"LOCALAPPDATA": r"C:\Users\u\AppData\Local", "APPDATA": r"C:\Users\u\AppData\Roaming"} def test_appdata_hint_names_the_folder_llvm_mc_is_in(self): with mock.patch("os.name", "nt"), mock.patch.dict(os.environ, self.APPDATA_ENV): for cmd, var in ((r"C:\Users\u\AppData\Local\Leonida\llvm-mc\llvm-mc.exe", "LOCALAPPDATA"), (r'"c:\users\U\appdata\roaming\llvm\llvm-mc.exe"', "APPDATA")): with self.subTest(cmd=cmd): hint = make_game.appdata_hint(cmd) self.assertIn(f"LLVM_MC points into %{var}%", hint) self.assertIn(r"%USERPROFILE%\.leonida\llvm-mc", hint) def test_appdata_hint_is_empty_outside_appdata(self): with mock.patch("os.name", "nt"), mock.patch.dict(os.environ, self.APPDATA_ENV): for cmd in ("llvm-mc", r"D:\Tools\llvm-mc\llvm-mc.exe", r"C:\Users\u\.leonida\llvm-mc\llvm-mc.exe", r"C:\Users\u\AppData\LocalLow\llvm-mc.exe", "wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc"): with self.subTest(cmd=cmd): self.assertEqual(make_game.appdata_hint(cmd), "") def test_appdata_hint_is_empty_off_windows(self): with mock.patch("os.name", "posix"), mock.patch.dict(os.environ, self.APPDATA_ENV): self.assertEqual(make_game.appdata_hint(r"C:\Users\u\AppData\Local\llvm-mc.exe"), "") def test_need_success_returns_tool(self): self.assertEqual(make_game.need(sys.executable, "Install python"), sys.executable) def test_need_failure_exits_with_hint(self): self.assert_fails(make_game.need, "ghost_compiler", "Please install it.", match="'ghost_compiler' was not found on PATH. Please install it.") class PreflightPrerequisiteTest(PreflightTestBase): def setUp(self): super().setUp() # preflight runs `dotnet --list-sdks` (#223). Follow the test's faked shutil.which instead: the SDK counts as # installed exactly when the test says dotnet is on PATH, so no real dotnet is needed and none is consulted. patcher = mock.patch("make_game.dotnet_sdk_ok", side_effect=lambda: bool(shutil.which("dotnet"))) patcher.start() self.addCleanup(patcher.stop) def test_preflight_success_all_tools_present_and_space_sufficient(self): with tempfile.TemporaryDirectory() as tmp_work: with mock.patch("sys.version_info", (3, 12, 0)), \ mock.patch("shutil.which", return_value="/usr/bin/tool"), \ mock.patch("make_game.tool_available", return_value=True), \ mock.patch("make_game.ensure_submodule", return_value=None) as ensure_submodule, \ mock.patch("make_game.visual_cpp_tools_ok", return_value=True), \ mock.patch("shutil.disk_usage", return_value=Usage(1000 * 2**30, 200 * 2**30, 800 * 2**30)): # off Windows runtime checks the cross-build instead (tests/test_make_game_platform.py) stages = ["shaders", "assets"] + (["runtime"] if os.name == "nt" else []) make_game.preflight(stages, tmp_work, wav=True) ensure_submodule.assert_called_once_with() def test_preflight_aggregates_multiple_missing_tools_and_deduplicates(self): with tempfile.TemporaryDirectory() as tmp_work: with mock.patch("sys.version_info", (3, 12, 0)), \ mock.patch("shutil.which", return_value=None), \ mock.patch("make_game.tool_available", return_value=False), \ mock.patch.object(make_game, "ROOT", tmp_work), \ mock.patch("os.path.isfile", return_value=False), \ mock.patch("os.name", "nt"): err = self.assert_fails(make_game.preflight, ["shaders", "assets", "runtime"], tmp_work, wav=True, match="Install these first, then run the build again:") self.assertIn("ffmpeg (needed for --wav)", err) self.assertIn("llvm-mc (LLVM 23+ with the AMDGPU target)", err) self.assertIn("spirv-as:", err) self.assertIn("spirv-val:", err) self.assertIn(".NET 8 SDK", err) self.assertIn("Visual Studio 2022", err) def test_preflight_accepts_spaced_llvm_mc_resolved_by_which(self): with tempfile.TemporaryDirectory() as tmp_work: mc = os.path.join(tmp_work, "LLVM Tools", "llvm-mc") available = {mc: mc + ".exe", "spirv-as": "spirv-as", "spirv-val": "spirv-val"} with mock.patch.dict(os.environ, {"LLVM_MC": mc}), \ mock.patch("shutil.which", side_effect=available.get), \ mock.patch("shutil.disk_usage", return_value=Usage(100 * 2**30, 0, 100 * 2**30)): make_game.preflight(["shaders"], tmp_work) def test_preflight_explains_llvm_mc_hidden_in_appdata(self): env = {"LOCALAPPDATA": r"C:\Users\u\AppData\Local", "LLVM_MC": r"C:\Users\u\AppData\Local\Leonida\llvm-mc\llvm-mc.exe"} available = {"spirv-as": "spirv-as", "spirv-val": "spirv-val"} with tempfile.TemporaryDirectory() as tmp_work, \ mock.patch.dict(os.environ, env), \ mock.patch("os.name", "nt"), \ mock.patch("sys.version_info", (3, 12, 0)), \ mock.patch("shutil.which", side_effect=available.get), \ mock.patch("os.path.isfile", return_value=False): err = self.assert_fails(make_game.preflight, ["shaders"], tmp_work, match="llvm-mc (LLVM 23+ with the AMDGPU target)") self.assertIn("LLVM_MC points into %LOCALAPPDATA%", err) def test_preflight_rejects_visual_studio_installer_without_cpp_tools(self): with tempfile.TemporaryDirectory() as tmp_work, \ mock.patch("os.name", "nt"), \ mock.patch("os.path.isfile", return_value=True), \ mock.patch("subprocess.run", return_value=mock.Mock(returncode=0, stdout=b"\r\n")): self.assert_fails(make_game.preflight, ["runtime"], tmp_work, match="Visual Studio 2022") def test_visual_cpp_tools_accepts_matching_installation(self): with mock.patch("os.path.isfile", return_value=True), \ mock.patch("subprocess.run", return_value=mock.Mock(returncode=0, stdout=b"C:\\VS\r\n")) as run: self.assertTrue(make_game.visual_cpp_tools_ok()) self.assertEqual(run.call_args.args[0][1:], ["-latest", "-products", "*", "-requires", "Microsoft.VisualStudio.Component.VC.Tools.x86.x64", "-property", "installationPath"]) def test_preflight_python_version_check(self): with tempfile.TemporaryDirectory() as tmp_work: with mock.patch("sys.version_info", (3, 11, 9)), \ mock.patch("shutil.which", return_value="/usr/bin/tool"), \ mock.patch("make_game.tool_available", return_value=True), \ mock.patch("make_game.ensure_submodule", return_value=None), \ mock.patch("os.path.isfile", return_value=True), \ mock.patch("shutil.disk_usage", return_value=Usage(1000 * 2**30, 100 * 2**30, 900 * 2**30)): self.assert_fails(make_game.preflight, ["shaders"], tmp_work, wav=False, match="Python 3.12 or newer:") def test_preflight_wav_without_assets_does_not_require_ffmpeg(self): with tempfile.TemporaryDirectory() as tmp_work: def mock_which(cmd): return None if cmd == "ffmpeg" else f"/bin/{cmd}" with mock.patch("sys.version_info", (3, 12, 0)), \ mock.patch("shutil.which", side_effect=mock_which), \ mock.patch("make_game.tool_available", return_value=True), \ mock.patch("shutil.disk_usage", return_value=Usage(1000 * 2**30, 100 * 2**30, 900 * 2**30)): # wav=True with ["shaders"] stage only: ffmpeg not required make_game.preflight(["shaders"], tmp_work, wav=True) def test_preflight_assets_without_wav_does_not_require_ffmpeg(self): with tempfile.TemporaryDirectory() as tmp_work: def mock_which(cmd): return None if cmd == "ffmpeg" else f"/bin/{cmd}" with mock.patch("sys.version_info", (3, 12, 0)), \ mock.patch("shutil.which", side_effect=mock_which), \ mock.patch("make_game.ensure_submodule", return_value=None), \ mock.patch("shutil.disk_usage", return_value=Usage(1000 * 2**30, 100 * 2**30, 900 * 2**30)): # wav=False with ["assets"] stage: ffmpeg not required make_game.preflight(["assets"], tmp_work, wav=False) def test_preflight_disk_space_insufficient(self): with tempfile.TemporaryDirectory() as tmp_work: with mock.patch("sys.version_info", (3, 12, 0)), \ mock.patch("shutil.which", return_value="/usr/bin/tool"), \ mock.patch("make_game.tool_available", return_value=True), \ mock.patch("make_game.ensure_submodule", return_value=None), \ mock.patch("os.path.isfile", return_value=True), \ mock.patch("shutil.disk_usage", return_value=Usage(500 * 2**30, 485 * 2**30, 15 * 2**30)): # Shaders needs 30 GB, only 15 GB free self.assert_fails(make_game.preflight, ["shaders"], tmp_work, wav=False, match="15 GB free on the drive of") def test_preflight_charges_space_only_when_shaders_need_to_be_rebuilt(self): cases = ( ("current translation", {}, {}, False, True), ("matching emulation", {"spirv/wave64_emulate.txt": "on"}, {"emulate": True}, False, True), ("auto keeps emulation", {"spirv/wave64_emulate.txt": "on"}, {"keep_emulated": True}, False, True), ("missing disassembly marker", {"dxbc/disasm.done": None}, {}, False, False), ("old disassembly marker", {"dxbc/disasm.done": "shader_disasm.py finished"}, {}, False, False), ("changed LLVM", {"dxbc/disasm.done": "old llvm-mc"}, {}, False, False), ("stale translator", {"spirv/translation_sources.sha256": "stale"}, {}, False, False), ("old translation without fingerprint", {"spirv/translation_sources.sha256": None}, {}, False, False), ("needs emulation", {}, {"emulate": True}, False, False), ("explicit native mode", {"spirv/wave64_emulate.txt": "on"}, {}, False, False), ("interrupted unpack", {"dxbc/fssm_index.json": None}, {}, False, False), ("interrupted translation", {"spirv/index.json": None}, {}, False, False), ("empty translation", {"spirv/index.json": "{}"}, {}, False, False), ("old disassembly layout", {}, {}, True, False), ) fingerprint = make_game.translation_sources_digest() usage = Usage(500 * 2**30, 485 * 2**30, 15 * 2**30) for name, changed, settings, legacy_layout, reusable in cases: with self.subTest(name=name), tempfile.TemporaryDirectory() as work: files = { "dxbc/index.json": '[{"file": "shader.dxbc"}]', "dxbc/fssm_index.json": '[{"name": "shader"}]', "dxbc/disasm.done": "test llvm-mc 21", "spirv/index.json": '{"shader":{"stage":"ps"}}', "spirv/translation_sources.sha256": fingerprint, "spirv/wave64_emulate.txt": "off", **changed, } shader_root = os.path.join(work, "shaders") for name, content in files.items(): if content is not None: path = os.path.join(shader_root, name) os.makedirs(os.path.dirname(path), exist_ok=True) with open(path, "w", encoding="utf-8") as handle: handle.write(content + "\n") disasm_parts = ("disasm",) if legacy_layout else ("dxbc", "disasm") disasm = os.path.join(shader_root, *disasm_parts) os.makedirs(disasm) with open(os.path.join(disasm, "shader.s"), "w", encoding="utf-8", newline="\n") as f: f.write("synthetic listing\n") with mock.patch("sys.version_info", (3, 12, 0)), \ mock.patch("make_game.llvm_mc_signature", return_value="test llvm-mc 21"), \ mock.patch("make_game.tool_available", return_value=True), \ mock.patch("shutil.which", return_value="/usr/bin/tool"), \ mock.patch("shutil.disk_usage", return_value=usage), \ mock.patch("sys.stdout", io.StringIO()): if reusable: make_game.preflight(["shaders"], work, **settings) else: self.assert_fails(make_game.preflight, ["shaders"], work, match="about 30 GB is needed", **settings) def test_preflight_disk_space_stage_accumulation(self): with tempfile.TemporaryDirectory() as tmp_work: with mock.patch("sys.version_info", (3, 12, 0)), \ mock.patch("shutil.which", return_value="/usr/bin/tool"), \ mock.patch("make_game.tool_available", return_value=True), \ mock.patch("make_game.ensure_submodule", return_value=None) as ensure_submodule, \ mock.patch("shutil.disk_usage", return_value=Usage(500 * 2**30, 250 * 2**30, 250 * 2**30)): # shaders (30) + assets (370) = 400 GB needed, only 250 GB free err = self.assert_fails(make_game.preflight, ["shaders", "assets"], tmp_work, wav=False, match="about 400 GB is needed") self.assertIn("250 GB free", err) ensure_submodule.assert_not_called() def test_preflight_suggests_loader_only_when_dropping_assets_makes_it_fit(self): gib = 1 << 30 loader_build = ["check", "shaders", "runtime"] full_build = [*loader_build, "assets"] cases = ( ("reusable shader outputs", full_build, 10 * gib, True, False, True), ("asset export only", ["assets"], 250 * gib, False, False, False), ("shader and asset exports only", ["shaders", "assets"], 250 * gib, False, False, False), ("WAV export requested", full_build, 250 * gib, False, True, False), ) with mock.patch.multiple( make_game, mc_command=mock.Mock(return_value=["llvm-mc"]), dotnet_sdk_ok=mock.Mock(return_value=True), ensure_submodule=mock.Mock(), visual_cpp_tools_ok=mock.Mock(return_value=True), cross_build_missing=mock.Mock(return_value=[]), assets_exported=mock.Mock(return_value=False), ), mock.patch("shutil.which", return_value="/usr/bin/tool"): for name, stages, free, reusable, wav, expect_hint in cases: usage = Usage(500 * gib, 500 * gib - free, free) with self.subTest(name=name), tempfile.TemporaryDirectory() as work, \ mock.patch("shutil.disk_usage", return_value=usage), \ mock.patch.object(make_game, "shader_outputs_reusable", return_value=reusable): err = self.assert_fails(make_game.preflight, stages, work, wav=wav, match="is needed") self.assertEqual("--stages check,shaders,runtime" in err, expect_hint) def test_low_disk_cli_suggests_a_working_stage_selection(self): gib = 1 << 30 with tempfile.TemporaryDirectory() as tmp, mock.patch.multiple( make_game, below_normal=mock.DEFAULT, check=mock.Mock(return_value={"expected_exe": "synthetic.exe"}), mc_command=mock.Mock(return_value=["llvm-mc"]), dotnet_sdk_ok=mock.Mock(return_value=True), ensure_submodule=mock.DEFAULT, visual_cpp_tools_ok=mock.Mock(return_value=True), cross_build_missing=mock.Mock(return_value=[]), cross_configure=mock.DEFAULT, pipeline_check_exe=mock.Mock(return_value="vk_pipeline_check"), assets_exported=mock.Mock(return_value=False), shader_outputs_reusable=mock.Mock(return_value=False), wave64_settings=mock.Mock(return_value=(False, False)), runtime_gpu_per_vertex=mock.Mock(return_value=True), log=mock.DEFAULT, shaders=mock.DEFAULT, assets=mock.DEFAULT, runtime=mock.DEFAULT, pipelines=mock.DEFAULT, ) as stages, mock.patch("shutil.which", return_value="available-tool"), \ mock.patch("shutil.disk_usage") as disk: argv = ["make_game.py", "--game", os.path.join(tmp, "input"), "--out", os.path.join(tmp, "out")] with mock.patch.object(sys, "argv", argv): disk.return_value = Usage(500 * gib, 470 * gib + 1, 30 * gib - 1) error = self.assert_fails(make_game.main, match="about 400 GB is needed") self.assertNotIn("--stages", error) disk.return_value = Usage(500 * gib, 470 * gib, 30 * gib) error = self.assert_fails(make_game.main, match="about 400 GB is needed") suggestion = re.search(r"--stages ([a-z,]+)", error) self.assertIsNotNone(suggestion, error) for stage in ("shaders", "assets", "runtime", "pipelines"): stages[stage].assert_not_called() with mock.patch.object(sys, "argv", [*argv, "--stages", suggestion.group(1)]): self.assertEqual(make_game.main(), 0) stages["shaders"].assert_called_once() stages["runtime"].assert_called_once() stages["assets"].assert_not_called() stages["pipelines"].assert_not_called() def test_preflight_counts_assets_again_with_wav_even_when_exported(self): # --wav decodes again over the exported audio (assets_exported says it is finished), so the 370 GB stays. with tempfile.TemporaryDirectory() as tmp_work: with mock.patch("sys.version_info", (3, 12, 0)), \ mock.patch("make_game.assets_exported", return_value=True), \ mock.patch("make_game.tool_available", return_value=True), \ mock.patch("make_game.ensure_submodule", return_value=None), \ mock.patch("shutil.which", return_value="/usr/bin/tool"), \ mock.patch("os.path.isfile", return_value=True), \ mock.patch("shutil.disk_usage", return_value=Usage(500 * 2**30, 250 * 2**30, 250 * 2**30)): # Without --wav the exported assets are credited, so 250 GB free is enough for the asset tools. make_game.preflight(["assets"], tmp_work, wav=False) err = self.assert_fails(make_game.preflight, ["assets"], tmp_work, wav=True, match="about 370 GB is needed") # c506d00c: the loader-only hint is offered only when shaders and runtime are selected and not --wav self.assertNotIn("without exporting assets", err) def test_ensure_submodule_present_is_noop(self): with tempfile.TemporaryDirectory() as tmp: core_dir = os.path.join(tmp, "third_party", "rpf9-explorer", "Core") os.makedirs(core_dir) with open(os.path.join(core_dir, "Core.cs"), "w") as f: f.write("// dummy") with mock.patch.object(make_game, "ROOT", tmp): make_game.ensure_submodule() def test_ensure_submodule_missing_fails_cleanly(self): with tempfile.TemporaryDirectory() as tmp: with mock.patch.object(make_game, "ROOT", tmp), \ mock.patch("shutil.which", return_value=None): self.assert_fails(make_game.ensure_submodule, match="git clone --recursive https://github.com/ProjectLeonida/mandy") def test_ensure_submodule_zip_with_git_does_not_say_install_git(self): with tempfile.TemporaryDirectory() as tmp: not_a_repo = subprocess.CompletedProcess([], 128) with mock.patch.object(make_game, "ROOT", tmp), \ mock.patch("shutil.which", return_value="/usr/bin/git"), \ mock.patch("subprocess.run", return_value=not_a_repo): err = self.assert_fails(make_game.ensure_submodule, match="git clone --recursive https://github.com/ProjectLeonida/mandy") self.assertNotIn("Install Git", err) def test_ensure_submodule_names_the_clone_command_the_readme_gives(self): # the hint once named a repository that had gone private; the README is where the address is kept current with open(os.path.join(ROOT, "README.md"), encoding="utf-8") as f: readme = f.read() with tempfile.TemporaryDirectory() as tmp: with mock.patch.object(make_game, "ROOT", tmp), \ mock.patch("shutil.which", return_value=None): err = self.assert_fails(make_game.ensure_submodule, match="git clone --recursive ") clone = re.search(r"git clone --recursive https://github\.com/[\w.-]+/[\w.-]+", err) self.assertIsNotNone(clone, err) self.assertIn(f"`{clone.group(0)}`", readme) def test_ensure_submodule_failed_fetch_in_clone_names_the_fetch(self): with tempfile.TemporaryDirectory() as tmp: results = [subprocess.CompletedProcess([], 0), subprocess.CompletedProcess([], 1)] with mock.patch.object(make_game, "ROOT", tmp), \ mock.patch("shutil.which", return_value="/usr/bin/git"), \ mock.patch("subprocess.run", side_effect=results), \ mock.patch.object(make_game, "log"): err = self.assert_fails(make_game.ensure_submodule, match="fetching third_party/rpf9-explorer failed") self.assertIn("git submodule update --init --recursive", err) self.assertNotIn("Download ZIP", err) class GameDiscoveryTest(unittest.TestCase): def setUp(self): self.home = self.enterContext(tempfile.TemporaryDirectory()) self.desktop = os.path.join(self.home, "Desktop") self.downloads = os.path.join(self.home, "Downloads") self.version = {"title": "Synthetic", "version": "1.0", "files": { "MicrosoftGame.Config": {"size": 3}, "Catalog000.bin": {"size": 4}, "appdata0.rpf": {"size": 5}, }} def write_probes(self, folder): os.makedirs(folder) for name, info in self.version["files"].items(): with open(os.path.join(folder, name), "wb") as file: file.truncate(info["size"]) def discover(self, known=()): """find_dumps() over the synthetic home folder only; `known` is what the shell reports for Downloads, Desktop and Documents.""" roots = (self.home, self.desktop, self.downloads, *known) isdir = os.path.isdir with mock.patch("os.path.expanduser", return_value=self.home), \ mock.patch("os.path.isdir", side_effect=lambda path: path in roots and isdir(path)), \ mock.patch.object(make_game, "known_folders", return_value=list(known)), \ mock.patch.object(make_game, "versions", return_value=[self.version]): return make_game.find_dumps() def test_find_searches_known_folders_moved_into_onedrive(self): # OneDrive's Known Folder Move: Explorer's Desktop and Documents are ~\OneDrive\Desktop and # ~\OneDrive\Documents, two levels below the home folder, so the home root alone never reaches inside them. desktop = os.path.join(self.home, "OneDrive", "Desktop") documents = os.path.join(self.home, "OneDrive", "Documents") on_desktop = os.path.join(desktop, "GTA VI") in_documents = os.path.join(documents, "Games", "GTA VI") self.write_probes(on_desktop) self.write_probes(in_documents) self.assertEqual(self.discover(), []) self.assertEqual(self.discover(known=(desktop, documents)), [(on_desktop, self.version), (in_documents, self.version)]) def test_find_reports_a_copy_once_when_known_folders_are_not_moved(self): package = os.path.join(self.desktop, "Package") self.write_probes(package) self.assertEqual(self.discover(known=(self.downloads, self.desktop)), [(package, self.version)]) def test_known_folders_from_the_shell(self): folders = make_game.known_folders() if os.name != "nt": self.assertEqual(folders, []) return # Without KF_FLAG_DONT_VERIFY the shell reports a known folder only where it exists, so the result is exactly # the unverified paths that are directories: a missing or unreachable folder drops out, and an empty result # passes only on a machine where none of the three exists. self.assertEqual(folders, [path for path in self.unverified_known_folders() if os.path.isdir(path)]) for folder in folders: self.assertTrue(os.path.isabs(folder), folder) self.assertEqual(make_game.known_folders(), folders) # the shell's buffers are freed, calls repeat cleanly @staticmethod def unverified_known_folders(): """Each of make_game.KNOWN_FOLDERS as SHGetKnownFolderPath reports it with KF_FLAG_DONT_VERIFY (0x4000): the configured path, whether or not the folder is there.""" import uuid from ctypes import wintypes shell32, ole32 = ctypes.WinDLL("shell32"), ctypes.WinDLL("ole32") get = shell32.SHGetKnownFolderPath get.argtypes = [ctypes.c_char_p, wintypes.DWORD, wintypes.HANDLE, ctypes.POINTER(ctypes.c_void_p)] get.restype = ctypes.c_long ole32.CoTaskMemFree.argtypes = [ctypes.c_void_p] paths = [] for folder in make_game.KNOWN_FOLDERS: path = ctypes.c_void_p() try: if get(uuid.UUID(folder).bytes_le, 0x4000, None, ctypes.byref(path)) == 0 and path.value: paths.append(ctypes.wstring_at(path.value)) finally: ole32.CoTaskMemFree(path) return paths def test_known_folders_keeps_available_paths_when_a_lookup_fails(self): expected = [r"C:\Redirected\Downloads", r"C:\Redirected\Documents"] first, last = [ctypes.create_unicode_buffer(path) for path in expected] addresses = [ctypes.addressof(first), None, ctypes.addressof(last)] results = iter(addresses) def get_path(_folder, _flags, _token, path): address = next(results) if address is None: return -1 ctypes.cast(path, ctypes.POINTER(ctypes.c_void_p)).contents.value = address return 0 shell32, ole32 = mock.Mock(), mock.Mock() shell32.SHGetKnownFolderPath.side_effect = get_path libraries = {"shell32": shell32, "ole32": ole32} with mock.patch.object(ctypes, "WinDLL", side_effect=libraries.__getitem__, create=True), \ mock.patch.object(os, "name", "nt"): self.assertEqual(make_game.known_folders(), expected) self.assertEqual([call.args[0].value for call in ole32.CoTaskMemFree.call_args_list], addresses) def test_find_searches_below_rejected_folder_with_config(self): outer = os.path.join(self.desktop, "Backup") package = os.path.join(outer, "Package") self.write_probes(package) with open(os.path.join(outer, "MicrosoftGame.Config"), "wb") as config: config.write(b"abc") self.write_probes(os.path.join(outer, "Other", "TooDeep")) self.assertEqual(self.discover(), [(package, self.version)]) def test_find_revisits_aliased_root_with_more_depth(self): target = os.path.join(self.downloads, "Outer", "Inner") package = os.path.join(self.desktop, "Package") self.write_probes(os.path.join(target, "Package")) self.write_probes(package) realpath = os.path.realpath def resolve(path): if path == self.desktop or path.startswith(self.desktop + os.sep): path = os.path.join(target, os.path.relpath(path, self.desktop)) return realpath(path) with mock.patch("os.path.realpath", side_effect=resolve): self.assertEqual(self.discover(), [(package, self.version)]) def test_discovery_roots_follow_the_platform(self): # Elsewhere than Windows a copy on another disk or on a share shows up under a mount point, so those are # searched too: /Volumes is where macOS mounts drives and mount_smbfs shares, /run/media is Fedora's. with mock.patch.object(make_game.os, "name", "posix"), \ mock.patch.object(make_game, "known_folders", return_value=[]): roots = make_game.discovery_roots(self.home) self.assertIn(os.path.join(self.home, "Downloads"), roots) for root in ("/mnt", "/media", "/run/media", "/Volumes"): self.assertIn(root, roots) self.assertEqual([r for r in roots if r.endswith(":\\")], []) def test_volume_roots_add_the_users_mount_folders(self): # udisks2 mounts a drive at /media//