"""gamedata_maps.py must decode the measured MHIU and PAMH (HMAP) layouts. python -I tests/test_gamedata_maps.py Every fixture is synthetic. MHIU is a 44-byte header, a row table and packed u8 heights with a default fill. PAMH is HMAP v1.2: a row table, a max u8 array and a min u8 array. The archive tests build a carve-shaped directory and check the CLI, including a MHIU split across two 64 KiB streams. """ import json import os 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.path.join(TOOLS, "gamedata_maps.py") sys.path.insert(0, TOOLS) import gamedata_maps # noqa: E402 def mhiu_payload(width: int, height: int, rows, pixels: bytes, default: int = 23) -> bytes: """`rows` is a list of (start, count, values); offsets are assigned in order.""" table = bytearray() packed = bytearray() for start, count, values in rows: assert len(values) == count offset = len(packed) - start table += struct.pack(" bytes: rows = b"".join(struct.pack("max", p.stdout) def test_groups_mhiu_continuation_stream(self): payload = mhiu_payload(300, 1, [(0, 300, [i % 256 for i in range(300)])], pixels=b"\x07" * 90000) self.assertGreater(len(payload), 65536) self.add(payload, [payload[:65536], payload[65536:]]) self.finish() p, data = self.run_tool() self.assertEqual(p.returncode, 0, p.stdout + p.stderr) mhiu = data["payloads"][0] self.assertEqual(mhiu["chunks"], 2) self.assertEqual(mhiu["grid"]["width"], 300) self.assertEqual(mhiu["grid"]["height"], 1) def test_groups_a_continuation_after_a_128k_first_stream(self): # The header's size bounds the join, so a first stream of any whole number of 64 KiB blocks continues. payload = mhiu_payload(300, 1, [(0, 300, [i % 256 for i in range(300)])], pixels=b"\x07" * 150000) self.assertGreater(len(payload), 2 * 65536) self.add(payload, [payload[:2 * 65536], payload[2 * 65536:]]) self.finish() p, data = self.run_tool() self.assertEqual(p.returncode, 0, p.stdout + p.stderr) mhiu = data["payloads"][0] self.assertEqual(mhiu["chunks"], 2) self.assertEqual(mhiu["grid"]["width"], 300) def test_reports_an_unwritable_json_destination(self): self.finish() blocker = os.path.join(self.root, "blocker") with open(blocker, "wb") as f: f.write(b"not a directory") out = os.path.join(blocker, "maps.json") result = subprocess.run( [sys.executable, "-I", TOOL, self.carve, "--json", out], capture_output=True, text=True, errors="replace", ) self.assertEqual(result.returncode, 1) self.assertIn(f"cannot write {out}", result.stderr) self.assertNotIn("Traceback", result.stderr) self.assertNotIn("wrote", result.stdout) def test_creates_missing_parent_directories_for_json_with_lf_endings(self): self.add(pamh_payload(3, 2, [1, 2, 3, 4, 5, 6], [0, 1, 2, 3, 4, 5])) self.finish() out = os.path.join(self.root, "missing", "nested", "maps.json") result = subprocess.run( [sys.executable, "-I", TOOL, self.carve, "--json", out], cwd=self.root, capture_output=True, text=True, encoding="utf-8", errors="replace", ) self.assertEqual(result.returncode, 0, result.stdout + result.stderr) self.assertTrue(os.path.isfile(out)) with open(out, "rb") as f: raw = f.read() self.assertIn(b"\n", raw) self.assertNotIn(b"\r\n", raw) data = json.loads(raw.decode("utf-8")) self.assertEqual(len(data["payloads"]), 1) self.assertEqual(data["payloads"][0]["type"], "PAMH") def test_refuses_json_colliding_with_index_json_and_case_variants(self): self.add(pamh_payload(2, 2, [1, 2, 3, 4], [0, 1, 2, 3])) self.finish() index_path = os.path.join(self.carve, "index.json") with open(index_path, "rb") as f: original = f.read() targets = [index_path, os.path.join(self.carve, ".", "index.json")] cased_index = os.path.join(self.carve, "INDEX.JSON") if os.path.exists(cased_index): targets.append(cased_index) targets.append(os.path.join(self.root, "CARVE", "INDEX.JSON")) for out in targets: with self.subTest(out=out): result = subprocess.run( [sys.executable, "-I", TOOL, self.carve, "--json", out], cwd=self.root, capture_output=True, text=True, encoding="utf-8", errors="replace", ) self.assertEqual(result.returncode, 1, result.stdout + result.stderr) self.assertIn("error:", result.stderr) self.assertIn("would overwrite", result.stderr) self.assertNotIn("Traceback", result.stderr) self.assertNotIn("wrote", result.stdout) with open(index_path, "rb") as f: self.assertEqual(f.read(), original) def test_refuses_json_colliding_with_carved_bin_file(self): self.add(pamh_payload(2, 2, [1, 2, 3, 4], [0, 1, 2, 3])) self.finish() carved = os.path.join(self.carve, "000000001000.bin") with open(carved, "rb") as f: original = f.read() targets = [carved] cased_bin = os.path.join(self.carve, "000000001000.BIN") if os.path.exists(cased_bin): targets.append(cased_bin) hardlink = os.path.join(self.root, "hardlink.json") try: os.link(carved, hardlink) except (OSError, NotImplementedError): hardlink = None if hardlink is not None: targets.append(hardlink) symlink = os.path.join(self.root, "symlink.json") try: os.symlink(carved, symlink) except (OSError, NotImplementedError): symlink = None if symlink is not None: targets.append(symlink) for out in targets: with self.subTest(out=out): result = subprocess.run( [sys.executable, "-I", TOOL, self.carve, "--json", out], cwd=self.root, capture_output=True, text=True, encoding="utf-8", errors="replace", ) self.assertEqual(result.returncode, 1, result.stdout + result.stderr) self.assertIn("error:", result.stderr) self.assertIn("would overwrite", result.stderr) self.assertNotIn("Traceback", result.stderr) self.assertNotIn("wrote", result.stdout) with open(carved, "rb") as f: self.assertEqual(f.read(), original) def test_refuses_json_colliding_with_index_only_carved_stream(self): self.add(pamh_payload(2, 2, [1, 2, 3, 4], [0, 1, 2, 3])) self.finish() carved = os.path.join(self.carve, "000000001000.bin") os.remove(carved) result = subprocess.run( [sys.executable, "-I", TOOL, self.carve, "--json", carved], cwd=self.root, capture_output=True, text=True, encoding="utf-8", errors="replace", ) self.assertEqual(result.returncode, 1, result.stdout + result.stderr) self.assertIn("error:", result.stderr) self.assertIn("would overwrite", result.stderr) self.assertFalse(os.path.exists(carved)) def test_refuses_json_pointing_to_existing_directory_or_carve_dir(self): self.finish() existing_dir = os.path.join(self.root, "reports_dir") os.makedirs(existing_dir) for out, expected in ((existing_dir, "directory"), (self.carve, "would overwrite")): with self.subTest(out=out): result = subprocess.run( [sys.executable, "-I", TOOL, self.carve, "--json", out], cwd=self.root, capture_output=True, text=True, encoding="utf-8", errors="replace", ) self.assertEqual(result.returncode, 1, result.stdout + result.stderr) self.assertIn("error:", result.stderr) self.assertIn(expected, result.stderr) self.assertNotIn("Traceback", result.stderr) self.assertNotIn("wrote", result.stdout) def test_validates_json_before_scanning_carve_dir(self): # Leave index.json corrupt so a scan would fail with a JSON error instead of the path guard. carved = os.path.join(self.carve, "000000001000.bin") with open(carved, "wb") as f: f.write(b"raw carved stream") index_path = os.path.join(self.carve, "index.json") with open(index_path, "wb") as f: f.write(b"{corrupt json") out_dir = os.path.join(self.root, "existing_dir") os.makedirs(out_dir) for out, expected in ((out_dir, "directory"), (index_path, "would overwrite"), (carved, "would overwrite")): with self.subTest(out=out): result = subprocess.run( [sys.executable, "-I", TOOL, self.carve, "--json", out], cwd=self.root, capture_output=True, text=True, encoding="utf-8", errors="replace", ) self.assertEqual(result.returncode, 1, result.stdout + result.stderr) self.assertIn(expected, result.stderr) self.assertEqual(result.stdout, "") def test_allows_non_input_json_report_inside_carve_dir(self): self.add(pamh_payload(2, 2, [1, 2, 3, 4], [0, 1, 2, 3])) self.finish() out = os.path.join(self.carve, "maps.json") for _ in range(2): result = subprocess.run( [sys.executable, "-I", TOOL, self.carve, "--json", out], cwd=self.root, capture_output=True, text=True, encoding="utf-8", errors="replace", ) self.assertEqual(result.returncode, 0, result.stdout + result.stderr) with open(out, encoding="utf-8") as f: data = json.load(f) self.assertEqual(len(data["payloads"]), 1) def test_macos_case_insensitive_volume_folds_case_and_nfd(self): with mock.patch.object(gamedata_maps.os, "name", "posix"), \ mock.patch.object(gamedata_maps.sys, "platform", "darwin"), \ mock.patch.object(gamedata_maps.os, "pathconf", return_value=0, create=True): self.assertTrue(gamedata_maps.same_report_path( os.path.join(self.carve, "INDEX.JSON"), os.path.join(self.carve, "index.json"), )) self.assertTrue(gamedata_maps.same_report_path( os.path.join(self.carve, "caf\u00e9.json"), os.path.join(self.carve, "CAFE\u0301.json"), )) def test_complete_64k_map_leaves_the_next_stream_alone(self): payload = mhiu_payload(255, 1, [(0, 255, [7] * 255)], pixels=b"\x00" * 65229) self.assertEqual(len(payload), 65536) self.add(payload) self.add(b"unrelated resource") self.finish() p, data = self.run_tool() self.assertEqual(p.returncode, 0, p.stderr) row, = data["payloads"] self.assertEqual((row["size"], row["chunks"]), (65536, 1)) self.assertEqual(row["grid"]["width"], 255) class MalformedCarveIndex(unittest.TestCase): """A carve index that parses but has no usable files list names the index, not a bare KeyError.""" def run_tool(self, index): with tempfile.TemporaryDirectory() as root: with open(os.path.join(root, "index.json"), "w", encoding="utf-8") as f: json.dump(index, f) result = subprocess.run([sys.executable, "-I", TOOL, root], capture_output=True, text=True, errors="replace") return result def test_empty_index_names_the_file_and_the_missing_key(self): result = self.run_tool({}) self.assertEqual(result.returncode, 1) self.assertIn("index.json has no 'files' list", result.stderr) self.assertNotIn("error: 'files'", result.stderr) self.assertNotIn("Traceback", result.stderr) def test_row_without_an_offset_is_named(self): result = self.run_tool({"files": [{"stored": 12}]}) self.assertEqual(result.returncode, 1) self.assertIn("row 0 needs an 'off'", result.stderr) self.assertNotIn("Traceback", result.stderr) def test_utf8_bom_index_json_loads_cleanly(self): with tempfile.TemporaryDirectory() as root: payload = pamh_payload(2, 2, [5, 6, 7, 8], [1, 2, 3, 4]) with open(os.path.join(root, "000000001000.bin"), "wb") as f: f.write(payload) idx_bytes = json.dumps({ "files": [{"off": 0x1000, "stored": len(payload), "size": len(payload), "head": payload[:16].hex()}] }).encode("utf-8") with open(os.path.join(root, "index.json"), "wb") as f: f.write(b"\xef\xbb\xbf" + idx_bytes) out_json = os.path.join(root, "report.json") result = subprocess.run( [sys.executable, "-I", TOOL, root, "--json", out_json], capture_output=True, text=True, errors="replace", ) self.assertEqual(result.returncode, 0, result.stderr) with open(out_json, "rb") as f: raw = f.read() self.assertTrue(raw.endswith(b"\n")) self.assertEqual(len(json.loads(raw.decode("utf-8"))["payloads"]), 1) def test_index_rejects_bad_off_and_row_field_types(self): for bad_off in (True, -1, "0x1000", None): with self.subTest(bad_off=bad_off): result = self.run_tool({"files": [{"off": bad_off, "stored": 12}]}) self.assertEqual(result.returncode, 1) self.assertIn("must be a non-negative integer", result.stderr) self.assertNotIn("Traceback", result.stderr) with tempfile.TemporaryDirectory() as root: with self.assertRaisesRegex(ValueError, "'head' must be a hex string"): gamedata_maps._read_row(root, {"off": 0x1000, "head": 12345}) self.assertEqual(gamedata_maps._read_row(root, {"off": 0x1000, "head": None}), b"") payload = pamh_payload(2, 2, [5, 6, 7, 8], [1, 2, 3, 4]) with open(os.path.join(root, "000000001000.bin"), "wb") as f: f.write(payload) rows_null = [{"off": 0x1000, "stored": None, "size": None, "head": payload[:16].hex()}] parsed = gamedata_maps.read_payloads(root, rows=rows_null) self.assertEqual(len(parsed), 1) self.assertEqual(parsed[0]["stored"], 0) with self.assertRaisesRegex(ValueError, "non-negative integer"): gamedata_maps.read_payloads(root, rows=[{"off": 0x1000, "stored": True, "size": len(payload)}]) def test_atomic_json_write_rejects_nan_and_preserves_existing_file(self): with tempfile.TemporaryDirectory() as root: out_path = os.path.join(root, "maps.json") sentinel = '{"keep": true}\n' with open(out_path, "w", encoding="utf-8", newline="\n") as f: f.write(sentinel) with self.assertRaises(ValueError): gamedata_maps._write_json(out_path, {"bad": float("nan")}) with open(out_path, encoding="utf-8") as f: self.assertEqual(f.read(), sentinel) self.assertEqual(os.listdir(root), ["maps.json"]) if __name__ == "__main__": unittest.main()