"""gamedata_blobs.py must decode the remaining text and binary common.rpf payloads without game data. python -I tests/test_gamedata_blobs.py Every fixture is synthetic: preload lists, visual-settings lines, fixed-stride 1,296-byte records, a compact 3-region spatial grid blob, and minimal SGD5 databases. Set ``LEONIDA_GAMEDATA_BLOBS`` to another copy of the tool to use as a negative control; main's version fails the bad-index cases with a bare KeyError or a raw index.json path. """ import json import os import shutil import struct import subprocess import sys import tempfile import unittest from unittest import mock ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TOOLS = os.path.join(ROOT, "tools") TOOL = os.environ.get("LEONIDA_GAMEDATA_BLOBS", os.path.join(TOOLS, "gamedata_blobs.py")) sys.path.insert(0, TOOLS) import gamedata_blobs # noqa: E402 import sgd5_effects # noqa: E402 def fixed_table_1296_blob(records: int) -> bytes: """Build a synthetic 4 + N * 1296 fixed-stride table.""" buf = bytearray(struct.pack(" bytes: """Build a minimal valid 3-region grid (cells -> Region 3 ptrs -> Region 2 records of sizes 3, 6, 11).""" r2_offset = cells * 4 rec_word_sizes = (3, 6, 11) r2_bytes = bytearray() r2_rec_offsets = [] pos = r2_offset for idx, sz in enumerate(rec_word_sizes): r2_rec_offsets.append(pos) for w_i in range(sz): # Keep Region 2 words >= len(blob) (high bit set) so they are distinct from trailing pointers. r2_bytes += struct.pack(" 5 u32 words r3_lists = ( [r2_rec_offsets[0]], [r2_rec_offsets[1], r2_rec_offsets[2]], [r2_rec_offsets[0], r2_rec_offsets[2]], ) r3_bytes = bytearray() r3_cell_offs = [] cur = r3_offset for lst in r3_lists: r3_cell_offs.append(cur) for ptr in lst: r3_bytes += struct.pack(" bytes: nbytes = name.encode("ascii") + b"\x00" return ( bytes([len(nbytes)]) + nbytes + bytes(4 + 24 + 80 + 16 + 12) + struct.pack(" 0.95 distinguishes text from binary in small fixtures preload0 = ("fx_one.fx\nfx_unused.fx\nfx_two.fx\n" + "\n" * 10).encode("ascii") preload1 = ("fx_db1_only.fx\n" * 1).encode("ascii") + b" \n" vfx_dat = ("# vfx\nfx_one.scale 0.5\nother.gamma 2.2\n" * 40).encode("ascii") # Include enough lines for printable() and make binary chunk distinguishable tbl = fixed_table_1296_blob(2) grid = spatial_grid_blob(cells=8) self.add(tbl) self.add(grid) self.add(vfx_dat) self.add(preload0) self.add(preload1) self.finish() archive_bytes, layouts = synthetic_sgd5_archive(["fx_one", "fx_two"], ["fx_db1_only"]) shaders_path = os.path.join(self.root, "synthetic_shaders.rpf") with open(shaders_path, "wb") as f: f.write(archive_bytes) with mock.patch.object(sgd5_effects, "DATABASES", layouts): payloads = gamedata_blobs.read_payloads(self.carve) self.assertEqual([p["kind"] for p in payloads], ["fixed_table_1296", "spatial_grid_table", "vfx_settings_dat", "fx_preload_list", "fx_preload_list"]) xref = gamedata_blobs.cross_reference_sgd5(payloads, shaders_path) self.assertEqual(xref["preload_lists"][0]["in_db0"], 2) self.assertEqual(xref["preload_lists"][0]["unshipped"], 1) self.assertTrue(xref["preload_lists"][0]["exact_order_db0"]) self.assertTrue(xref["preload_lists"][1]["exact_order_db1"]) self.assertEqual(xref["vfx_settings"][0]["prefixes_in_db0"], 1) self.assertEqual(xref["vfx_settings"][0]["data_lines"], 80) self.assertEqual(xref["vfx_settings"][0]["data_lines_in_db0"], 40) out_json = os.path.join(self.root, "reports", "blobs.json") p = subprocess.run([sys.executable, "-I", TOOL, self.carve, "--json", out_json], cwd=self.root, capture_output=True, text=True, encoding="utf-8", errors="replace") self.assertEqual(p.returncode, 0, p.stdout + p.stderr) with open(out_json, "rb") as f: raw = f.read() self.assertIn(b"\n", raw) self.assertNotIn(b"\r\n", raw) for secret in ("fx_one", "fx_unused", "fx_two", "fx_db1_only", "other.gamma"): self.assertNotIn(secret, p.stdout) self.assertNotIn(secret.encode("ascii"), raw) # Collisions against carve index, bin, shaders.rpf, or existing directory fail cleanly for bad_out, extra in ( (os.path.join(self.carve, "index.json"), []), (os.path.join(self.carve, f"{self.rows[0]['off']:012x}.bin"), []), (shaders_path, ["--shaders", shaders_path]), ): r = subprocess.run([sys.executable, "-I", TOOL, self.carve, *extra, "--json", bad_out], cwd=self.root, capture_output=True, text=True, encoding="utf-8", errors="replace") self.assertEqual(r.returncode, 1) self.assertIn("error:", r.stderr) self.assertNotIn("Traceback", r.stderr) class BadCarveIndexTest(unittest.TestCase): """A folder that is not an rpf9_carve.py carve is one error line naming the index and the bad row.""" def run_tool(self, target): # UTF-8 mode: a piped stderr is the ANSI code page on Windows, and the errors below name a path. return subprocess.run([sys.executable, "-I", "-X", "utf8", TOOL, target], cwd=ROOT, capture_output=True, text=True, encoding="utf-8", errors="replace") def assert_one_error(self, result, *needles, code=1, prefix="error:"): self.assertEqual(result.returncode, code, result.stdout + result.stderr) self.assertNotIn("Traceback", result.stderr) lines = result.stderr.strip().splitlines() self.assertEqual(len(lines), 1, result.stderr) self.assertTrue(lines[0].startswith(prefix), lines[0]) for needle in needles: self.assertIn(needle, lines[0]) def make_folder(self, index_json=None): folder = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, folder, True) if index_json is not None: with open(os.path.join(folder, "index.json"), "w", encoding="utf-8") as f: f.write(index_json) return folder def test_no_index_json_names_the_folder(self): folder = os.path.join(self.make_folder(), "carve-\u00f8") os.mkdir(folder) self.assert_one_error(self.run_tool(folder), folder, "no index.json") def test_malformed_json_names_the_index(self): folder = self.make_folder("{oops") self.assert_one_error(self.run_tool(folder), "index.json", "is not valid JSON") def test_index_without_files_names_the_key(self): folder = self.make_folder("{}") self.assert_one_error(self.run_tool(folder), "index.json", "no 'files' list") def test_row_without_stored_names_the_row(self): folder = self.make_folder(json.dumps({"files": [{"off": 0}]})) self.assert_one_error(self.run_tool(folder), "index.json", "row 0", "'off'", "'stored'") def test_missing_file_names_what_is_wrong(self): # A missing input is "ERROR: ..." and exit 2 (#6701, tests/test_missing_input_exit_codes.py). folder = self.make_folder() self.assert_one_error(self.run_tool(os.path.join(folder, "nope.rpf")), "nope.rpf", "no such file or folder", code=2, prefix="ERROR:") def test_reads_carve_index_with_utf8_bom(self): folder = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, folder, True) payload = fixed_table_1296_blob(1) with open(os.path.join(folder, f"{0x1000:012x}.bin"), "wb") as f: f.write(payload) doc = {"files": [{"off": 0x1000, "stored": len(payload), "size": len(payload), "head": payload[:16].hex(), "pre": ""}]} with open(os.path.join(folder, "index.json"), "wb") as f: f.write(b"\xef\xbb\xbf" + json.dumps(doc).encode("utf-8")) r = self.run_tool(folder) self.assertEqual(r.returncode, 0, r.stdout + r.stderr) self.assertIn("fixed_table_1296", r.stdout) class GamedataBlobsSafetyTests(unittest.TestCase): def test_cross_reference_sgd5_unshipped_does_not_double_count_overlap(self): with tempfile.TemporaryDirectory() as tmp: archive_bytes, layouts = synthetic_sgd5_archive( ["shared_fx", "db0_only"], ["shared_fx", "db1_only"], ) shaders_path = os.path.join(tmp, "shaders.rpf") with open(shaders_path, "wb") as f: f.write(archive_bytes) payload = { "kind": "fx_preload_list", "offset_hex": "0x1000", "entries": 3, "_stems": ["shared_fx", "db0_only", "missing_fx"], } with mock.patch.object(sgd5_effects, "DATABASES", layouts): xref = gamedata_blobs.cross_reference_sgd5([payload], shaders_path) row = xref["preload_lists"][0] self.assertEqual(row["in_db0"], 2) self.assertEqual(row["in_db1"], 1) self.assertEqual(row["unshipped"], 1) def test_bad_index_types_recursion_error_and_single_index_parse(self): import contextlib import io with tempfile.TemporaryDirectory() as tmp: for row in ( {"off": True, "stored": 0}, {"off": -1, "stored": 0}, {"off": 0, "stored": "4"}, ): with self.subTest(row=row): folder = os.path.join(tmp, "bad") os.makedirs(folder, exist_ok=True) with open(os.path.join(folder, "index.json"), "w", encoding="utf-8", newline="\n") as f: json.dump({"files": [row]}, f) err = io.StringIO() with contextlib.redirect_stderr(err): rc = gamedata_blobs.main([folder]) self.assertEqual(rc, 1) self.assertIn("row 0", err.getvalue()) self.assertNotIn("Traceback", err.getvalue()) rec_folder = os.path.join(tmp, "rec") os.makedirs(rec_folder) with open(os.path.join(rec_folder, "index.json"), "w", encoding="utf-8", newline="\n") as f: f.write("{}") err = io.StringIO() with ( mock.patch.object(gamedata_blobs.json, "load", side_effect=RecursionError("deep")), contextlib.redirect_stderr(err), ): rc = gamedata_blobs.main([rec_folder]) self.assertEqual(rc, 1) self.assertIn("is not valid JSON", err.getvalue()) self.assertNotIn("Traceback", err.getvalue()) # Empty valid carve must parse index.json once across check_report_path + read_payloads. ok_folder = os.path.join(tmp, "ok") os.makedirs(ok_folder) with open(os.path.join(ok_folder, "index.json"), "w", encoding="utf-8", newline="\n") as f: json.dump({"files": []}, f) out_json = os.path.join(tmp, "out.json") with ( mock.patch.object(gamedata_blobs, "check_carve_index", wraps=gamedata_blobs.check_carve_index) as spy, mock.patch.object(gamedata_blobs.json, "load", wraps=json.load) as load_spy, contextlib.redirect_stdout(io.StringIO()), ): rc = gamedata_blobs.main([ok_folder, "--json", out_json]) self.assertEqual(rc, 0) spy.assert_called_once_with(ok_folder) load_spy.assert_called_once() def test_trailing_separator_json_and_missing_shaders_fail_before_read_payloads(self): import contextlib import io with tempfile.TemporaryDirectory() as tmp: carve = os.path.join(tmp, "carve") os.makedirs(carve) with open(os.path.join(carve, "index.json"), "w", encoding="utf-8", newline="\n") as f: json.dump({"files": []}, f) missing_shaders = os.path.join(tmp, "missing.rpf") dir_shaders = os.path.join(tmp, "shaders_dir") os.makedirs(dir_shaders) for args in ( [carve, "--json", os.path.join(tmp, "dir") + "/"], [carve, "--json", os.path.join(tmp, "dir") + "\\"], [carve, "--shaders", missing_shaders], [carve, "--shaders", dir_shaders], ): with self.subTest(args=args[1:]): err = io.StringIO() with ( mock.patch.object(gamedata_blobs, "read_payloads", side_effect=AssertionError("should not run")), contextlib.redirect_stderr(err), ): rc = gamedata_blobs.main(args) self.assertEqual(rc, 1) self.assertIn("error:", err.getvalue()) def test_atomic_json_lf_and_failure_preserves_existing_report(self): import contextlib import io with tempfile.TemporaryDirectory() as tmp: carve = os.path.join(tmp, "carve") os.makedirs(carve) with open(os.path.join(carve, "index.json"), "w", encoding="utf-8", newline="\n") as f: json.dump({"files": []}, f) out_dir = os.path.join(tmp, "reports") out_json = os.path.join(out_dir, "blobs.json") with contextlib.redirect_stdout(io.StringIO()): self.assertEqual(gamedata_blobs.main([carve, "--json", out_json]), 0) with open(out_json, "rb") as f: raw = f.read() self.assertTrue(raw.endswith(b"\n")) self.assertNotIn(b"\r\n", raw) def fail_dump(_obj, f, **_kw): f.write("{partial") raise OSError("disk full") for target, effect in ( ((gamedata_blobs.json, "dump"), fail_dump), ((gamedata_blobs.replace_retry, "replace"), OSError("replace denied")), ): with self.subTest(target=target[1]): err = io.StringIO() with ( mock.patch.object(target[0], target[1], side_effect=effect), contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(err), ): rc = gamedata_blobs.main([carve, "--json", out_json]) self.assertEqual(rc, 1) self.assertIn("cannot write", err.getvalue()) with open(out_json, "rb") as f: self.assertEqual(f.read(), raw) self.assertEqual([n for n in os.listdir(out_dir) if n.startswith(".blobs-")], []) def test_json_refuses_bink2_carve_input_alias(self): import contextlib import io with tempfile.TemporaryDirectory() as tmp: carve = os.path.join(tmp, "carve") os.makedirs(carve) bk2 = os.path.join(carve, "000000001000.bk2") with open(bk2, "wb") as f: f.write(b"KB2nDATA") with open(os.path.join(carve, "index.json"), "w", encoding="utf-8", newline="\n") as f: json.dump({"files": [{"off": 4096, "stored": 8, "type": "bink2"}]}, f) err = io.StringIO() with contextlib.redirect_stderr(err): rc = gamedata_blobs.main([carve, "--json", bk2]) self.assertEqual(rc, 1) self.assertIn("overwrite", err.getvalue()) with open(bk2, "rb") as f: self.assertEqual(f.read(), b"KB2nDATA") if __name__ == "__main__": unittest.main()