"""Synthetic-header tests for tools/anim_index.py. python -I tests/test_anim_index.py Every byte here is built by the test. No game file or game asset name is used. """ import contextlib import csv import json import os from pathlib import Path import struct import subprocess import sys import tempfile import unittest from unittest import mock import zlib ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TOOL = os.path.join(ROOT, "tools", "anim_index.py") sys.path.insert(0, os.path.join(ROOT, "tools")) import anim_index # noqa: E402 @contextlib.contextmanager def tracked_mmaps(): """Record every mmap.mmap opened by anim_index and close any leak on exit.""" real_mmap = anim_index.mmap.mmap created = [] def wrap(*args, **kwargs): mapping = real_mmap(*args, **kwargs) created.append(mapping) return mapping try: with mock.patch.object(anim_index.mmap, "mmap", side_effect=wrap): yield created finally: for mapping in created: if not mapping.closed: mapping.close() def move(): data = bytearray(72) data[:4] = b"MoVE" struct.pack_into("" * 4 return data + bytes(max(0, 64 - len(data))) def bink(): data = bytearray(0x40) data[:4] = b"KB2n" struct.pack_into("/index.json is the carve manifest's name even before a carve has written it. carve = os.path.join(self.root, "carved_no_manifest") os.makedirs(carve) manifest = os.path.join(carve, "index.json") out_csv = os.path.join(self.root, "no_manifest.csv") for args, flag in (([manifest], "output"), ([out_csv, "--rigs", manifest], "--rigs")): with self.subTest(flag=flag): p = subprocess.run([sys.executable, "-I", TOOL, carve, *args, "--quiet"], capture_output=True, text=True, encoding="utf-8", errors="replace") self.assertEqual(p.returncode, 2, p.stdout + p.stderr) self.assertIn(f"{flag} would overwrite the carve manifest", p.stderr) self.assertFalse(os.path.exists(manifest)) def test_cli_carve_dir_protects_manifest_and_input_files(self): carve = os.path.join(self.root, "carved_manifest_test") os.makedirs(carve) manifest = os.path.join(carve, "index.json") with open(manifest, "w", encoding="utf-8") as f: f.write('{"manifest": true}') bin_file = os.path.join(carve, "000000001000.bin") with open(bin_file, "wb") as f: f.write(b"A" * 64) out_csv = os.path.join(self.root, "valid.csv") # Refuse to overwrite carve manifest via out p = subprocess.run([sys.executable, "-I", TOOL, carve, manifest, "--quiet"], capture_output=True, text=True, errors="replace") self.assertEqual(p.returncode, 2, p.stdout + p.stderr) self.assertIn("output would overwrite the carve manifest", p.stderr) # Refuse to overwrite carve manifest via --rigs p = subprocess.run([sys.executable, "-I", TOOL, carve, out_csv, "--rigs", manifest, "--quiet"], capture_output=True, text=True, errors="replace") self.assertEqual(p.returncode, 2, p.stdout + p.stderr) self.assertIn("--rigs would overwrite the carve manifest", p.stderr) # Refuse to overwrite carved input file via out p = subprocess.run([sys.executable, "-I", TOOL, carve, bin_file, "--quiet"], capture_output=True, text=True, errors="replace") self.assertEqual(p.returncode, 2, p.stdout + p.stderr) self.assertIn("output would overwrite an input file", p.stderr) # Refuse to overwrite carved input file via --rigs p = subprocess.run([sys.executable, "-I", TOOL, carve, out_csv, "--rigs", bin_file, "--quiet"], capture_output=True, text=True, errors="replace") self.assertEqual(p.returncode, 2, p.stdout + p.stderr) self.assertIn("--rigs would overwrite an input file", p.stderr) def test_directory(self): folder = os.path.join(self.root, "carved") os.makedirs(folder) for i, payload in enumerate((move(), page(), names())): with open(os.path.join(folder, f"{0x1000 + i * 0x100:012x}.bin"), "wb") as f: f.write(payload) rows, summary = anim_index.scan_dir(folder) self.assertEqual([r["offset"] for r in rows], [0x1000, 0x1100, 0x1200]) self.assertEqual([r["signature"] for r in rows], ["move", "page-directory", "name-table"]) self.assertEqual(summary["mode"], "directory") def test_directory_classifies_each_payload_before_opening_the_next(self): folder = os.path.join(self.root, "streamed") os.mkdir(folder) payloads = (move(), page(), names()) for name, payload in zip(("00001000.bin", "a.bin", "b.bin"), payloads): with open(os.path.join(folder, name), "wb") as f: f.write(payload) classify = mock.Mock(wraps=anim_index.classify) reads = [] def tracked_open(path, mode): self.assertEqual(classify.call_count, len(reads)) reads.append(os.path.basename(path)) return open(path, mode) with mock.patch.object(anim_index, "classify", classify), \ mock.patch.object(anim_index, "open", tracked_open, create=True): rows, summary = anim_index.scan_dir(folder) self.assertEqual(reads, ["00001000.bin", "a.bin", "b.bin"]) self.assertEqual([row["offset"] for row in rows], [0x1000, 1, 2]) self.assertEqual(summary["span"], sum(map(len, payloads))) def test_directory_rejects_start_and_limit(self): folder = os.path.join(self.root, "carved") os.makedirs(folder) for offset in (0x100, 0x200): with open(os.path.join(folder, f"{offset:012x}.bin"), "wb") as f: f.write(b"A" * 64) cases = [("--start", "0"), ("--limit", "1"), ("--limit", "1", "--start", "0x200")] for i, flags in enumerate(cases): with self.subTest(flags=flags): out = os.path.join(self.root, f"bad{i}.json") p = subprocess.run([sys.executable, "-I", TOOL, folder, out, "--quiet", *flags], capture_output=True, text=True, errors="replace") self.assertEqual(p.returncode, 2, p.stdout + p.stderr) self.assertEqual(len(p.stderr.splitlines()), 1, p.stderr) for flag in flags[::2]: self.assertIn(flag, p.stderr) self.assertFalse(os.path.exists(out)) def test_directory_skips_the_carvers_index_and_reports(self): """rpf9_carve.py writes index.json next to the streams; it and a report are not payloads.""" folder = os.path.join(self.root, "carved") os.makedirs(folder) for i, payload in enumerate((move(), page(), names())): with open(os.path.join(folder, f"{0x1000 + i * 0x100:012x}.bin"), "wb") as f: f.write(payload) with open(os.path.join(folder, "index.json"), "w", encoding="utf-8") as f: f.write('[{"off": 4096, "stored": 16}]') with open(os.path.join(folder, "report.csv"), "w", encoding="utf-8") as f: f.write("offset,size\n") rows, summary = anim_index.scan_dir(folder) self.assertEqual([r["offset"] for r in rows], [0x1000, 0x1100, 0x1200]) def test_scan_rpf_closes_mmap_on_invalid_start(self): with tracked_mmaps() as created: with self.assertRaisesRegex(ValueError, "outside the archive"): anim_index.scan_rpf(self.rpf, start=os.path.getsize(self.rpf) + 1) self.assertEqual(len(created), 1) self.assertTrue(created[0].closed) os.remove(self.rpf) self.assertFalse(os.path.exists(self.rpf)) def test_scan_rpf_rejects_nonpositive_limit_and_bool_bounds(self): for kwargs in ({"limit": 0}, {"limit": -5}, {"limit": True}, {"limit": False}, {"start": True}): with self.subTest(kwargs=kwargs): with self.assertRaises(ValueError): anim_index.scan_rpf(self.rpf, **kwargs) def test_cli_rigs_failure_preserves_existing_index_output(self): out = os.path.join(self.root, "existing_index.json") rigs = os.path.join(self.root, "existing_rigs.json") with open(out, "w", encoding="utf-8") as f: f.write('{"keep_index": true}') with open(rigs, "w", encoding="utf-8") as f: f.write('{"keep_rigs": true}') p = subprocess.run([sys.executable, "-I", TOOL, self.rpf, out, "--rigs", rigs, "--quiet"], capture_output=True, text=True, errors="replace") self.assertEqual(p.returncode, 2, p.stdout + p.stderr) with open(out, encoding="utf-8") as f: self.assertEqual(json.load(f), {"keep_index": True}) with open(rigs, encoding="utf-8") as f: self.assertEqual(json.load(f), {"keep_rigs": True}) def test_write_output_is_atomic_and_rejects_trailing_separator(self): rows, summary = anim_index.scan_rpf(self.rpf) out = os.path.join(self.root, "atomic.json") with open(out, "w", encoding="utf-8") as f: f.write('{"before": true}') before_files = set(os.listdir(self.root)) with mock.patch.object(anim_index.os, "replace", side_effect=OSError("disk full")): with self.assertRaisesRegex(OSError, "disk full"): anim_index.write_output(out, rows, summary) with open(out, encoding="utf-8") as f: self.assertEqual(json.load(f), {"before": True}) self.assertEqual(set(os.listdir(self.root)), before_files) trailing = out + os.sep with self.assertRaises(IsADirectoryError): anim_index.write_output(trailing, rows, summary) p = subprocess.run([sys.executable, "-I", TOOL, self.rpf, trailing, "--quiet"], capture_output=True, text=True, errors="replace") self.assertEqual(p.returncode, 2, p.stderr) self.assertIn("is a folder", p.stderr) def test_unreadable_source_dir_with_existing_out_has_no_traceback(self): carve = os.path.join(self.root, "locked_carve") os.makedirs(carve) out = os.path.join(self.root, "out.json") with open(out, "w", encoding="utf-8") as f: f.write("{}") err = PermissionError(13, "Permission denied", carve) with mock.patch.object(sys, "argv", ["anim_index.py", carve, out, "--quiet"]), \ mock.patch.object(anim_index.os, "listdir", side_effect=err): with self.assertRaises(SystemExit) as cm: anim_index.main() self.assertIn("Permission denied", str(cm.exception)) class RigArchiveTest(unittest.TestCase): def setUp(self): self.tmp = tempfile.TemporaryDirectory() self.root = self.tmp.name self.rpf = os.path.join(self.root, "rigs.rpf") # A real continuation follows a full 64 KiB stream: pad the rig table (parse_rbf0 ignores the tail) # and cut it there. blob = rbf0_blob() blob += bytes(CHUNK + 4096 - len(blob)) self.parts = [blob[:CHUNK], blob[CHUNK:]] self.skel = b"SKEL_Synthetic\x00SKEL_Second\x00" self.skel += bytes(64 - len(self.skel)) self.front = b"\x0f\x00\xe0\x00\x0c\x00\x16\x00SKEL_Front\x00" self.front += struct.pack("