"""Tests for tools/text_tables.py, built from synthetic resources and conversation data (no game data). python -I tests/test_text_tables.py """ import contextlib import csv import errno import importlib.util import io import json import os import struct import tempfile import unittest from unittest import mock from unittest.mock import patch ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) def load_module(): path = os.path.join(ROOT, "tools", "text_tables.py") spec = importlib.util.spec_from_file_location("text_tables_under_test", path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module T = load_module() def ptr(off): return struct.pack(" text. ``pad`` adds bytes before the tables so they can cross a 64 KiB boundary. """ labels = list(strings) blob = bytearray() blob_offsets = [] for label in labels: blob_offsets.append(len(blob)) blob += strings[label].encode("utf-8") + b"\0" head = bytearray(0x10) + b"0DRP" + bytes(0x0C) desc_at = len(head) desc_len = 8 + 4 + 4 + 8 + 4 + 4 + 8 + 4 + 4 + 8 index_at = desc_at + desc_len + pad hash_at = index_at + 16 * len(labels) blob_at = hash_at + 16 * len(labels) desc = (ptr(index_at) + struct.pack(".bin per inflated stream.""" files, off = [], 0x1000 for data in streams: write(os.path.join(tmp, f"{off:012x}.bin"), data) files.append({"off": off, "stored": len(data), "size": len(data), "pre": "", "head": data[:16].hex()}) off += 0x20000 with open(os.path.join(tmp, "index.json"), "w", encoding="utf-8") as fh: json.dump({"files": files, "summary": {}}, fh) def test_resource_across_64k_streams(self): res = make_resource(EN, pad=T.BLOCK) # tables start past the first 64 KiB streams = [res[:T.BLOCK], res[T.BLOCK:], make_resource(DE), CONV] with tempfile.TemporaryDirectory() as tmp: self.carve(tmp, streams) scan = T.Scan() for label, off, data in T.blobs(tmp): scan.add(label, off, data) self.assertEqual(sorted(lang for _s, _o, lang, _t in scan.tables), ["de", "en"]) self.assertEqual(scan.tables[0][1], 0x1000) def test_resource_across_a_128k_first_stream(self): # A resource's first stream can be any whole number of 64 KiB blocks (docs/page_directory.md): 41 data.rpf # resources start with a 128 or 192 KiB stream whose descriptors end in the next stream. res = make_resource(EN, pad=2 * T.BLOCK) # tables start past the first 128 KiB streams = [res[:2 * T.BLOCK], res[2 * T.BLOCK:], make_resource(DE), CONV] with tempfile.TemporaryDirectory() as tmp: self.carve(tmp, streams) scan = T.Scan() for label, off, data in T.blobs(tmp): scan.add(label, off, data) self.assertEqual(sorted(lang for _s, _o, lang, _t in scan.tables), ["de", "en"]) def test_whole_block_streams_continue_and_others_end_the_chain(self): for first, joined in ((T.BLOCK, True), (2 * T.BLOCK, True), (3 * T.BLOCK, True), (T.BLOCK + 16, False), (T.BLOCK - 16, False)): with self.subTest(first=first): rows = [{"off": 0, "size": first}, {"off": 1, "size": 100}] data = {0: bytes(first), 1: b"b" * 100} offsets = [o for o, _d in T._chains(rows, lambda r: data[r["off"]])] self.assertEqual(offsets, [0] if joined else [0, 1]) def test_short_stream_ends_the_chain(self): rows = [{"off": 0, "size": 100}, {"off": 1, "size": 50}] data = {0: b"a" * 100, 1: b"b" * 50} self.assertEqual([o for o, _d in T._chains(rows, lambda r: data[r["off"]])], [0, 1]) def test_new_resource_ends_the_chain(self): rows = [{"off": 0, "size": T.BLOCK}, {"off": 1, "size": 10}] data = {0: bytes(T.BLOCK), 1: bytes(0x10) + b"0DRP"} self.assertEqual([o for o, _d in T._chains(rows, lambda r: data[r["off"]])], [0, 1]) class TestDialogue(unittest.TestCase): def test_waves_and_text(self): scan = T.Scan() scan.add("a", 0, make_resource(EN)) scan.add("b", 0, make_resource(DE)) scan.add("c", 0, CONV) rows = list(scan.dialogue_rows()) self.assertEqual([(r["wave"], r["label"], r["speaker"]) for r in rows], [("zz_rootau_abcd_01", "ZZ_LINE_A_1", "A"), ("zz_rootau_abcd_02", "ZZ_LINE_B_2", "B")]) self.assertEqual(rows[0]["text_en"], EN["ZZ_LINE_A_1"]) self.assertEqual(rows[1]["text_de"], DE["ZZ_LINE_B_2"]) self.assertEqual(scan.languages(), ["en", "de"]) def test_lowercase_in_label(self): scan = T.Scan() scan.add("c", 0, b"ZZ_KEYAU_ABCD\x00ZZ_TIMELEFT_90s_1\x00") self.assertEqual(scan.pairs["ZZ_KEYAU_ABCD"], ["ZZ_TIMELEFT_90s_1"]) def test_subfolders_are_read_in_name_order(self): # os.walk lists subfolders in the file system's own order (by name on NTFS, by hash on ext4), and the # dialogue table keeps the last text read for a label, so one folder of resources gave one text on Windows # and another on Linux. A walk that lists subfolders backwards stands in for the other file system. real_walk = os.walk def backwards(top, *args, **kwargs): for root, dirs, files in real_walk(top, *args, **kwargs): dirs.reverse() yield root, dirs, files first = dict(EN, ZZ_LINE_A_1="This is the first table and you know it") second = dict(EN, ZZ_LINE_A_1="This is the second table and you know it") with tempfile.TemporaryDirectory() as tmp: for sub, strings in (("a", first), ("b", second)): os.makedirs(os.path.join(tmp, sub)) write(os.path.join(tmp, sub, "res.bin"), make_resource(strings)) for walk in (real_walk, backwards): with self.subTest(walk=walk.__name__), patch.object(T.os, "walk", walk): scan = T.Scan() read = [] for label, off, data in T.blobs(tmp): read.append(os.path.relpath(label, tmp)) scan.add(label, off, data) scan.add("c", 0, CONV) self.assertEqual(read, [os.path.join("a", "res.bin"), os.path.join("b", "res.bin")]) self.assertEqual(next(scan.dialogue_rows())["text_en"], second["ZZ_LINE_A_1"]) class TestCli(unittest.TestCase): def test_unreadable_subdirectory_preserves_previous_tables_report(self): with tempfile.TemporaryDirectory() as tmp: source = os.path.join(tmp, "source") blocked = os.path.join(source, "blocked") os.makedirs(blocked) write(os.path.join(source, "visible.bin"), make_resource(EN)) write(os.path.join(blocked, "hidden.bin"), make_resource(DE)) report = os.path.join(tmp, "tables.csv") previous = b"previous complete report\n" write(report, previous) scandir = os.scandir def scan(path): if path == blocked: raise PermissionError(errno.EACCES, "Permission denied", path) return scandir(path) with (patch.object(os, "scandir", side_effect=scan), contextlib.redirect_stderr(io.StringIO()) as error, contextlib.redirect_stdout(io.StringIO()) as output): self.assertEqual(T.main([source, "--tables", report]), 2) self.assertEqual(output.getvalue(), "") self.assertEqual(len(error.getvalue().splitlines()), 1) self.assertIn("cannot read input", error.getvalue()) self.assertIn(repr(blocked), error.getvalue()) with open(report, "rb") as fh: self.assertEqual(fh.read(), previous) def test_csv_exports_explicitly_empty_strings(self) -> None: strings = {"ZZ_SYNTHETIC_BLANK": "", "ZZ_SYNTHETIC_LINE": "This is the text you know"} with tempfile.TemporaryDirectory() as tmp: source = write(os.path.join(tmp, "strings.bin"), make_resource(strings)) tables_csv = os.path.join(tmp, "tables.csv") strings_csv = os.path.join(tmp, "strings.csv") with contextlib.redirect_stdout(io.StringIO()): self.assertEqual(T.main([source, "--tables", tables_csv, "--strings", strings_csv]), 0) with open(tables_csv, encoding="utf-8", newline="") as f: self.assertEqual([row["strings"] for row in csv.DictReader(f)], ["2"]) with open(strings_csv, encoding="utf-8", newline="") as f: self.assertEqual({row["hash"]: row["text"] for row in csv.DictReader(f)}, {f"{T.joaat(label):08x}": text for label, text in strings.items()}) def test_end_to_end(self): with tempfile.TemporaryDirectory() as tmp: src = os.path.join(tmp, "src") os.mkdir(src) write(os.path.join(src, "en.bin"), make_resource(EN)) write(os.path.join(src, "de.bin"), make_resource(DE)) write(os.path.join(src, "conv.pso"), CONV) labels = os.path.join(tmp, "labels.json") with open(labels, "w", encoding="utf-8") as fh: json.dump({f"{T.joaat('zz_menu_title'):08x}": "zz_menu_title"}, fh) outs = {k: os.path.join(tmp, f"{k}.csv") for k in ("dialogue", "tables", "strings")} with contextlib.redirect_stdout(io.StringIO()) as log: self.assertEqual(T.main([src, "--labels", labels, "--dialogue", outs["dialogue"], "--tables", outs["tables"], "--strings", outs["strings"]]), 0) self.assertIn("2 string tables", log.getvalue()) self.assertIn("1 dialogue keys, 2 lines", log.getvalue()) with open(outs["tables"], encoding="utf-8", newline="") as fh: tables = list(csv.DictReader(fh)) self.assertEqual({(t["lang"], t["strings"], t["resolved"], t["group"]) for t in tables}, {("en", "3", "3", "ZZ_LINE"), ("de", "3", "3", "ZZ_LINE")}) # 2 of 3 share ZZ_LINE with open(outs["strings"], encoding="utf-8", newline="") as fh: strings = list(csv.DictReader(fh)) self.assertIn(("ZZ_MENU_TITLE", "das Menü"), {(s["label"], s["text"]) for s in strings}) self.assertFalse([f for f in os.listdir(tmp) if f.startswith(".text_tables-")], "staging files must not be left behind") def test_failed_later_write_leaves_earlier_reports_intact(self): with tempfile.TemporaryDirectory() as tmp: src = os.path.join(tmp, "src") os.mkdir(src) write(os.path.join(src, "conv.pso"), CONV) dialogue = os.path.join(tmp, "dialogue.csv") old = "OLD GOOD REPORT\n" with open(dialogue, "w", encoding="utf-8") as fh: fh.write(old) tables = os.path.join(tmp, "tables.csv") os.mkdir(tables) # a later output that cannot be written with contextlib.redirect_stderr(io.StringIO()) as err: self.assertEqual(T.main([src, "--dialogue", dialogue, "--tables", tables]), 2) self.assertIn("cannot write", err.getvalue()) with open(dialogue, encoding="utf-8") as fh: self.assertEqual(fh.read(), old) self.assertFalse([f for f in os.listdir(tmp) if f.startswith(".text_tables-")]) @unittest.skipUnless(os.name == "nt", "Windows denies os.replace on a file held open by a reader") def test_reader_holding_a_later_report_keeps_all_reports(self): with tempfile.TemporaryDirectory() as tmp: src = os.path.join(tmp, "src") os.mkdir(src) write(os.path.join(src, "conv.pso"), CONV) dialogue = os.path.join(tmp, "dialogue.csv") tables = os.path.join(tmp, "tables.csv") old_dialogue, old_tables = "OLD DIALOGUE\n", "OLD TABLES\n" for path, text in ((dialogue, old_dialogue), (tables, old_tables)): with open(path, "w", encoding="utf-8") as fh: fh.write(text) with open(tables, "rb"): # a reader keeps the second output open with contextlib.redirect_stderr(io.StringIO()) as err: self.assertEqual(T.main([src, "--dialogue", dialogue, "--tables", tables]), 2) self.assertIn("cannot write", err.getvalue()) with open(dialogue, encoding="utf-8") as fh: self.assertEqual(fh.read(), old_dialogue) with open(tables, encoding="utf-8") as fh: self.assertEqual(fh.read(), old_tables) self.assertFalse([f for f in os.listdir(tmp) if f.startswith(".text_tables-")], "staging and backup files must not be left behind") def test_failed_later_write_with_readonly_destination_cleans_up_staged_files(self): with tempfile.TemporaryDirectory() as tmp: src = os.path.join(tmp, "src") os.mkdir(src) write(os.path.join(src, "conv.pso"), CONV) dialogue = os.path.join(tmp, "dialogue.csv") old = "OLD GOOD REPORT\n" with open(dialogue, "w", encoding="utf-8") as fh: fh.write(old) os.chmod(dialogue, 0o444) tables = os.path.join(tmp, "tables.csv") os.mkdir(tables) # a later output that cannot be written with contextlib.redirect_stderr(io.StringIO()) as err: self.assertEqual(T.main([src, "--dialogue", dialogue, "--tables", tables]), 2) self.assertIn("cannot write", err.getvalue()) with open(dialogue, encoding="utf-8") as fh: self.assertEqual(fh.read(), old) self.assertFalse([f for f in os.listdir(tmp) if f.startswith(".text_tables-")]) def test_successful_write_with_readonly_destination_cleans_up_backup_files(self): with tempfile.TemporaryDirectory() as tmp: src = os.path.join(tmp, "src") os.mkdir(src) write(os.path.join(src, "conv.pso"), CONV) dialogue = os.path.join(tmp, "dialogue.csv") with open(dialogue, "w", encoding="utf-8") as fh: fh.write("OLD\n") os.chmod(dialogue, 0o444) self.assertEqual(T.main([src, "--dialogue", dialogue]), 0) self.assertFalse([f for f in os.listdir(tmp) if f.startswith(".text_tables-")]) def test_windows_readonly_file_removal_restores_write_mode(self): with tempfile.TemporaryDirectory() as tmp: src = os.path.join(tmp, "src") os.mkdir(src) write(os.path.join(src, "conv.pso"), CONV) dialogue = os.path.join(tmp, "dialogue.csv") with open(dialogue, "w", encoding="utf-8") as fh: fh.write("OLD\n") os.chmod(dialogue, 0o444) tables = os.path.join(tmp, "tables.csv") os.mkdir(tables) real_remove = os.remove def windows_strict_remove(path): mode = os.stat(path).st_mode if not (mode & 0o200): raise PermissionError(13, f"Access is denied: {path}") return real_remove(path) with mock.patch("os.remove", side_effect=windows_strict_remove): with contextlib.redirect_stderr(io.StringIO()) as err: self.assertEqual(T.main([src, "--dialogue", dialogue, "--tables", tables]), 2) self.assertIn("cannot write", err.getvalue()) self.assertFalse([f for f in os.listdir(tmp) if f.startswith(".text_tables-")]) def test_report_cannot_replace_the_carve_index(self): with tempfile.TemporaryDirectory() as tmp: source = os.path.join(tmp, "carve") os.mkdir(source) index = write(os.path.join(source, "index.json"), b'{"files": []}') with contextlib.redirect_stderr(io.StringIO()) as err, self.assertRaises(SystemExit) as code: T.main([source, "--tables", index]) self.assertEqual(code.exception.code, 2) self.assertIn("must not overwrite an input", err.getvalue()) with open(index, "rb") as f: self.assertEqual(f.read(), b'{"files": []}') def test_report_cannot_replace_a_file_read_from_a_source_directory(self): with tempfile.TemporaryDirectory() as tmp: src = os.path.join(tmp, "src") os.makedirs(os.path.join(src, "sub")) resource = write(os.path.join(src, "a.bin"), make_resource(EN)) nested = write(os.path.join(src, "sub", "notes.txt"), b"keep") for flag, target, old in (("--tables", nested, b"keep"), ("--strings", resource, make_resource(EN))): with contextlib.redirect_stderr(io.StringIO()) as err, self.assertRaises(SystemExit) as code: T.main([src, flag, target]) self.assertEqual(code.exception.code, 2) self.assertIn(f"{flag} would overwrite the input", err.getvalue()) with open(target, "rb") as f: self.assertEqual(f.read(), old) def test_new_report_inside_a_source_directory_is_still_written(self): with tempfile.TemporaryDirectory() as tmp: src = os.path.join(tmp, "src") os.mkdir(src) write(os.path.join(src, "a.bin"), make_resource(EN)) out = os.path.join(src, "tables.csv") with contextlib.redirect_stdout(io.StringIO()): self.assertEqual(T.main([src, "--tables", out]), 0) self.assertTrue(os.path.isfile(out)) def test_report_cannot_replace_a_carved_stream(self): with tempfile.TemporaryDirectory() as tmp: carve = os.path.join(tmp, "carve") os.mkdir(carve) data = make_resource(EN) stream = write(os.path.join(carve, f"{0x1100:012x}.bin"), data) with open(os.path.join(carve, "index.json"), "w", encoding="utf-8") as fh: json.dump({"files": [{"off": 0x1100, "stored": len(data), "size": len(data), "pre": "", "head": data[:16].hex()}]}, fh) with contextlib.redirect_stderr(io.StringIO()) as err, self.assertRaises(SystemExit) as code: T.main([carve, "--dialogue", stream]) self.assertEqual(code.exception.code, 2) self.assertIn("--dialogue would overwrite the input", err.getvalue()) with open(stream, "rb") as f: self.assertEqual(f.read(), data) def test_two_outputs_naming_one_file_are_refused(self): with tempfile.TemporaryDirectory() as tmp: src = os.path.join(tmp, "src") os.mkdir(src) write(os.path.join(src, "conv.pso"), CONV) out = os.path.join(tmp, "same.csv") with contextlib.redirect_stderr(io.StringIO()) as err: with self.assertRaises(SystemExit) as cm: T.main([src, "--dialogue", out, "--tables", out]) self.assertEqual(cm.exception.code, 2) self.assertIn("distinct", err.getvalue()) self.assertFalse(os.path.exists(out), "no report may be written before the check") def test_missing_input(self): # "/nonexistent" is a drive-root path on Windows (C:\nonexistent), which really exists on some hosts. # Use a path inside a fresh temp directory so the input is guaranteed to be missing on every platform. with tempfile.TemporaryDirectory() as tmp: missing = os.path.join(tmp, "missing-input") self.assertFalse(os.path.exists(missing)) with contextlib.redirect_stderr(io.StringIO()): self.assertEqual(T.main([missing]), 2) def test_missing_parent_and_hardlinked_outputs_rejected_upfront(self): with tempfile.TemporaryDirectory() as tmp: src = write(os.path.join(tmp, "en.bin"), make_resource(EN)) missing_parent = os.path.join(tmp, "no_such_dir", "out.csv") err = io.StringIO() with contextlib.redirect_stderr(err), self.assertRaises(SystemExit) as cm: T.main([src, "--tables", missing_parent]) self.assertEqual(cm.exception.code, 2) self.assertIn("parent directory does not exist", err.getvalue()) first = write(os.path.join(tmp, "first.csv"), b"old\n") alias = os.path.join(tmp, "alias.csv") try: os.link(first, alias) except OSError: self.skipTest("hard links unavailable") err = io.StringIO() with contextlib.redirect_stderr(err), self.assertRaises(SystemExit) as cm: T.main([src, "--dialogue", first, "--tables", alias]) self.assertEqual(cm.exception.code, 2) self.assertIn("distinct", err.getvalue()) def test_invalid_json_labels_is_clean_error_not_traceback(self): with tempfile.TemporaryDirectory() as tmp: src = write(os.path.join(tmp, "en.bin"), make_resource(EN)) bad_labels = os.path.join(tmp, "bad.json") with open(bad_labels, "w", encoding="utf-8") as fh: fh.write("{not valid json") err = io.StringIO() with contextlib.redirect_stderr(err): rc = T.main([src, "--labels", bad_labels]) self.assertEqual(rc, 2) self.assertIn("cannot read input", err.getvalue()) def test_wrong_shape_labels_json_is_clean_error(self): with tempfile.TemporaryDirectory() as tmp: src = write(os.path.join(tmp, "en.bin"), make_resource(EN)) for text in ("[1, 2]", '"x"', "null"): with self.subTest(text): labels = os.path.join(tmp, "labels.json") with open(labels, "w", encoding="utf-8", newline="\n") as fh: fh.write(text) err = io.StringIO() with contextlib.redirect_stderr(err): rc = T.main([src, "--labels", labels]) self.assertEqual(rc, 2) self.assertIn("cannot read input", err.getvalue()) def test_carve_folder_with_wrong_shape_index_is_clean_error(self): for name, text in (("list", "[]"), ("nofiles", "{}"), ("badrow", '{"files": [1]}')): with self.subTest(name), tempfile.TemporaryDirectory() as tmp: with open(os.path.join(tmp, "index.json"), "w", encoding="utf-8", newline="\n") as fh: fh.write(text) err = io.StringIO() with contextlib.redirect_stderr(err): rc = T.main([tmp]) self.assertEqual(rc, 2) self.assertIn("cannot read input", err.getvalue()) UNDECIDED = {"ZZ_CODE_1": "qqq zzz", "ZZ_CODE_2": "xkcd 42"} # no script, letter or word decides: xx def rpf9_header(data_off=0x800): return b"9FPR" + struct.pack("