"""Synthetic tests for tools/psin_data.py (no game data: every hash is the joaat of an invented name).""" import json import os import struct import subprocess import sys import tempfile import unittest ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TOOL = os.path.join(ROOT, "tools", "psin_data.py") sys.path.insert(0, os.path.join(ROOT, "tools")) sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import psin_data as D # noqa: E402 from test_psin_index import joaat, make_lenm, make_lsch, make_section # noqa: E402 def ptr(block, offset=0): """A PSIN pointer: block number in the low 20 bits, byte offset above.""" return block | (offset << 20) def make_container(blocks, structs, enums=(), root=1, end_row=True, fill=b"\xaa" * 8): """blocks: [(type, bytes)]. Returns a complete PSIN container with LSCH, LENM, LRSC (root at +0x10) and CHKS.""" rows = b"".join(struct.pack("I", first + len(sections) + 16) + b"\0" * 4) return b"PSIN" + struct.pack(">I", first) + rows + bytes(data) + sections ROOT_T, ITEM_T, STR_T = joaat("RootThing"), joaat("ItemThing"), 0x10 KIND = joaat("KindEnum") # RootThing (0x90 bytes): every container shape the decoder reads. ROOT_MEMBERS = [ (0x100, 0, 0x05, 0, 0, ITEM_T), # 0: element descriptor, ItemThing (0x100, 0, 0x15, 0, 0, 0), # 1: element descriptor, u32 (0x100, 0, 0x4A, 0, 0, 0), # 2: element descriptor, u32 hash (map key) (joaat("items"), 0x00, 0x5C, 0, 0, 0), # {u32 count, u32 capacity, ptr} -> ItemThing[] (joaat("values"), 0x10, 0x52, 0, 1, 0), # {ptr, u16 count, u16 capacity} -> u32[] (joaat("sorted"), 0x20, 0x71, 0, 0, 2 | (1 << 16)), # binary map u32 hash -> u32 (joaat("hashed"), 0x38, 0x75, 0, 0, 2 | (1 << 16)), # SwissTable u32 hash -> u32 (joaat("open"), 0x48, 0x73, 0, 0, 2 | (1 << 16)), # open addressing u32 hash -> u32 (joaat("child"), 0x58, 0x07, 0, 0, 0), # pointer to an ItemThing block (joaat("label"), 0x60, 0x42, 0, 0, 0), # string pointer (joaat("short"), 0x68, 0x44, 0, 0, 0), # 16-byte string, stored in place (joaat("kind"), 0x78, 0x62, 0, 0, KIND), # 32-bit enum (joaat("fixed"), 0x7C, 0x50, 0, 1, 3), # u32[3] in place (joaat("odd"), 0x88, 0x77, 0, 0, 0), # a type this tool does not decode ] SCHEMA = [ (ROOT_T, 0x1, 0x90, 3, ROOT_MEMBERS), (ITEM_T, 0x2, 0x8, 2, [(joaat("x"), 0, 0x21, 0, 0, 0), (joaat("n"), 4, 0x15, 0, 0, 0)]), ] ENUMS = [(KIND, 0x3, [(0, joaat("KIND_A")), (1, joaat("KIND_B"))])] def sample(kind=1): """Blocks: 1 root, 2 ItemThing[2], 3 u32[3], 4 map pairs, 5 SwissTable group, 6 open slots, 7 one ItemThing, 8 strings.""" k1, k2 = joaat("alpha"), joaat("beta") lo, hi = sorted((k1, k2)) root = bytearray(0x90) struct.pack_into("I", blob, 4)[0] blocks, fills = D.block_table(blob, first) self.assertTrue(fills) self.assertEqual([(t, s) for t, _, s in blocks], [(0x15, 4), (0x16, 17)]) self.assertEqual(blocks[0][1] % 16, 0) self.assertEqual(blocks[1][1], blocks[0][1] + 16) def test_missing_end_row(self): blob = make_container([(0x15, b"\0" * 4)], [], end_row=False) with self.assertRaisesRegex(ValueError, "fill|padding"): D.block_table(blob, struct.unpack_from(">I", blob, 4)[0]) def test_bad_fill(self): blob = make_container([(0x15, b"\0" * 4)], [], fill=b"\0" * 8) with self.assertRaisesRegex(ValueError, "fill"): D.block_table(blob, struct.unpack_from(">I", blob, 4)[0]) def test_blocks_past_the_region_are_rejected(self): # A damaged size must not make the walker allocate gigabytes (review on #1077). blob = bytearray(make_container([(0x15, b"\0" * 4), (0x16, b"\0" * 32)], [])) struct.pack_into("I", blob, 4)[0]) stats = __import__("collections").Counter() self.assertFalse(D.measure(bytes(blob), stats)) self.assertEqual(stats["containers"], 0) def test_first_row_is_what_psin_index_calls_version(self): blob = make_container([(0x16, b"\0" * 0x230)], []) record = D.psin_index.parse(blob) self.assertEqual((record["version"], record["table_bytes"]), (0x16, 0x230)) class TestWalk(unittest.TestCase): def setUp(self): self.container = D.Container(sample()) self.stats = __import__("collections").Counter() self.tree = D.Walker(self.container, self.stats, keep=True).run() def test_every_byte_is_reached(self): self.assertEqual(self.stats["bytes reached"], self.stats["bytes"]) self.assertEqual(self.stats["blocks reached"], 8) def test_arrays(self): self.assertEqual(self.tree[f"{joaat('items'):08x}"], [{f"{joaat('x'):08x}": 1.5, f"{joaat('n'):08x}": 10}, {f"{joaat('x'):08x}": 2.5, f"{joaat('n'):08x}": 20}]) self.assertEqual(self.tree[f"{joaat('values'):08x}"], [1, 2, 3]) self.assertEqual(self.tree[f"{joaat('fixed'):08x}"], [7, 8, 9]) self.assertEqual(self.stats["array 5c block type matches element"], 1) self.assertEqual(self.stats["array 52 block type matches element"], 1) def test_maps(self): lo, hi = sorted((joaat("alpha"), joaat("beta"))) self.assertEqual(self.tree[f"{joaat('sorted'):08x}"], [[f"{lo:08x}", 100], [f"{hi:08x}", 200]]) self.assertEqual(sorted(v for _, v in self.tree[f"{joaat('hashed'):08x}"]), [11, 22]) self.assertEqual(self.tree[f"{joaat('open'):08x}"], [[f"{joaat('alpha'):08x}", 33]]) for check in ("map 71 first word 1", "map 71 keys ascending", "map 75 used slots == count", "map 75 groups a power of two", "map 73 used slots == count"): self.assertEqual(self.stats[check], 1, check) def test_pointers_and_strings(self): self.assertEqual(self.tree[f"{joaat('child'):08x}"], {f"{joaat('x'):08x}": 3.5, f"{joaat('n'):08x}": 30}) self.assertEqual(self.tree[f"{joaat('label'):08x}"], "hello") self.assertEqual(self.tree[f"{joaat('short'):08x}"], "abc") self.assertEqual(self.stats["short strings in place"], 1) def test_enum_and_undecoded_type(self): self.assertEqual(self.tree[f"{joaat('kind'):08x}"], 1) self.assertEqual(self.stats["enum value listed"], 1) self.assertEqual(self.stats["type 77 not decoded"], 1) self.assertIsNone(self.tree[f"{joaat('odd'):08x}"]) def test_enum_value_not_listed(self): stats = __import__("collections").Counter() D.Walker(D.Container(sample(kind=5)), stats).run() self.assertEqual(stats["enum value not listed"], 1) def test_32_bit_enum_matches_negative_and_high_values(self): # LENM lists both negative values and values >= 2**31 for 0x62 enums. for listed, stored in ((-1, -1), (0xFFFFFFF0, -16)): c = D.Container(sample(kind=stored)) c.enums[KIND]["values"].append({"value": listed, "name": joaat("KIND_X")}) stats = __import__("collections").Counter() tree = D.Walker(c, stats, keep=True).run() self.assertEqual(stats["enum value listed"], 1) self.assertEqual(stats["enum value not listed"], 0) self.assertEqual(tree[f"{joaat('kind'):08x}"], listed) def test_bad_pointer_is_counted_not_followed(self): blob = bytearray(sample()) root_at = D.Container(bytes(blob)).blocks[0][1] struct.pack_into("I", 16) + b"\x70" * 8 + make_section("CHKS", b"\0" * 8) self.assertFalse(D.measure(blob, stats)) self.assertEqual(stats["skipped: no LSCH or LRSC section"], 1) def test_root_out_of_range(self): blob = make_container([(ROOT_T, b"\0" * 0x90)], SCHEMA, ENUMS, root=3) stats = __import__("collections").Counter() self.assertTrue(D.measure(blob, stats)) self.assertEqual(stats["root out of range"], 1) class TestCli(unittest.TestCase): def run_tool(self, *args): return subprocess.run([sys.executable, "-I", TOOL, *args], capture_output=True, text=True) def test_counts_on_a_folder(self): with tempfile.TemporaryDirectory() as tmp: with open(os.path.join(tmp, "000000001000.bin"), "wb") as f: f.write(sample()) with open(os.path.join(tmp, "000000002000.bin"), "wb") as f: f.write(b"\x78\xda not psin") r = self.run_tool(tmp, "--json") self.assertEqual(r.returncode, 0, r.stderr) got = json.loads(r.stdout) self.assertEqual((got["PSIN files"], got["containers"], got["containers fully reached"]), (1, 1, 1)) self.assertEqual(got["bytes reached"], got["bytes"]) def test_dump_prints_the_tree(self): with tempfile.TemporaryDirectory() as tmp: path = os.path.join(tmp, "one.bin") with open(path, "wb") as f: f.write(sample()) r = self.run_tool(path, "--dump") self.assertEqual(r.returncode, 0, r.stderr) tree = json.loads(r.stdout)[f"{ROOT_T:08x}"] self.assertEqual(tree[f"{joaat('label'):08x}"], "hello") self.assertEqual(self.run_tool(tmp, "--dump").returncode, 2) def test_missing_source_is_one_line(self): r = self.run_tool(os.path.join(tempfile.gettempdir(), "no-such-psin-folder")) self.assertEqual(r.returncode, 2) self.assertEqual(len(r.stderr.strip().splitlines()), 1) def test_dump_of_a_bad_container_is_one_line(self): with tempfile.TemporaryDirectory() as tmp: path = os.path.join(tmp, "bad.bin") with open(path, "wb") as f: f.write(sample()[:-5]) r = self.run_tool(path, "--dump") self.assertEqual(r.returncode, 2) self.assertIn("incomplete", r.stderr) if __name__ == "__main__": unittest.main()