"""Synthetic unit tests for `tools/ped_catalogues.py`. All test inputs are synthesized in memory or inside a temporary directory: no game files, no real asset names, and no retail hashes are used. python -I tests/test_ped_catalogues.py """ from __future__ import annotations import io import json import os 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__))) TOOLS = os.path.join(ROOT, "tools") sys.path.insert(0, TOOLS) import odrp_7a # noqa: E402 import ped_catalogues as pc # noqa: E402 def _encode_ptr(block_1based: int, byte_offset: int) -> int: return (byte_offset << 20) | (block_1based & 0xFFFFF) def _align16(n: int) -> int: return (n + 15) & ~15 def build_synthetic_0drp( blocks: list[tuple[int, bytes]], *, root_block: int = 1, truncate_by: int = 0, ) -> bytes: """Build a valid standalone `0DRP` v122 resource buffer from a 1-based list of `(key, payload)`.""" # Layout: # +0x00..+0x5f: 0x60-byte 0DRP/0x7a header # +0x60.. : minimal struct table (1 struct of 32 bytes matching root block type) # aligned : block directory (nb * 16 bytes) # aligned : block payloads root_type = blocks[root_block - 1][0] if 1 <= root_block <= len(blocks) else 0x11111111 q28 = 0x60 struct_table = struct.pack(" 0: return bytes(out[:-truncate_by]) return bytes(out) def build_synthetic_psin( blocks: list[tuple[int, bytes]], *, root_block: int = 1, ) -> bytes: """Build a valid standalone `PSIN` container from a 1-based list of `(key, payload)`.""" nb = len(blocks) table_bytes = 8 + nb * 16 + 8 # header(8) + nb*16 + 8 bytes of 0x70 padding assert table_bytes % 16 == 0 payloads = bytearray() for _key, payload in blocks: payloads.extend(payload) pad = _align16(len(payloads)) - len(payloads) if pad: payloads.extend(b"\x00" * pad) first_section = table_bytes + len(payloads) out = bytearray() out.extend(b"PSIN") out.extend(struct.pack(">I", first_section)) for key, payload in blocks: out.extend(struct.pack("I", 8 + len(lsch_pay)) + lsch_pay) out.extend(b"LENM" + struct.pack(">I", 8)) lrsc_pay = bytearray(80) lrsc_pay[0:4] = b"0DRP" struct.pack_into("I", 8 + len(lrsc_pay)) + lrsc_pay) out.extend(b"CHKS" + struct.pack(">I", 20) + b"\x00" * 12) return bytes(out) def _pack_root(bucket0_count: int, bucket0_ptr: int = 0, bucket1_count: int = 0, bucket1_ptr: int = 0) -> bytes: buf = bytearray(pc.CATALOG_ROOT_SIZE) struct.pack_into(" bytes: buf = bytearray(pc.PRESET_STRIDE) struct.pack_into(" bytes: buf = bytearray(pc.STATE_STRIDE) struct.pack_into(" tuple[list[tuple[int, bytes]], dict[str, int]]: """Build a synthetic `0x8dcb4cf5` catalogue exercising tags, 2-hop inheritance, states, and `cull_drawable`. Uses non-default synthetic block IDs (`0x101` for tags, `0x103` for `0xb70a22c1` ext maps) to verify the parser does not hardcode `0x100` / `0x101`. """ names = { "direct_head": "synth_head_direct_00", "inherited_head": "synth_head_inherited_01", "state_tag_item": "synth_hat_statetag_02", "h0_only_body": "synth_body_full_03", "cull_target": "synth_body_cull_03", } hashes = {f"{k}_j32": pc.joaat32(v) for k, v in names.items()} hashes.update({f"{k}_m64": pc.murmur64(v) for k, v in names.items()}) # Block numbering (1-based): # 1: 0x8dcb4cf5 root # 2: 0xf795e8ba presets (5 presets) # 3: 0x37e52277 states (4 states) # 4: tag_block_type (24 B slots) # 5: 0x4a u32 tag values # 6: ext_block_type (16 B slots for 0xb70a22c1) # 7: 0x3d780b74 cull_drawable targets (16 B each) tag_vals = bytearray() tag_slots = bytearray() def add_tag_map(entries: list[tuple[int, list[int]]]) -> tuple[int, int]: slot_off = len(tag_slots) for tk, vals in entries: val_off = len(tag_vals) for v in vals: tag_vals.extend(struct.pack(" block 7+0 ext_block = bytearray() ext_block.extend(struct.pack(" cull_target s0 = _pack_state( state_id=0x101, drawable_hash=hashes["direct_head_m64"], albedo_hash=0xAAA0000000000001, normal_hash=0xBBB0000000000001, extra_hash=0xCCC0000000000001, ) s1 = _pack_state( state_id=0x102, drawable_hash=0, albedo_hash=0xAAA0000000000002, normal_hash=0xBBB0000000000002, ) s2 = _pack_state( state_id=0x103, drawable_hash=0, albedo_hash=0xAAA0000000000003, normal_hash=0, tag_ptr=t_state_ptr, tag_count=t_state_cnt, ) s3 = _pack_state( state_id=0x104, flags=7, drawable_hash=hashes["h0_only_body_m64"], albedo_hash=0xAAA0000000000004, normal_hash=0xBBB0000000000004, ext_ptr=_encode_ptr(6, 0), ext_count=2, ) states_block = s0 + s1 + s2 + s3 # Presets (block 2): 5 presets # 0x1000: direct head (state 0) # 0x2000: grandparent (has drawable tag 0x1c114e61, 0 states) # 0x2001: middle parent (parent_id=0x2000, no drawable tag, 0 states) # 0x2002: grandchild (parent_id=0x2001, overrides non-drawable tag, state 1) # 0x3000: garment with state 2 (state tag) and state 3 (h0 + cull_drawable) p0 = _pack_preset( preset_id=0x1000, parent_id=0, state_count=1, state_ptr=_encode_ptr(3, 0), category=pc.HEAD_CATEGORY, tag_ptr=t_direct_ptr, tag_count=t_direct_cnt, ) p1 = _pack_preset( preset_id=0x2000, parent_id=0, state_count=0, category=pc.HEAD_CATEGORY, tag_ptr=t_grand_ptr, tag_count=t_grand_cnt, ) p2 = _pack_preset( preset_id=0x2001, parent_id=0x2000, state_count=0, category=pc.HEAD_CATEGORY, ) p3 = _pack_preset( preset_id=0x2002, parent_id=0x2001, state_count=1, state_ptr=_encode_ptr(3, pc.STATE_STRIDE), category=pc.HEAD_CATEGORY, tag_ptr=t_child_override_ptr, tag_count=t_child_override_cnt, ) p4 = _pack_preset( preset_id=0x3000, parent_id=0, state_count=2, state_ptr=_encode_ptr(3, 2 * pc.STATE_STRIDE), category=0x3817131D, ) presets_block = p0 + p1 + p2 + p3 + p4 root_block = _pack_root(bucket0_count=5, bucket0_ptr=_encode_ptr(2, 0)) blocks = [ (pc.CATALOG_ROOT_HASH, root_block), (pc.PRESET_STRUCT_HASH, presets_block), (pc.STATE_STRUCT_HASH, states_block), (tag_block_type, bytes(tag_slots)), (pc.TAG_VALUE_BLOCK_TYPE, bytes(tag_vals)), (ext_block_type, bytes(ext_block)), (pc.CULL_DRAWABLE_STRUCT_HASH, cull_block), ] return blocks, hashes def build_synthetic_rpf(streams: list[bytes]) -> bytes: """Build a minimal synthetic RPF9 (`9FPR`) archive with 16-byte-aligned zlib streams.""" data_start = 0x100 out = bytearray(data_start) out[0:4] = b"9FPR" struct.pack_into(" self-cycle (parent_id = 0x10) # 0x20 -> 0x21 -> 0x20 (2-cycle) # 0x30 -> 0x9999 (unresolved parent) presets_block = ( _pack_preset(preset_id=0x10, parent_id=0x10) + _pack_preset(preset_id=0x20, parent_id=0x21) + _pack_preset(preset_id=0x21, parent_id=0x20) + _pack_preset(preset_id=0x30, parent_id=0x9999) ) blocks = [ (pc.CATALOG_ROOT_HASH, _pack_root(bucket0_count=4, bucket0_ptr=_encode_ptr(2, 0))), (pc.PRESET_STRUCT_HASH, presets_block), ] cat = pc.parse_catalogue_strict(build_synthetic_0drp(blocks), source="cycles.0drp") self.assertEqual(cat.stats["parent_cycles"], 3) self.assertEqual(cat.stats["unresolved_parents"], 1) self.assertTrue(any("cycle" in w for w in cat.warnings)) # Cycle guards on both resolve helpers terminate cleanly tags_self, chain_self, cyc_self = pc.resolve_ancestor_tags(cat, cat.presets_by_id[0x10]) self.assertTrue(cyc_self) self.assertEqual(tags_self, {}) self.assertEqual(chain_self, ()) tags_two, chain_two, cyc_two = pc.resolve_ancestor_tags(cat, cat.presets_by_id[0x20]) self.assertTrue(cyc_two) self.assertEqual(chain_two, (0x21,)) eff_two, eff_chain, eff_cyc = pc.resolve_effective_tags(cat, cat.presets_by_id[0x20]) self.assertTrue(eff_cyc) self.assertEqual(eff_two, {}) self.assertEqual(eff_chain, (0x21,)) tags_unres, chain_unres, cyc_unres = pc.resolve_ancestor_tags(cat, cat.presets_by_id[0x30]) self.assertFalse(cyc_unres) self.assertEqual(tags_unres, {}) self.assertEqual(chain_unres, ()) def test_malformed_and_truncated_inputs(self): # Empty / garbage self.assertIsNone(pc.parse_catalogue(b"")) self.assertIsNone(pc.parse_catalogue(b"not a catalogue")) with self.assertRaises(ValueError): pc.parse_catalogue_strict(b"not a catalogue") # Truncated 0DRP blocks, _ = build_rich_catalogue_blocks() full_0drp = build_synthetic_0drp(blocks) truncated = full_0drp[:-32] self.assertIsNone(pc.parse_catalogue(truncated)) with self.assertRaisesRegex(ValueError, "truncated"): pc.parse_catalogue_strict(truncated) # Wrong root struct type (non-catalogue 0DRP and PSIN) non_cat = [(0xD3593FA6, b"\x00" * 64)] self.assertIsNone(pc.parse_catalogue(build_synthetic_0drp(non_cat))) self.assertIsNone(pc.parse_catalogue(build_synthetic_psin(non_cat))) with self.assertRaisesRegex(ValueError, "expected 0x8dcb4cf5"): pc.parse_catalogue_strict(build_synthetic_0drp(non_cat)) # Malformed internal pointers inside a valid 0x8dcb4cf5 container produce warnings, never crash bad_ext = struct.pack(" truncation warning state_ptr=_encode_ptr(3, 0), ) bad_blocks = [ (pc.CATALOG_ROOT_HASH, _pack_root(bucket0_count=1, bucket0_ptr=_encode_ptr(2, 0))), (pc.PRESET_STRUCT_HASH, bad_preset), (pc.STATE_STRUCT_HASH, bad_state), (0x101, bad_ext), (pc.TAG_VALUE_BLOCK_TYPE, b"\x00" * 16), ] cat_bad = pc.parse_catalogue_strict(build_synthetic_0drp(bad_blocks), source="bad_ptrs.0drp") self.assertEqual(len(cat_bad.presets), 1) self.assertEqual(len(cat_bad.presets[0].states), 1) self.assertIsNone(cat_bad.presets[0].states[0].cull_drawable) self.assertGreaterEqual(len(cat_bad.warnings), 3) def test_rpf_and_carved_dir_continuation_joining(self): blocks, _ = build_rich_catalogue_blocks() raw_0drp = build_synthetic_0drp(blocks) raw_psin = build_synthetic_psin(blocks) non_cat = build_synthetic_0drp([(0xD3593FA6, b"\x00" * 64)]) noise = b"unrelated stream payload" * 10 # Split both catalogues into 2 streams to exercise multi-stream continuation joining! split_0drp = len(raw_0drp) // 2 split_psin = len(raw_psin) // 2 rpf_bytes = build_synthetic_rpf([ noise, raw_0drp[:split_0drp], raw_0drp[split_0drp:], non_cat, raw_psin[:split_psin], raw_psin[split_psin:], ]) with tempfile.TemporaryDirectory() as tmp: rpf_path = os.path.join(tmp, "synth.rpf") with open(rpf_path, "wb") as fh: fh.write(rpf_bytes) rep = pc.census(rpf_path) self.assertEqual(rep["catalogues"], 2) self.assertEqual(rep["by_framing"], {"0drp": 1, "psin": 1}) self.assertEqual(rep["presets"], 10) self.assertEqual(rep["states"], 8) self.assertEqual(rep["states_with_cull_drawable"], 2) self.assertEqual(rep["catalogues_with_cull_drawable"], 2) self.assertEqual(rep["warnings"], 0) # Also test carved directory with index.json joining a 2-stream 0DRP carve_dir = os.path.join(tmp, "carved") os.makedirs(carve_dir) part0 = raw_0drp[:split_0drp] part1 = raw_0drp[split_0drp:] with open(os.path.join(carve_dir, "000000000100.bin"), "wb") as fh: fh.write(part0) with open(os.path.join(carve_dir, "000000000300.bin"), "wb") as fh: fh.write(part1) with open(os.path.join(carve_dir, "index.json"), "w", encoding="utf-8") as fh: json.dump( { "files": [ {"offset": 0x100, "stored": 0x1F5, "file": "000000000100.bin"}, {"offset": 0x300, "stored": 0x200, "file": "000000000300.bin"}, ] }, fh, ) dir_rep = pc.census(carve_dir) self.assertEqual(dir_rep["catalogues"], 1) self.assertEqual(dir_rep["by_framing"], {"0drp": 1}) self.assertEqual(dir_rep["presets"], 5) def test_carve_index_rows_with_bad_types_are_skipped(self): blocks, _ = build_rich_catalogue_blocks() raw = build_synthetic_0drp(blocks) split = len(raw) // 2 with tempfile.TemporaryDirectory() as tmp: with open(os.path.join(tmp, "000000000100.bin"), "wb") as fh: fh.write(raw[:split]) with open(os.path.join(tmp, "000000000300.bin"), "wb") as fh: fh.write(raw[split:]) rows = [ {"offset": 0, "file": 5}, # non-string file name {"offset": True}, # bool offset {"offset": -16, "file": "x.bin"}, # negative offset "not a row", {"offset": 0x100, "stored": 0x1F5, "file": "000000000100.bin"}, # the continuation row's file name is not a string: falls back to .bin {"offset": 0x300, "stored": 0x200, "file": 5}, ] with open(os.path.join(tmp, "index.json"), "w", encoding="utf-8") as fh: json.dump({"files": rows}, fh) cats = list(pc.iter_catalogues_in_dir(tmp)) self.assertEqual(len(cats), 1) def test_large_single_stream_and_adjacent_complete_0drp_in_rpf(self): # 1. A >1 MiB single zlib stream followed by trailing bytes (exercises multi-chunk decompress + eof/unused_data). blocks_big, _ = build_rich_catalogue_blocks() blocks_big.append((0x99999999, b"\x00" * (1_200_000))) big_0drp = build_synthetic_0drp(blocks_big) self.assertGreater(len(big_0drp), 1 << 20) # 2. A complete 64 KiB-multiple 0DRP immediately followed by another complete 0DRP # (must not swallow the second catalogue as a continuation). blocks_a, _ = build_rich_catalogue_blocks() base_a = build_synthetic_0drp(blocks_a) pad_len = 65536 - (len(base_a) % 65536) exact_64k_0drp = base_a + (b"\x00" * pad_len) self.assertEqual(len(exact_64k_0drp) % 65536, 0) second_0drp = build_synthetic_0drp(blocks_a) rpf_bytes = build_synthetic_rpf([big_0drp, exact_64k_0drp, second_0drp]) with tempfile.TemporaryDirectory() as tmp: rpf_path = os.path.join(tmp, "edge.rpf") with open(rpf_path, "wb") as fh: fh.write(rpf_bytes) rep = pc.census(rpf_path) self.assertEqual(rep["catalogues"], 3) self.assertEqual(rep["by_framing"], {"0drp": 3}) self.assertEqual(rep["presets"], 15) self.assertEqual(rep["warnings"], 0) def test_cli_census_inspect_resolve_and_guards(self): blocks, hashes = build_rich_catalogue_blocks() raw_0drp = build_synthetic_0drp(blocks) script = os.path.join(TOOLS, "ped_catalogues.py") py = [sys.executable, "-I", script] with tempfile.TemporaryDirectory() as tmp: cat_file = os.path.join(tmp, "sample.0drp") with open(cat_file, "wb") as fh: fh.write(raw_0drp) # inspect --json --out out_ins = os.path.join(tmp, "inspect.json") r1 = subprocess.run(py + ["inspect", cat_file, "--json", "--out", out_ins], capture_output=True, text=True) self.assertEqual(r1.returncode, 0, r1.stderr) doc_ins = json.loads(r1.stdout) self.assertEqual(doc_ins["framing"], "0drp") self.assertEqual(doc_ins["stats"]["presets"], 5) with open(out_ins, encoding="utf-8") as fh: self.assertEqual(json.load(fh), doc_ins) # census --json r2 = subprocess.run(py + ["census", cat_file, "--json"], capture_output=True, text=True) self.assertEqual(r2.returncode, 0, r2.stderr) doc_cen = json.loads(r2.stdout) self.assertEqual(doc_cen["catalogues"], 1) self.assertEqual(doc_cen["states_with_cull_drawable"], 1) # resolve --name --cull-only --json r3 = subprocess.run( py + ["resolve", cat_file, "--name", "synth_body_full_03", "--cull-only", "--json"], capture_output=True, text=True, ) self.assertEqual(r3.returncode, 0, r3.stderr) doc_res = json.loads(r3.stdout) self.assertEqual(doc_res["matches"], 1) self.assertEqual(doc_res["bindings"][0]["cull_drawable_hash"], f"{hashes['cull_target_m64']:016x}") # resolve --hash (32-bit joaat of inherited head) r4 = subprocess.run( py + ["resolve", cat_file, "--hash", f"0x{hashes['inherited_head_j32']:08x}", "--json"], capture_output=True, text=True, ) self.assertEqual(r4.returncode, 0, r4.stderr) doc_res4 = json.loads(r4.stdout) self.assertEqual(doc_res4["matches"], 1) self.assertEqual(doc_res4["bindings"][0]["match_kind"], "inherited_drawable_tag") self.assertEqual(doc_res4["bindings"][0]["parent_chain"], ["0x00002001", "0x00002000"]) # Refuses overwriting input file r5 = subprocess.run(py + ["census", cat_file, "--out", cat_file], capture_output=True, text=True) self.assertEqual(r5.returncode, 2) self.assertIn("overwrite", r5.stderr) # Private-use character in path under -X utf8=0 must not crash stdout weird_dir = os.path.join(tmp, "dir-\ue9c3") os.makedirs(weird_dir) weird_file = os.path.join(weird_dir, "cat-\ue9c3.0drp") with open(weird_file, "wb") as fh: fh.write(raw_0drp) r6 = subprocess.run( [sys.executable, "-I", "-X", "utf8=0", script, "census", weird_file], capture_output=True, ) self.assertEqual(r6.returncode, 0, r6.stderr.decode("utf-8", "replace")) self.assertNotIn("UnicodeEncodeError", r6.stderr.decode("utf-8", "replace")) def test_cli_out_path_guards_directory_inputs(self): blocks, _ = build_rich_catalogue_blocks() raw_0drp = build_synthetic_0drp(blocks) script = os.path.join(TOOLS, "ped_catalogues.py") py = [sys.executable, "-I", script] with tempfile.TemporaryDirectory() as tmp: cat_dir = os.path.join(tmp, "cats") sub_dir = os.path.join(cat_dir, "sub") sibling_dir = os.path.join(tmp, "cats_out") os.makedirs(sub_dir) os.makedirs(sibling_dir) cat_file = os.path.join(cat_dir, "sample.0drp") with open(cat_file, "wb") as fh: fh.write(raw_0drp) # census --out / -> exit 2, catalogue untouched r1 = subprocess.run(py + ["census", cat_dir, "--out", cat_file], capture_output=True, text=True) self.assertEqual(r1.returncode, 2) self.assertIn("inside input folder", r1.stderr) with open(cat_file, "rb") as fh: self.assertEqual(fh.read(), raw_0drp) # resolve --out / -> exit 2, catalogue untouched r2 = subprocess.run(py + ["resolve", cat_dir, "--out", cat_file], capture_output=True, text=True) self.assertEqual(r2.returncode, 2) self.assertIn("inside input folder", r2.stderr) with open(cat_file, "rb") as fh: self.assertEqual(fh.read(), raw_0drp) # census --out /sub/report.json (existing and non-existing nested dir) -> exit 2 nested_out = os.path.join(sub_dir, "report.json") r3 = subprocess.run(py + ["census", cat_dir, "--out", nested_out], capture_output=True, text=True) self.assertEqual(r3.returncode, 2) self.assertIn("inside input folder", r3.stderr) self.assertFalse(os.path.exists(nested_out)) missing_nested = os.path.join(cat_dir, "missing_sub", "report.json") r3b = subprocess.run(py + ["census", cat_dir, "--out", missing_nested], capture_output=True, text=True) self.assertEqual(r3b.returncode, 2) self.assertIn("inside input folder", r3b.stderr) # Relative path with '..' and trailing slash still resolves inside -> exit 2 trav_out = os.path.join(sibling_dir, "..", "cats", "sub", "report.json") r3c = subprocess.run( py + ["resolve", cat_dir + os.sep, "--out", trav_out], capture_output=True, text=True, ) self.assertEqual(r3c.returncode, 2) self.assertIn("inside input folder", r3c.stderr) self.assertFalse(os.path.exists(nested_out)) # Windows case and separator differences still match -> exit 2 if os.name == "nt": mixed_out = os.path.join(cat_dir, "SUB", "report.json").replace("\\", "/") r3d = subprocess.run(py + ["census", cat_dir, "--out", mixed_out], capture_output=True, text=True) self.assertEqual(r3d.returncode, 2) self.assertIn("inside input folder", r3d.stderr) self.assertFalse(os.path.exists(nested_out)) # Different drive letters must not raise ValueError self.assertFalse(pc._is_under_dir(r"Z:\elsewhere\report.json", r"C:\cats")) # Symlink outside pointing at a file inside -> exit 2, target untouched link_out = os.path.join(sibling_dir, "link.0drp") try: os.symlink(cat_file, link_out) except (OSError, NotImplementedError): link_out = None if link_out is not None: r_sym = subprocess.run(py + ["census", cat_dir, "--out", link_out], capture_output=True, text=True) self.assertEqual(r_sym.returncode, 2) self.assertIn("inside input folder", r_sym.stderr) with open(cat_file, "rb") as fh: self.assertEqual(fh.read(), raw_0drp) # inspect --out -> exit 2, file untouched r4 = subprocess.run(py + ["inspect", cat_file, "--out", cat_file], capture_output=True, text=True) self.assertEqual(r4.returncode, 2) self.assertIn("overwrite", r4.stderr) with open(cat_file, "rb") as fh: self.assertEqual(fh.read(), raw_0drp) # resolve --names-file --out -> exit 2, names untouched names_file = os.path.join(sibling_dir, "names.txt") with open(names_file, "w", encoding="utf-8") as fh: fh.write("synth_body_full_03\n") r5 = subprocess.run( py + ["resolve", cat_dir, "--names-file", names_file, "--out", names_file], capture_output=True, text=True, ) self.assertEqual(r5.returncode, 2) self.assertIn("overwrite", r5.stderr) with open(names_file, encoding="utf-8") as fh: self.assertEqual(fh.read(), "synth_body_full_03\n") # census --out /report.json (shares string prefix "_out") -> exit 0 sibling_out = os.path.join(sibling_dir, "report.json") r6 = subprocess.run(py + ["census", cat_dir, "--out", sibling_out], capture_output=True, text=True) self.assertEqual(r6.returncode, 0, r6.stderr) with open(sibling_out, encoding="utf-8") as fh: rep = json.load(fh) self.assertEqual(rep["catalogues"], 1) self.assertEqual(rep["presets"], 5) class PedCataloguesHardeningTests(unittest.TestCase): """Regression tests for filter handling, BOM/UTF-8 safety, traversal guards, depth cap, bounds, and atomic JSON.""" @staticmethod def _cli(*args: str) -> subprocess.CompletedProcess: return subprocess.run( [sys.executable, "-I", os.path.join(TOOLS, "ped_catalogues.py"), *args], capture_output=True, text=True, timeout=60, ) def test_empty_names_file_and_blank_name_keep_filtering_active(self): blocks, _ = build_rich_catalogue_blocks() raw = build_synthetic_0drp(blocks) with tempfile.TemporaryDirectory() as tmp: cat_file = os.path.join(tmp, "sample.0drp") with open(cat_file, "wb") as fh: fh.write(raw) empty_names = os.path.join(tmp, "empty_names.txt") with open(empty_names, "w", encoding="utf-8", newline="\n") as fh: fh.write("# comment only\n \n\n") r1 = self._cli("resolve", cat_file, "--names-file", empty_names, "--json") self.assertEqual(r1.returncode, 0, r1.stderr) self.assertEqual(json.loads(r1.stdout)["matches"], 0) r2 = self._cli("resolve", cat_file, "--name", " ", "--json") self.assertEqual(r2.returncode, 0, r2.stderr) self.assertEqual(json.loads(r2.stdout)["matches"], 0) def test_utf8_bom_and_invalid_utf8_in_names_file_and_carved_index(self): blocks, _ = build_rich_catalogue_blocks() raw = build_synthetic_0drp(blocks) split = len(raw) // 2 with tempfile.TemporaryDirectory() as tmp: cat_file = os.path.join(tmp, "sample.0drp") with open(cat_file, "wb") as fh: fh.write(raw) # UTF-8 BOM on line 1 of --names-file must still match the first name bom_names = os.path.join(tmp, "bom_names.txt") with open(bom_names, "wb") as fh: fh.write(b"\xef\xbb\xbfsynth_body_full_03\n") r_bom = self._cli("resolve", cat_file, "--names-file", bom_names, "--json") self.assertEqual(r_bom.returncode, 0, r_bom.stderr) doc_bom = json.loads(r_bom.stdout) self.assertEqual(doc_bom["matches"], 1) self.assertEqual(doc_bom["bindings"][0]["matched_name"], "synth_body_full_03") # Invalid UTF-8 in --names-file exits cleanly with code 2 (no traceback) bad_names = os.path.join(tmp, "bad_names.txt") with open(bad_names, "wb") as fh: fh.write(b"\xff\xfeinvalid") r_bad = self._cli("resolve", cat_file, "--names-file", bad_names) self.assertEqual(r_bad.returncode, 2) self.assertNotIn("Traceback", r_bad.stderr) self.assertIn("ERROR:", r_bad.stderr) # Carved index.json with UTF-8 BOM joins continuation streams cleanly bom_dir = os.path.join(tmp, "bom_carve") os.makedirs(bom_dir) with open(os.path.join(bom_dir, "000000000100.bin"), "wb") as fh: fh.write(raw[:split]) with open(os.path.join(bom_dir, "000000000300.bin"), "wb") as fh: fh.write(raw[split:]) idx_payload = json.dumps({ "files": [ {"offset": 0x100, "stored": 0x1F5, "file": "000000000100.bin"}, {"offset": 0x300, "stored": 0x200, "file": "000000000300.bin"}, ] }).encode("utf-8") with open(os.path.join(bom_dir, "index.json"), "wb") as fh: fh.write(b"\xef\xbb\xbf" + idx_payload) self.assertEqual(len(list(pc.iter_catalogues_in_dir(bom_dir))), 1) # Invalid UTF-8 index.json falls back to directory walk without crashing bad_idx_dir = os.path.join(tmp, "bad_idx") os.makedirs(bad_idx_dir) with open(os.path.join(bad_idx_dir, "index.json"), "wb") as fh: fh.write(b"\xff\xfe{not utf8}") with open(os.path.join(bad_idx_dir, "good.0drp"), "wb") as fh: fh.write(raw) self.assertEqual(len(list(pc.iter_catalogues_in_dir(bad_idx_dir))), 1) def test_carved_index_blocks_path_traversal(self): blocks, _ = build_rich_catalogue_blocks() raw = build_synthetic_0drp(blocks) split = len(raw) // 2 with tempfile.TemporaryDirectory() as tmp: outside = os.path.join(tmp, "outside.0drp") with open(outside, "wb") as fh: fh.write(raw) outside_part1 = os.path.join(tmp, "outside_part1.bin") with open(outside_part1, "wb") as fh: fh.write(raw[split:]) carve_dir = os.path.join(tmp, "carved") os.makedirs(carve_dir) with open(os.path.join(carve_dir, "part0.bin"), "wb") as fh: fh.write(raw[:split]) with open(os.path.join(carve_dir, "index.json"), "w", encoding="utf-8", newline="\n") as fh: json.dump( { "files": [ {"offset": 0x100, "stored": 0x100, "file": "../outside.0drp"}, {"offset": 0x400, "stored": 0x1F5, "file": "part0.bin"}, {"offset": 0x600, "stored": 0x200, "file": "../outside_part1.bin"}, ] }, fh, ) self.assertEqual(list(pc.iter_catalogues_in_dir(carve_dir)), []) def test_exact_max_parent_depth_chain_does_not_warn_and_max_depth_validation(self): # Clean chain of exactly MAX_PARENT_DEPTH hops (last ancestor has parent_id=0): no cap warning. exact_presets = bytearray() for idx in range(pc.MAX_PARENT_DEPTH + 1): pid = 0x1000 + idx parent_id = (0x1000 + idx + 1) if idx < pc.MAX_PARENT_DEPTH else 0 exact_presets.extend(_pack_preset(preset_id=pid, parent_id=parent_id)) exact_blocks = [ (pc.CATALOG_ROOT_HASH, _pack_root(bucket0_count=pc.MAX_PARENT_DEPTH + 1, bucket0_ptr=_encode_ptr(2, 0))), (pc.PRESET_STRUCT_HASH, bytes(exact_presets)), ] cat_exact = pc.parse_catalogue_strict(build_synthetic_0drp(exact_blocks), source="exact_depth.0drp") self.assertEqual(cat_exact.stats["max_parent_depth"], pc.MAX_PARENT_DEPTH) self.assertEqual(cat_exact.warnings, ()) # Chain of MAX_PARENT_DEPTH + 1 hops DOES trigger the cap warning. over_presets = bytearray() for idx in range(pc.MAX_PARENT_DEPTH + 2): pid = 0x2000 + idx parent_id = (0x2000 + idx + 1) if idx < pc.MAX_PARENT_DEPTH + 1 else 0 over_presets.extend(_pack_preset(preset_id=pid, parent_id=parent_id)) over_blocks = [ (pc.CATALOG_ROOT_HASH, _pack_root(bucket0_count=pc.MAX_PARENT_DEPTH + 2, bucket0_ptr=_encode_ptr(2, 0))), (pc.PRESET_STRUCT_HASH, bytes(over_presets)), ] cat_over = pc.parse_catalogue_strict(build_synthetic_0drp(over_blocks), source="over_depth.0drp") self.assertTrue(any("reached cap" in w for w in cat_over.warnings)) # Invalid max_depth rejected cleanly root_preset = cat_exact.presets[0] for bad_depth in (-1, True): with self.assertRaises(ValueError): pc.resolve_ancestor_tags(cat_exact, root_preset, max_depth=bad_depth) with self.assertRaises(ValueError): pc.resolve_effective_tags(cat_exact, root_preset, max_depth=bad_depth) with self.assertRaises(ValueError): pc.resolve_preset_bindings(cat_exact, max_depth=bad_depth) def test_scan_bounds_and_inspect_max_inflate(self): blocks, _ = build_rich_catalogue_blocks() raw = build_synthetic_0drp(blocks) rpf_bytes = build_synthetic_rpf([raw]) with tempfile.TemporaryDirectory() as tmp: cat_file = os.path.join(tmp, "sample.0drp") zcat_file = os.path.join(tmp, "sample.0drp.z") rpf_path = os.path.join(tmp, "sample.rpf") with open(cat_file, "wb") as fh: fh.write(raw) with open(zcat_file, "wb") as fh: fh.write(zlib.compress(raw, 6)) with open(rpf_path, "wb") as fh: fh.write(rpf_bytes) for kwargs in ( {"limit": 0}, {"limit": -4}, {"limit": True}, {"start": -1}, {"start": True}, {"max_inflate": 0}, {"max_inflate": True}, ): with self.subTest(rpf_kwargs=kwargs): with self.assertRaises(ValueError): list(pc.iter_catalogues_in_rpf(rpf_path, **kwargs)) with self.assertRaises(ValueError): list(pc.iter_catalogues_in_file(cat_file, max_inflate=0)) with self.assertRaises(ValueError): list(pc.iter_catalogues_in_dir(tmp, max_inflate=-1)) # inspect enforces --max-inflate on both raw and zlib-compressed inputs r_raw = self._cli("inspect", cat_file, "--max-inflate", "64") self.assertEqual(r_raw.returncode, 2) self.assertIn("--max-inflate", r_raw.stderr) r_z = self._cli("inspect", zcat_file, "--max-inflate", str(len(raw) - 1)) self.assertEqual(r_z.returncode, 2) self.assertIn("--max-inflate", r_z.stderr) def test_atomic_write_json_rejects_nan_and_cli_handles_write_oserror(self): blocks, _ = build_rich_catalogue_blocks() raw = build_synthetic_0drp(blocks) with tempfile.TemporaryDirectory() as tmp: out_path = os.path.join(tmp, "out.json") sentinel = '{"keep": true}\n' with open(out_path, "w", encoding="utf-8", newline="\n") as fh: fh.write(sentinel) with self.assertRaises(ValueError): pc._write_json(out_path, {"bad": float("nan")}) with open(out_path, encoding="utf-8") as fh: self.assertEqual(fh.read(), sentinel) self.assertEqual(os.listdir(tmp), ["out.json"]) cat_file = os.path.join(tmp, "sample.0drp") with open(cat_file, "wb") as fh: fh.write(raw) for argv in ( ["census", cat_file, "--out", out_path], ["inspect", cat_file, "--out", out_path], ["resolve", cat_file, "--out", out_path], ): with self.subTest(argv=argv): err_buf = io.StringIO() with mock.patch.object(pc, "_write_json", side_effect=OSError("disk full")), mock.patch.object( sys, "stderr", err_buf ): rc = pc.main(argv) self.assertEqual(rc, 2) self.assertIn("ERROR:", err_buf.getvalue()) self.assertIn("disk full", err_buf.getvalue()) if __name__ == "__main__": unittest.main()