diff options
Diffstat (limited to 'tests/test_imhex_patterns.py')
| -rw-r--r-- | tests/test_imhex_patterns.py | 170 |
1 files changed, 170 insertions, 0 deletions
diff --git a/tests/test_imhex_patterns.py b/tests/test_imhex_patterns.py new file mode 100644 index 000000000..9e0cc1cca --- /dev/null +++ b/tests/test_imhex_patterns.py | |||
| @@ -0,0 +1,170 @@ | |||
| 1 | """Tests for the ImHex patterns in tools/imhex. | ||
| 2 | |||
| 3 | python -I tests/test_imhex_patterns.py | ||
| 4 | |||
| 5 | Every byte here is built by the test: no game file, name or path is used. The RBF0 inputs are first checked with | ||
| 6 | tools/rbf0_index.py, the repository's own parser. When ImHex is installed, each pattern then runs on the same bytes | ||
| 7 | through ImHex's pattern-language CLI (`imhex --pl format ... -f json`) and the decoded fields are compared with the | ||
| 8 | parser's result. ImHex is found through LEONIDA_IMHEX, then PATH, then its default Windows install folder; without it | ||
| 9 | the ImHex half is skipped and the rest still runs. | ||
| 10 | """ | ||
| 11 | import json | ||
| 12 | import os | ||
| 13 | import shutil | ||
| 14 | import struct | ||
| 15 | import subprocess | ||
| 16 | import sys | ||
| 17 | import tempfile | ||
| 18 | import unittest | ||
| 19 | |||
| 20 | ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | ||
| 21 | PATTERNS = os.path.join(ROOT, "tools", "imhex") | ||
| 22 | sys.path.insert(0, os.path.join(ROOT, "tools")) | ||
| 23 | |||
| 24 | import rbf0_index # noqa: E402 | ||
| 25 | |||
| 26 | |||
| 27 | def find_imhex(): | ||
| 28 | candidates = [os.environ.get("LEONIDA_IMHEX"), shutil.which("imhex")] | ||
| 29 | if os.name == "nt": | ||
| 30 | candidates.append(os.path.join(os.environ.get("ProgramFiles", r"C:\Program Files"), "ImHex", "imhex.exe")) | ||
| 31 | for c in candidates: | ||
| 32 | if c and os.path.isfile(c): | ||
| 33 | return c | ||
| 34 | return None | ||
| 35 | |||
| 36 | |||
| 37 | IMHEX = find_imhex() | ||
| 38 | |||
| 39 | |||
| 40 | # ---- synthetic inputs ------------------------------------------------------------------------------------------ | ||
| 41 | |||
| 42 | def _name(name): | ||
| 43 | return struct.pack("<H", len(name)) + name | ||
| 44 | |||
| 45 | |||
| 46 | def rbf0_stream(wide): | ||
| 47 | """One resource with every record type of docs/rbf0.md section 3, then bytes past the root close.""" | ||
| 48 | q, d = ("Q", "d") if wide else ("I", "f") | ||
| 49 | q, d, d3 = "<" + q, "<" + d, "<" + d * 3 | ||
| 50 | out = b"RBF0" + (rbf0_index.PROLOGUE if wide else b"") | ||
| 51 | out += bytes([0, 0x00]) + _name(b"root") + struct.pack("<HHH", 0, 0, 1) | ||
| 52 | out += bytes([1, 0x10]) + _name(b"count") + struct.pack(q, 7) # the root's one attribute | ||
| 53 | out += bytes([2, 0x00]) + _name(b"item") + struct.pack("<HHH", 0, 0, 0) | ||
| 54 | out += bytes([3, 0x40]) + _name(b"scale") + struct.pack(d, 1.5) | ||
| 55 | out += bytes([4, 0x50]) + _name(b"pos") + struct.pack(d3, 1.0, -2.0, 0.25) | ||
| 56 | out += bytes([5, 0x60]) + _name(b"label") + struct.pack("<H", 5) + b"probe" | ||
| 57 | out += bytes([6, 0x20]) + _name(b"flag") + bytes([6, 0x30]) # new, then reused | ||
| 58 | out += bytes([3, 0x10]) + struct.pack(q, 9) # reused with another type | ||
| 59 | out += bytes([0xFD, 0xFF]) + struct.pack("<I", 5) + b"text\x00" | ||
| 60 | out += b"\xff\xff" # close item | ||
| 61 | out += b"\xff\xff" # close root: the end | ||
| 62 | return out + b"\x00\x11\x22\x33" # not part of the resource | ||
| 63 | |||
| 64 | |||
| 65 | def rpf9_archive(data_offset=0x100, size=0x140): | ||
| 66 | head = b"9FPR" + struct.pack("<III", data_offset, 0x11, 0x22) | ||
| 67 | toc = bytes((i * 37) & 0xFF for i in range(data_offset - len(head))) | ||
| 68 | body = b"\x78\x9c" + bytes(size - data_offset - 2) | ||
| 69 | return head + toc + body | ||
| 70 | |||
| 71 | |||
| 72 | def pragma_magic(pattern): | ||
| 73 | """The bytes of `#pragma magic [ .. ] @ 0x00` in a pattern file.""" | ||
| 74 | with open(os.path.join(PATTERNS, pattern), encoding="utf-8") as f: | ||
| 75 | for line in f: | ||
| 76 | if line.startswith("#pragma magic"): | ||
| 77 | inside = line[line.index("[") + 1:line.index("]")] | ||
| 78 | return bytes(int(b, 16) for b in inside.split()) | ||
| 79 | return None | ||
| 80 | |||
| 81 | |||
| 82 | # ---- tests ----------------------------------------------------------------------------------------------------- | ||
| 83 | |||
| 84 | class InputsAndMagic(unittest.TestCase): | ||
| 85 | """Runs everywhere: the synthetic inputs are valid RBF0 by the repository's parser, and the magics agree.""" | ||
| 86 | |||
| 87 | def test_synthetic_streams_parse(self): | ||
| 88 | for wide in (True, False): | ||
| 89 | r = rbf0_index.parse_rbf0(rbf0_stream(wide)[:-4]) | ||
| 90 | self.assertEqual(r["status"], "ok", r["error"]) | ||
| 91 | self.assertEqual(r["layout"], "wide-64" if wide else "narrow-32") | ||
| 92 | self.assertEqual(r["elements"], 2) | ||
| 93 | self.assertEqual(r["descriptors"], 7) | ||
| 94 | |||
| 95 | def test_pattern_magics(self): | ||
| 96 | self.assertEqual(pragma_magic("rbf0.hexpat"), rbf0_index.MAGIC) | ||
| 97 | self.assertEqual(pragma_magic("rpf9.hexpat"), b"9FPR") # RPF9 stored little-endian (docs/rpf.md) | ||
| 98 | |||
| 99 | |||
| 100 | @unittest.skipUnless(IMHEX, "ImHex is not installed (set LEONIDA_IMHEX to imhex.exe)") | ||
| 101 | class PatternsInImHex(unittest.TestCase): | ||
| 102 | def setUp(self): | ||
| 103 | self.tmp = tempfile.TemporaryDirectory() | ||
| 104 | self.addCleanup(self.tmp.cleanup) | ||
| 105 | |||
| 106 | def run_pattern(self, pattern, data): | ||
| 107 | """Returns (decoded JSON or None, combined output).""" | ||
| 108 | src = os.path.join(self.tmp.name, "input.bin") | ||
| 109 | out = os.path.join(self.tmp.name, "out.json") | ||
| 110 | if os.path.exists(out): | ||
| 111 | os.remove(out) | ||
| 112 | with open(src, "wb") as f: | ||
| 113 | f.write(data) | ||
| 114 | cmd = [IMHEX, "--pl", "format", "-i", src, "-p", os.path.join(PATTERNS, pattern), "-o", out, "-f", "json"] | ||
| 115 | includes = os.path.join(os.path.dirname(IMHEX), "includes") | ||
| 116 | if os.path.isdir(includes): | ||
| 117 | cmd += ["-I", includes] | ||
| 118 | p = subprocess.run(cmd, capture_output=True, text=True, timeout=120) | ||
| 119 | log = p.stdout + p.stderr | ||
| 120 | if not os.path.exists(out): | ||
| 121 | return None, log | ||
| 122 | with open(out, encoding="utf-8") as f: | ||
| 123 | return json.load(f), log | ||
| 124 | |||
| 125 | def check_rbf0(self, wide): | ||
| 126 | data = rbf0_stream(wide) | ||
| 127 | ref = rbf0_index.parse_rbf0(data[:-4]) | ||
| 128 | got, log = self.run_pattern("rbf0.hexpat", data) | ||
| 129 | self.assertIsNotNone(got, log) | ||
| 130 | self.assertEqual("prologue" in got["header"], wide) | ||
| 131 | records = got["records"] | ||
| 132 | |||
| 133 | names = [r["name"] for r in records if "name" in r] | ||
| 134 | self.assertEqual(names, ref["descriptor_names"]) | ||
| 135 | self.assertEqual(sum(1 for r in records if r["index"] < 0xFD and r["type"] == 0x00), ref["elements"]) | ||
| 136 | ints = [r["value_int"] for r in records if "value_int" in r] | ||
| 137 | self.assertEqual(ints, ref["ints"]) | ||
| 138 | floats = [] | ||
| 139 | for r in records: | ||
| 140 | floats += [r["value_float"]] if "value_float" in r else r.get("value_vec3", []) | ||
| 141 | self.assertEqual(floats, ref["floats"]) | ||
| 142 | strings = [r.get("value_string", r.get("text", "")) for r in records if "value_string" in r or "text" in r] | ||
| 143 | self.assertEqual([s.split("%00")[0] for s in strings], ref["strings"]) | ||
| 144 | self.assertEqual([r["attribute_count"] for r in records if "attribute_count" in r], [1, 0]) | ||
| 145 | # The pattern stops where the root closes, as parse_rbf0 does: the 4 trailing bytes are not records. | ||
| 146 | self.assertEqual(records[-1]["index"], 0xFF) | ||
| 147 | self.assertEqual(sum(1 for r in records if r["index"] == 0xFF), 2) | ||
| 148 | |||
| 149 | def test_rbf0_wide(self): | ||
| 150 | self.check_rbf0(wide=True) | ||
| 151 | |||
| 152 | def test_rbf0_narrow(self): | ||
| 153 | self.check_rbf0(wide=False) | ||
| 154 | |||
| 155 | def test_rpf9_header_and_opaque_toc(self): | ||
| 156 | got, log = self.run_pattern("rpf9.hexpat", rpf9_archive(data_offset=0x100)) | ||
| 157 | self.assertIsNotNone(got, log) | ||
| 158 | self.assertEqual(got["header"]["magic"], "9FPR") | ||
| 159 | self.assertEqual(got["header"]["data_offset"], 0x100) | ||
| 160 | self.assertEqual((got["header"]["u32_08"], got["header"]["u32_0c"]), (0x11, 0x22)) | ||
| 161 | self.assertEqual(len(got["header_rest_and_toc"]), 0x100 - 0x10) | ||
| 162 | |||
| 163 | def test_rpf9_rejects_a_data_offset_past_the_end(self): | ||
| 164 | got, log = self.run_pattern("rpf9.hexpat", rpf9_archive(data_offset=0x100, size=0x140)[:0x20]) | ||
| 165 | self.assertIsNone(got) | ||
| 166 | self.assertIn("data offset is outside the file", log) | ||
| 167 | |||
| 168 | |||
| 169 | if __name__ == "__main__": | ||
| 170 | unittest.main() | ||