"""Synthetic tests for tools/navmesh_decode.py. No game files are read or needed.""" import csv import json import os import struct import subprocess import sys import tempfile import unittest import zlib ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, os.path.join(ROOT, "tools")) import navmesh_decode as nd # noqa: E402 TOOL = os.path.join(ROOT, "tools", "navmesh_decode.py") BASE = nd.BASE def make_rpf(path, streams, data_start=0x40, pad_between=0): buf = bytearray(data_start) buf[0:4] = b"9FPR" struct.pack_into("= cur) else ((cur + 7) & ~7) need = q40_off + 4 + 8 * len(q40_items) + sum(sz for _, sz in q40_items) if need > len(buf): buf.extend(bytes(need - len(buf))) struct.pack_into("> 9 x0, y0, dx, dy, dz = (sx - 256) * 128.0, (sy - 256) * 128.0, 128.0, 128.0, 16.0 if not has_links: n_links = n_link_idx = 0 n_polys = len(poly_sizes) pool = sum(poly_sizes) # Fixed header at +0x00..+0xEF. struct.pack_into(" len(buf): buf.extend(bytes(cur - len(buf))) return off # Special links (+0xA8) and index table (+0xB0). if has_links: la = alloc(32 * n_links) lb = alloc(2 * n_link_idx) for k in range(n_link_idx): val = n_links if (corrupt_link_idx and k == 0) else (k % n_links) struct.pack_into(" 1 child leaf node -> leaf_data -> u16[n_polys]. root = alloc(0x60) child = alloc(0x60) leaf = alloc(0x20) lpolys = alloc(2 * n_polys) for k in range(n_polys): struct.pack_into("> 9 ox, oy = (sx - 256) * 128.0, (sy - 256) * 128.0 decl = entries if declared_entries is None else declared_entries struct.pack_into("I", 64) + bytes(56) sec2 = b"CHKS" + struct.pack(">I", 20) + bytes(12) table = bytes(0x40) first = 16 + len(table) hdr = b"PSIN" + struct.pack(">I", first) + struct.pack("0, broken chain, qt cycle. streams += build_navmesh(corrupt_checksum=True, corrupt_vidx=True, corrupt_link_idx=True, corrupt_null_vol=True, corrupt_chain=True, qt_cycle=True) # 4. Corrupt grid: bad control byte + duplicate value. streams += build_grid(bad_ctrl=True, dup_value=True) # 5. Adversarial OOM-DoS grid: u32@0x14 == u32@0x50 == 0xFFFFFFFF with 8 empty groups. streams += build_grid(groups=8, entries=0, declared_entries=0xFFFFFFFF) # 6. Truncated PSIN (placed last so it does not consume later streams). streams += build_psin(truncate=True) with tempfile.TemporaryDirectory() as tmp: arc = os.path.join(tmp, "bad.rpf") make_rpf(arc, streams) doc = nd.scan(arc, deep=True) json.dumps(doc, allow_nan=False) # Separate archives for MAX_STREAMS-capped resources so they cannot swallow other test fixtures. arc_cap_0drp = os.path.join(tmp, "cap_0drp.rpf") make_rpf(arc_cap_0drp, build_0drp(total_size=0x2000, bad_bm_streams=100) + [bytes(64)] * (nd.MAX_STREAMS + 2)) doc_cap_0drp = nd.scan(arc_cap_0drp, deep=True) arc_cap_psin = os.path.join(tmp, "cap_psin.rpf") big_psin = b"PSIN" + struct.pack(">I", 0x2000) + struct.pack("4sI", b"PSIN", 64) + bytes(56)) out = os.path.join(tmp, "out.json") proc = subprocess.run([sys.executable, "-I", TOOL, carve, "--quiet", "--out", out], capture_output=True, text=True) self.assertEqual(proc.returncode, 0, proc.stderr) with open(out, encoding="utf-8") as f: doc = json.load(f) self.assertEqual(doc["resources"]["psin"]["resources"], 1) self.assertEqual(doc["resources"]["psin"]["incomplete"], 1) self.assertEqual(doc["psin"]["complete"], 0) def test_header_only_psin_does_not_swallow_the_next_resource(self): with tempfile.TemporaryDirectory() as tmp: carve = os.path.join(tmp, "carve") os.mkdir(carve) with open(os.path.join(carve, "000000000000.bin"), "wb") as f: f.write(struct.pack(">4sI", b"PSIN", 64) + bytes(56)) with open(os.path.join(carve, "000000000040.bin"), "wb") as f: f.write(struct.pack(">4sI", b"PSIN", 64) + bytes(56) + struct.pack(">4sI", b"SECT", 64) + bytes(56)) out = os.path.join(tmp, "out.json") proc = subprocess.run([sys.executable, "-I", TOOL, carve, "--quiet", "--out", out], capture_output=True, text=True) self.assertEqual(proc.returncode, 0, proc.stderr) with open(out, encoding="utf-8") as f: doc = json.load(f) self.assertEqual(doc["resources"]["psin"]["resources"], 2) self.assertEqual(doc["resources"]["psin"]["incomplete"], 1) self.assertEqual(doc["psin"]["complete"], 1) def test_carved_directory_mode_and_window_limit(self): sector = (260 << 9) | 250 p0, p1 = build_0drp(total_size=0x1000, split_at=0x1000, node_count=2, override_n4e=0) nav = build_navmesh(sector=sector)[0] g0, g1 = build_grid(sector=sector, two_streams=True) with tempfile.TemporaryDirectory() as tmp: empty_dir = os.path.join(tmp, "empty") os.mkdir(empty_dir) edoc = nd.scan(empty_dir, deep=True) self.assertEqual(edoc["resources"], {}) carve = os.path.join(tmp, "carve") os.mkdir(carve) for off, blob in ((0x001000, p0), (0x002000, p1), (0x003000, nav), (0x004000, g0), (0x005000, g1)): with open(os.path.join(carve, f"{off:012x}.bin"), "wb") as f: f.write(blob) doc = nd.scan(carve, deep=True) self.assertEqual(doc["mode"], "directory") self.assertEqual(doc["resources"]["0drp"]["resources"], 1) self.assertEqual(doc["resources"]["navmesh"]["resources"], 1) self.assertEqual(doc["resources"]["grid"]["resources"], 1) self.assertEqual(doc["0drp"]["pages_4k_boundary"], {"zero": 1}) for cls, table in doc["checks"].items(): for name, counts in table.items(): self.assertEqual(counts["fail"], 0, f"{cls}.{name} failed: {counts}") # Window --limit stops after a resource whose >=64 B continuation crosses --limit. arc = os.path.join(tmp, "win.rpf") offs = make_rpf(arc, [g0, g1, nav]) win = nd.scan(arc, start=offs[0], limit=offs[1] - offs[0], deep=True) self.assertEqual(win["resources"]["grid"]["resources"], 1) self.assertNotIn("navmesh", win["resources"]) # The continuation starts at the window's end: decoded as part of the grid, but carved past the # window, so the carver counts match navmesh_index.py on the same window (#766). self.assertEqual(win["carver_streams"]["streams"], 1) self.assertEqual(win["carver_streams"]["past_window"], 1) c = win["carver_streams"] self.assertEqual(c["stored"] + c["zero_padding"] + c["unread"], win["span"]) def test_limit_inside_a_stream_counts_nothing_past_the_window(self): """--limit ending inside the first of two streams: nothing is carved, and the byte classes add up to the span, as navmesh_index.py reports for the same window.""" import hashlib noisy = lambda seed: b"".join(hashlib.sha256(bytes([seed, i])).digest() for i in range(128)) with tempfile.TemporaryDirectory() as tmp: arc = os.path.join(tmp, "w.rpf") offs = make_rpf(arc, [noisy(1), noisy(2)]) doc = nd.scan(arc, start=offs[0], limit=0x100) c = doc["carver_streams"] self.assertEqual((c["streams"], c["stored"]), (0, 0)) self.assertEqual(c["stored"] + c["zero_padding"] + c["unread"], doc["span"]) self.assertEqual(c["past_window"], 1) def test_cli_rejects_shared_report_destination(self): with tempfile.TemporaryDirectory() as tmp: archive = os.path.join(tmp, "nav.rpf") make_rpf(archive, build_0drp()) output = os.path.join(tmp, "nav.navmesh-decode.json") result = subprocess.run( [sys.executable, "-I", TOOL, archive, "--csv", output, "--quiet"], cwd=tmp, capture_output=True, text=True, ) self.assertEqual(result.returncode, 2, result.stderr) self.assertIn("--out and --csv must use different paths", result.stderr) self.assertFalse(os.path.exists(output)) def test_cli_creates_missing_output_folders(self): with tempfile.TemporaryDirectory() as tmp: archive = os.path.join(tmp, "nav.rpf") make_rpf(archive, build_0drp()) out_json = os.path.join(tmp, "reports", "deep", "nav.json") out_csv = os.path.join(tmp, "tables", "nav.csv") result = subprocess.run( [sys.executable, "-I", TOOL, archive, "--out", out_json, "--csv", out_csv, "--quiet"], capture_output=True, text=True, check=False, ) self.assertEqual(result.returncode, 0, result.stderr) self.assertNotIn("Traceback", result.stderr) with open(out_json, encoding="utf-8") as f: self.assertEqual(json.load(f)["resources"]["0drp"]["resources"], 1) with open(out_csv, newline="", encoding="utf-8") as f: self.assertEqual(len(list(csv.DictReader(f))), 1) def test_cli_refuses_to_overwrite_its_input(self): with tempfile.TemporaryDirectory() as tmp: archive = os.path.join(tmp, "nav.rpf") make_rpf(archive, build_0drp()) with open(archive, "rb") as f: original = f.read() for flag in ("--out", "--csv"): result = subprocess.run( [sys.executable, "-I", TOOL, archive, flag, archive, "--quiet"], capture_output=True, text=True, check=False, ) self.assertEqual(result.returncode, 2, result.stderr) self.assertIn("would overwrite the input", result.stderr) self.assertNotIn("Traceback", result.stderr) with open(archive, "rb") as f: self.assertEqual(f.read(), original, f"{flag} touched the input") def test_cli_rejects_bad_arguments_and_files(self): with tempfile.TemporaryDirectory() as tmp: empty = os.path.join(tmp, "empty.rpf") with open(empty, "wb"): pass tiny = os.path.join(tmp, "tiny.rpf") with open(tiny, "wb") as f: f.write(b"9FPR123") bad_ver = os.path.join(tmp, "badver.rpf") with open(bad_ver, "wb") as f: f.write(b"6FPR" + bytes(32)) arc = os.path.join(tmp, "ok.rpf") make_rpf(arc, build_0drp()) for args in ( [arc, "--limit", "0"], [arc, "--limit", "-5"], [arc, "--start", "-1"], [arc, "--start", "999999"], [empty], [tiny], [bad_ver], [tmp, "--limit", "64"], ): proc = subprocess.run([sys.executable, "-I", TOOL, *args], capture_output=True, text=True) self.assertNotEqual(proc.returncode, 0, f"expected failure for {args}") self.assertNotIn("Traceback", proc.stderr) if __name__ == "__main__": unittest.main()