From 8a54fad9fbeef93ffacda78083cb439c64c93fde Mon Sep 17 00:00:00 2001 From: "Allen.Xiao" Date: Sat, 5 Sep 2026 19:24:26 +0800 Subject: [PATCH 1/6] tmp --- tmp.txt | 1 + 1 file changed, 1 insertion(+) create mode 100644 tmp.txt diff --git a/tmp.txt b/tmp.txt new file mode 100644 index 0000000..c1b0730 --- /dev/null +++ b/tmp.txt @@ -0,0 +1 @@ +x \ No newline at end of file From 6132a30e54f3773f9bab9499eafb204deccb3d6e Mon Sep 17 00:00:00 2001 From: "Allen.Xiao" Date: Sat, 5 Sep 2026 19:24:31 +0800 Subject: [PATCH 2/6] Start Unreal locres adapter --- src/localizer/adapters/resources/unreal_locres.py | 1 + 1 file changed, 1 insertion(+) create mode 100644 src/localizer/adapters/resources/unreal_locres.py diff --git a/src/localizer/adapters/resources/unreal_locres.py b/src/localizer/adapters/resources/unreal_locres.py new file mode 100644 index 0000000..fdffa2a --- /dev/null +++ b/src/localizer/adapters/resources/unreal_locres.py @@ -0,0 +1 @@ +# placeholder From bda5363256d0cd9ee70fca33f7c80a04f096be9a Mon Sep 17 00:00:00 2001 From: "Allen.Xiao" Date: Sat, 5 Sep 2026 19:29:17 +0800 Subject: [PATCH 3/6] Implement Unreal locres v3 adapter for Tyr (#58) --- .../adapters/resources/unreal_locres.py | 405 +++++++++++++++++- 1 file changed, 404 insertions(+), 1 deletion(-) diff --git a/src/localizer/adapters/resources/unreal_locres.py b/src/localizer/adapters/resources/unreal_locres.py index fdffa2a..918907b 100644 --- a/src/localizer/adapters/resources/unreal_locres.py +++ b/src/localizer/adapters/resources/unreal_locres.py @@ -1 +1,404 @@ -# placeholder +from __future__ import annotations + +import io +import json +import struct +from dataclasses import dataclass, replace +from pathlib import Path +from typing import Any, Mapping, Optional, Sequence, Tuple + +from localizer.adapters.resources.options import AdapterOptionsModel, normalize_options +from localizer.adapters.resources.registry import register_adapter +from localizer.domain.translation_unit import TranslationUnit +from localizer.infrastructure.atomic_io import AtomicIO +from localizer.ports.resource import RenderResult, ResourceDescriptor, ValidationResult +from localizer.rules.placeholder import register_placeholder_syntax + + +LOCRES_MAGIC = bytes.fromhex("0e147475674a03fc4a15909dc3377f1b") +LOCRES_VERSION_OPTIMIZED_CITYHASH64_UTF16 = 3 + +# Unreal RichText allows a shorthand close tag (``), which the generic +# `` pattern intentionally does not match. +UNREAL_LOCRES_PLACEHOLDERS: Tuple[str, ...] = ( + r"", +) + +register_placeholder_syntax("unreal_locres", UNREAL_LOCRES_PLACEHOLDERS) + + +@dataclass(frozen=True) +class _LocresEntry: + key_hash: int + key: str + source_string_hash: int + value: str + + +@dataclass(frozen=True) +class _LocresNamespace: + namespace_hash: int + name: str + entries: Tuple[_LocresEntry, ...] + + +@dataclass(frozen=True) +class _LocresV3: + namespaces: Tuple[_LocresNamespace, ...] + + @property + def entry_count(self) -> int: + return sum(len(namespace.entries) for namespace in self.namespaces) + + +class _Reader: + def __init__(self, data: bytes) -> None: + self.data = data + self.pos = 0 + + def seek(self, offset: int) -> None: + if offset < 0 or offset > len(self.data): + raise ValueError(f"locres offset out of bounds: {offset}") + self.pos = offset + + def read(self, size: int) -> bytes: + if size < 0 or self.pos + size > len(self.data): + raise ValueError("truncated locres") + value = self.data[self.pos : self.pos + size] + self.pos += size + return value + + def u8(self) -> int: + return self.read(1)[0] + + def i32(self) -> int: + return struct.unpack(" int: + return struct.unpack(" int: + return struct.unpack(" str: + length = self.i32() + if length == 0: + return "" + if length > 0: + raw = self.read(length) + if not raw.endswith(b"\x00"): + raise ValueError("ANSI FString is missing its terminator") + try: + return raw[:-1].decode("ascii") + except UnicodeDecodeError as exc: + raise ValueError("locres ANSI FString is not ASCII") from exc + + code_units = -length + raw = self.read(code_units * 2) + if not raw.endswith(b"\x00\x00"): + raise ValueError("UTF-16 FString is missing its terminator") + try: + return raw[:-2].decode("utf-16-le") + except UnicodeDecodeError as exc: + raise ValueError("invalid UTF-16 FString") from exc + + +def _write_fstring(stream: io.BytesIO, value: str) -> None: + if "\x00" in value: + raise ValueError("locres strings cannot contain embedded NUL") + if all(ord(char) <= 0x7F for char in value): + payload = value.encode("ascii") + b"\x00" + stream.write(struct.pack(" _LocresV3: + reader = _Reader(data) + if reader.read(len(LOCRES_MAGIC)) != LOCRES_MAGIC: + raise ValueError("unsupported legacy locres: missing magic") + + version = reader.u8() + if version != LOCRES_VERSION_OPTIMIZED_CITYHASH64_UTF16: + raise ValueError( + f"unsupported locres version {version}; unreal_locres v1 supports version 3" + ) + + string_table_offset = reader.i64() + entry_count = reader.i32() + namespace_count = reader.i32() + if entry_count < 0 or namespace_count < 0: + raise ValueError("locres contains negative counts") + + namespace_headers = [] + actual_entries = 0 + for _ in range(namespace_count): + namespace_hash = reader.u32() + namespace = reader.fstring() + key_count = reader.i32() + if key_count < 0: + raise ValueError("locres namespace contains a negative key count") + entries = [] + for _ in range(key_count): + key_hash = reader.u32() + key = reader.fstring() + source_string_hash = reader.u32() + string_index = reader.i32() + entries.append((key_hash, key, source_string_hash, string_index)) + actual_entries += 1 + namespace_headers.append((namespace_hash, namespace, entries)) + + if actual_entries != entry_count: + raise ValueError( + f"locres entry count mismatch: header={entry_count}, parsed={actual_entries}" + ) + if reader.pos != string_table_offset: + raise ValueError( + "locres v3 string-table offset does not match the end of the key table" + ) + + reader.seek(string_table_offset) + string_count = reader.i32() + if string_count < 0: + raise ValueError("locres contains a negative string-table count") + strings = [] + ref_counts = [] + for _ in range(string_count): + strings.append(reader.fstring()) + ref_count = reader.i32() + if ref_count < 0: + raise ValueError("locres contains a negative string reference count") + ref_counts.append(ref_count) + + if reader.pos != len(data): + raise ValueError("locres has unexpected trailing bytes") + + actual_ref_counts = [0] * string_count + namespaces = [] + seen_coordinates = set() + for namespace_hash, namespace, raw_entries in namespace_headers: + entries = [] + for key_hash, key, source_string_hash, string_index in raw_entries: + if string_index < 0 or string_index >= string_count: + raise ValueError(f"locres string index out of range: {string_index}") + coordinate = (namespace, key) + if coordinate in seen_coordinates: + raise ValueError(f"duplicate locres coordinate: {coordinate!r}") + seen_coordinates.add(coordinate) + actual_ref_counts[string_index] += 1 + entries.append( + _LocresEntry( + key_hash=key_hash, + key=key, + source_string_hash=source_string_hash, + value=strings[string_index], + ) + ) + namespaces.append( + _LocresNamespace( + namespace_hash=namespace_hash, + name=namespace, + entries=tuple(entries), + ) + ) + + if actual_ref_counts != ref_counts: + raise ValueError("locres string-table reference counts are inconsistent") + + return _LocresV3(tuple(namespaces)) + + +def _dump_locres_v3(resource: _LocresV3) -> bytes: + stream = io.BytesIO() + stream.write(LOCRES_MAGIC) + stream.write(bytes((LOCRES_VERSION_OPTIMIZED_CITYHASH64_UTF16,))) + string_table_offset_pos = stream.tell() + stream.write(struct.pack(" str: + return json.dumps([namespace, key], ensure_ascii=False, separators=(",", ":")) + + +def _decode_logical_key(value: str) -> Tuple[str, str]: + try: + decoded = json.loads(value) + except json.JSONDecodeError as exc: + raise ValueError(f"invalid unreal_locres logical_key: {value!r}") from exc + if ( + not isinstance(decoded, list) + or len(decoded) != 2 + or not all(isinstance(item, str) for item in decoded) + ): + raise ValueError(f"invalid unreal_locres logical_key: {value!r}") + return decoded[0], decoded[1] + + +@register_adapter +class UnrealLocresAdapter: + adapter_id = "unreal_locres" + options_model = AdapterOptionsModel + + def __init__( + self, + *, + project_id: str, + source_root: Path, + source_locale: str, + target_locale: str, + options: Optional[Mapping[str, Any]] = None, + ) -> None: + self.options = normalize_options(self.options_model, options) + self.project_id = project_id + self.source_root = Path(source_root).resolve() + self.source_locale = source_locale + self.target_locale = target_locale + + def probe(self, path: Path) -> float: + candidate = Path(path) + if candidate.suffix.lower() != ".locres" or not candidate.is_file(): + return 0.0 + try: + _load_locres_v3(AtomicIO.read_bytes(candidate)) + except (OSError, ValueError): + return 0.0 + return 1.0 + + def scan(self, path: Path) -> ResourceDescriptor: + candidate = Path(path).resolve(strict=True) + confidence = self.probe(candidate) + if confidence == 0: + raise ValueError(f"not a supported Unreal locres v3 resource: {candidate}") + return ResourceDescriptor( + self.adapter_id, + candidate, + self._relative(candidate), + candidate.stat().st_size, + confidence, + ) + + def extract(self, path: Path) -> Sequence[TranslationUnit]: + candidate = Path(path).resolve(strict=True) + resource = _load_locres_v3(AtomicIO.read_bytes(candidate)) + relative = self._relative(candidate) + units = [] + for namespace in resource.namespaces: + for entry in namespace.entries: + units.append( + TranslationUnit( + project_id=self.project_id, + adapter_id=self.adapter_id, + relative_path=relative, + logical_file=relative, + logical_key=_logical_key(namespace.name, entry.key), + source_text=entry.value, + translation=None, + context=f"{namespace.name} / {entry.key}" + if namespace.name + else entry.key, + source_locale=self.source_locale, + target_locale=self.target_locale, + metadata={ + "namespace": namespace.name, + "key": entry.key, + "locres_version": LOCRES_VERSION_OPTIMIZED_CITYHASH64_UTF16, + "source_string_hash": entry.source_string_hash, + "namespace_hash": namespace.namespace_hash, + "key_hash": entry.key_hash, + }, + ) + ) + return tuple(units) + + def render( + self, units: Sequence[TranslationUnit], source: Path, destination: Path + ) -> RenderResult: + source_path = Path(source).resolve(strict=True) + resource = _load_locres_v3(AtomicIO.read_bytes(source_path)) + + source_entries = { + (namespace.name, entry.key) + for namespace in resource.namespaces + for entry in namespace.entries + } + translations = {} + for unit in units: + coordinate = _decode_logical_key(unit.logical_key) + if coordinate not in source_entries: + raise ValueError( + f"unreal_locres unit does not exist in source: {coordinate!r}" + ) + if coordinate in translations: + raise ValueError(f"duplicate unreal_locres unit: {coordinate!r}") + if unit.translation is not None: + translations[coordinate] = unit.translation + + namespaces = [] + for namespace in resource.namespaces: + entries = [] + for entry in namespace.entries: + value = translations.get((namespace.name, entry.key), entry.value) + entries.append(replace(entry, value=value)) + namespaces.append(replace(namespace, entries=tuple(entries))) + + destination_path = AtomicIO.write_bytes( + Path(destination), _dump_locres_v3(_LocresV3(tuple(namespaces))) + ) + validation = self.validate(destination_path) + return RenderResult(destination_path, len(units), validation) + + def validate(self, path: Path) -> ValidationResult: + try: + _load_locres_v3(AtomicIO.read_bytes(Path(path))) + except (OSError, ValueError) as exc: + return ValidationResult(False, (str(exc),)) + return ValidationResult(True) + + def _relative(self, path: Path) -> str: + try: + return path.relative_to(self.source_root).as_posix() + except ValueError as exc: + raise ValueError( + f"resource is outside source root {self.source_root}: {path}" + ) from exc From 8d93b6406dd530738e96a67aaf74daa2813da57d Mon Sep 17 00:00:00 2001 From: "Allen.Xiao" Date: Sat, 5 Sep 2026 19:29:22 +0800 Subject: [PATCH 4/6] Remove temporary branch-write probe --- tmp.txt | 1 - 1 file changed, 1 deletion(-) delete mode 100644 tmp.txt diff --git a/tmp.txt b/tmp.txt deleted file mode 100644 index c1b0730..0000000 --- a/tmp.txt +++ /dev/null @@ -1 +0,0 @@ -x \ No newline at end of file From 27bee5581aa2fdae91a5a549e434f6712fea9d31 Mon Sep 17 00:00:00 2001 From: "Allen.Xiao" Date: Sat, 5 Sep 2026 19:29:59 +0800 Subject: [PATCH 5/6] Add Unreal locres round-trip and placeholder regressions (#58) --- tests/test_unreal_locres_adapter.py | 169 ++++++++++++++++++++++++++++ 1 file changed, 169 insertions(+) create mode 100644 tests/test_unreal_locres_adapter.py diff --git a/tests/test_unreal_locres_adapter.py b/tests/test_unreal_locres_adapter.py new file mode 100644 index 0000000..5b4df2a --- /dev/null +++ b/tests/test_unreal_locres_adapter.py @@ -0,0 +1,169 @@ +from __future__ import annotations + +from dataclasses import replace + +from localizer.adapters.resources.registry import available_adapters +from localizer.adapters.resources.unreal_locres import ( + LOCRES_VERSION_OPTIMIZED_CITYHASH64_UTF16, + UnrealLocresAdapter, + _LocresEntry, + _LocresNamespace, + _LocresV3, + _dump_locres_v3, +) +from localizer.rules.placeholder import PlaceholderRule + + +def _fixture() -> _LocresV3: + return _LocresV3( + ( + _LocresNamespace( + namespace_hash=101, + name="ST_A", + entries=( + _LocresEntry( + key_hash=201, + key="Label", + source_string_hash=301, + value="{PlayerName}", + ), + _LocresEntry( + key_hash=202, + key="Plural", + source_string_hash=302, + value="Add {Quantity}|plural(one=Salute,other=Salutes)", + ), + ), + ), + _LocresNamespace( + namespace_hash=102, + name="ST_B", + entries=( + _LocresEntry( + key_hash=203, + key="Label", + source_string_hash=303, + value="Ability", + ), + ), + ), + ) + ) + + +def _adapter(tmp_path) -> UnrealLocresAdapter: + return UnrealLocresAdapter( + project_id="tyr", + source_root=tmp_path, + source_locale="en", + target_locale="zh-Hans", + options={}, + ) + + +def _semantic(units): + return tuple( + ( + unit.logical_key, + unit.source_text, + unit.metadata["source_string_hash"], + unit.metadata["namespace_hash"], + unit.metadata["key_hash"], + ) + for unit in units + ) + + +def test_unreal_locres_is_discovered_and_extracts_stable_namespace_key_identity(tmp_path): + assert "unreal_locres" in available_adapters() + + source = tmp_path / "Tyr/Content/Localization/Game/en/Game.locres" + source.parent.mkdir(parents=True) + source.write_bytes(_dump_locres_v3(_fixture())) + + adapter = _adapter(tmp_path) + assert adapter.probe(source) == 1.0 + assert adapter.scan(source).relative_path == "Tyr/Content/Localization/Game/en/Game.locres" + + units = adapter.extract(source) + assert len(units) == 3 + assert units[0].logical_key == '["ST_A","Label"]' + assert units[2].logical_key == '["ST_B","Label"]' + assert units[0].stable_identity != units[2].stable_identity + assert units[0].translation is None + assert units[0].metadata["locres_version"] == LOCRES_VERSION_OPTIMIZED_CITYHASH64_UTF16 + + +def test_unreal_locres_noop_render_is_byte_identical_and_semantically_equal(tmp_path): + source = tmp_path / "source/Game.locres" + source.parent.mkdir(parents=True) + original = _dump_locres_v3(_fixture()) + source.write_bytes(original) + + adapter = _adapter(tmp_path) + before = adapter.extract(source) + destination = tmp_path / "rendered/Game.locres" + result = adapter.render(before, source, destination) + + assert result.validation.valid + assert destination.read_bytes() == original + after = adapter.extract(destination) + assert _semantic(after) == _semantic(before) + + +def test_unreal_locres_single_entry_mutation_preserves_unrelated_entries_and_hashes(tmp_path): + source = tmp_path / "source/Game.locres" + source.parent.mkdir(parents=True) + source.write_bytes(_dump_locres_v3(_fixture())) + + adapter = _adapter(tmp_path) + before = adapter.extract(source) + changed = tuple( + replace(unit, translation="{PlayerName},你好") + if unit.logical_key == '["ST_A","Label"]' + else unit + for unit in before + ) + + destination = tmp_path / "rendered/Game.locres" + result = adapter.render(changed, source, destination) + assert result.validation.valid + + after = adapter.extract(destination) + differences = [ + (left, right) + for left, right in zip(before, after) + if left.source_text != right.source_text + ] + assert len(differences) == 1 + original, translated = differences[0] + assert original.logical_key == translated.logical_key == '["ST_A","Label"]' + assert translated.source_text == "{PlayerName},你好" + assert translated.metadata == original.metadata + + unchanged_before = [unit for unit in before if unit.logical_key != '["ST_A","Label"]'] + unchanged_after = [unit for unit in after if unit.logical_key != '["ST_A","Label"]'] + assert _semantic(unchanged_after) == _semantic(unchanged_before) + + +def test_unreal_locres_placeholder_profile_covers_richtext_shorthand_close(): + rule = PlaceholderRule.for_adapter("unreal_locres") + assert rule.extract("{PlayerName}") == ( + "", + "{PlayerName}", + "", + ) + assert rule.round_trip("{PlayerName}") + + +def test_unreal_locres_v1_fails_closed_on_other_versions(tmp_path): + source = tmp_path / "Game.locres" + payload = bytearray(_dump_locres_v3(_fixture())) + payload[16] = 2 + source.write_bytes(payload) + + adapter = _adapter(tmp_path) + assert adapter.probe(source) == 0.0 + validation = adapter.validate(source) + assert not validation.valid + assert "supports version 3" in validation.errors[0] From e96c8495bdf28e6509dd01f8c0bd59df35929e71 Mon Sep 17 00:00:00 2001 From: "Allen.Xiao" Date: Sat, 5 Sep 2026 19:30:51 +0800 Subject: [PATCH 6/6] Run Unreal locres regressions under unittest discovery (#58) --- tests/test_unreal_locres_adapter.py | 201 +++++++++++++++------------- 1 file changed, 109 insertions(+), 92 deletions(-) diff --git a/tests/test_unreal_locres_adapter.py b/tests/test_unreal_locres_adapter.py index 5b4df2a..bc96a68 100644 --- a/tests/test_unreal_locres_adapter.py +++ b/tests/test_unreal_locres_adapter.py @@ -1,6 +1,9 @@ from __future__ import annotations +import tempfile +import unittest from dataclasses import replace +from pathlib import Path from localizer.adapters.resources.registry import available_adapters from localizer.adapters.resources.unreal_locres import ( @@ -51,16 +54,6 @@ def _fixture() -> _LocresV3: ) -def _adapter(tmp_path) -> UnrealLocresAdapter: - return UnrealLocresAdapter( - project_id="tyr", - source_root=tmp_path, - source_locale="en", - target_locale="zh-Hans", - options={}, - ) - - def _semantic(units): return tuple( ( @@ -74,96 +67,120 @@ def _semantic(units): ) -def test_unreal_locres_is_discovered_and_extracts_stable_namespace_key_identity(tmp_path): - assert "unreal_locres" in available_adapters() - - source = tmp_path / "Tyr/Content/Localization/Game/en/Game.locres" - source.parent.mkdir(parents=True) - source.write_bytes(_dump_locres_v3(_fixture())) - - adapter = _adapter(tmp_path) - assert adapter.probe(source) == 1.0 - assert adapter.scan(source).relative_path == "Tyr/Content/Localization/Game/en/Game.locres" - - units = adapter.extract(source) - assert len(units) == 3 - assert units[0].logical_key == '["ST_A","Label"]' - assert units[2].logical_key == '["ST_B","Label"]' - assert units[0].stable_identity != units[2].stable_identity - assert units[0].translation is None - assert units[0].metadata["locres_version"] == LOCRES_VERSION_OPTIMIZED_CITYHASH64_UTF16 +class UnrealLocresAdapterTest(unittest.TestCase): + def setUp(self) -> None: + self._temp = tempfile.TemporaryDirectory() + self.root = Path(self._temp.name) + self.adapter = UnrealLocresAdapter( + project_id="tyr", + source_root=self.root, + source_locale="en", + target_locale="zh-Hans", + options={}, + ) + def tearDown(self) -> None: + self._temp.cleanup() -def test_unreal_locres_noop_render_is_byte_identical_and_semantically_equal(tmp_path): - source = tmp_path / "source/Game.locres" - source.parent.mkdir(parents=True) - original = _dump_locres_v3(_fixture()) - source.write_bytes(original) + def _write_fixture(self, relative: str = "source/Game.locres") -> Path: + source = self.root / relative + source.parent.mkdir(parents=True, exist_ok=True) + source.write_bytes(_dump_locres_v3(_fixture())) + return source - adapter = _adapter(tmp_path) - before = adapter.extract(source) - destination = tmp_path / "rendered/Game.locres" - result = adapter.render(before, source, destination) + def test_is_discovered_and_extracts_stable_namespace_key_identity(self) -> None: + self.assertIn("unreal_locres", available_adapters()) + source = self._write_fixture( + "Tyr/Content/Localization/Game/en/Game.locres" + ) - assert result.validation.valid - assert destination.read_bytes() == original - after = adapter.extract(destination) - assert _semantic(after) == _semantic(before) + self.assertEqual(self.adapter.probe(source), 1.0) + self.assertEqual( + self.adapter.scan(source).relative_path, + "Tyr/Content/Localization/Game/en/Game.locres", + ) + units = self.adapter.extract(source) + self.assertEqual(len(units), 3) + self.assertEqual(units[0].logical_key, '["ST_A","Label"]') + self.assertEqual(units[2].logical_key, '["ST_B","Label"]') + self.assertNotEqual(units[0].stable_identity, units[2].stable_identity) + self.assertIsNone(units[0].translation) + self.assertEqual( + units[0].metadata["locres_version"], + LOCRES_VERSION_OPTIMIZED_CITYHASH64_UTF16, + ) -def test_unreal_locres_single_entry_mutation_preserves_unrelated_entries_and_hashes(tmp_path): - source = tmp_path / "source/Game.locres" - source.parent.mkdir(parents=True) - source.write_bytes(_dump_locres_v3(_fixture())) + def test_noop_render_is_byte_identical_and_semantically_equal(self) -> None: + source = self._write_fixture() + original = source.read_bytes() + + before = self.adapter.extract(source) + destination = self.root / "rendered/Game.locres" + result = self.adapter.render(before, source, destination) + + self.assertTrue(result.validation.valid) + self.assertEqual(destination.read_bytes(), original) + after = self.adapter.extract(destination) + self.assertEqual(_semantic(after), _semantic(before)) + + def test_single_entry_mutation_preserves_unrelated_entries_and_hashes(self) -> None: + source = self._write_fixture() + before = self.adapter.extract(source) + changed = tuple( + replace(unit, translation="{PlayerName},你好") + if unit.logical_key == '["ST_A","Label"]' + else unit + for unit in before + ) - adapter = _adapter(tmp_path) - before = adapter.extract(source) - changed = tuple( - replace(unit, translation="{PlayerName},你好") - if unit.logical_key == '["ST_A","Label"]' - else unit - for unit in before - ) + destination = self.root / "rendered/Game.locres" + result = self.adapter.render(changed, source, destination) + self.assertTrue(result.validation.valid) + + after = self.adapter.extract(destination) + differences = [ + (left, right) + for left, right in zip(before, after) + if left.source_text != right.source_text + ] + self.assertEqual(len(differences), 1) + original, translated = differences[0] + self.assertEqual( + original.logical_key, + translated.logical_key, + ) + self.assertEqual(translated.logical_key, '["ST_A","Label"]') + self.assertEqual(translated.source_text, "{PlayerName},你好") + self.assertEqual(translated.metadata, original.metadata) + + unchanged_before = [ + unit for unit in before if unit.logical_key != '["ST_A","Label"]' + ] + unchanged_after = [ + unit for unit in after if unit.logical_key != '["ST_A","Label"]' + ] + self.assertEqual(_semantic(unchanged_after), _semantic(unchanged_before)) + + def test_placeholder_profile_covers_richtext_shorthand_close(self) -> None: + rule = PlaceholderRule.for_adapter("unreal_locres") + self.assertEqual( + rule.extract("{PlayerName}"), + ("", "{PlayerName}", ""), + ) + self.assertTrue(rule.round_trip("{PlayerName}")) - destination = tmp_path / "rendered/Game.locres" - result = adapter.render(changed, source, destination) - assert result.validation.valid - - after = adapter.extract(destination) - differences = [ - (left, right) - for left, right in zip(before, after) - if left.source_text != right.source_text - ] - assert len(differences) == 1 - original, translated = differences[0] - assert original.logical_key == translated.logical_key == '["ST_A","Label"]' - assert translated.source_text == "{PlayerName},你好" - assert translated.metadata == original.metadata - - unchanged_before = [unit for unit in before if unit.logical_key != '["ST_A","Label"]'] - unchanged_after = [unit for unit in after if unit.logical_key != '["ST_A","Label"]'] - assert _semantic(unchanged_after) == _semantic(unchanged_before) - - -def test_unreal_locres_placeholder_profile_covers_richtext_shorthand_close(): - rule = PlaceholderRule.for_adapter("unreal_locres") - assert rule.extract("{PlayerName}") == ( - "", - "{PlayerName}", - "", - ) - assert rule.round_trip("{PlayerName}") + def test_v1_fails_closed_on_other_versions(self) -> None: + source = self.root / "Game.locres" + payload = bytearray(_dump_locres_v3(_fixture())) + payload[16] = 2 + source.write_bytes(payload) + self.assertEqual(self.adapter.probe(source), 0.0) + validation = self.adapter.validate(source) + self.assertFalse(validation.valid) + self.assertIn("supports version 3", validation.errors[0]) -def test_unreal_locres_v1_fails_closed_on_other_versions(tmp_path): - source = tmp_path / "Game.locres" - payload = bytearray(_dump_locres_v3(_fixture())) - payload[16] = 2 - source.write_bytes(payload) - adapter = _adapter(tmp_path) - assert adapter.probe(source) == 0.0 - validation = adapter.validate(source) - assert not validation.valid - assert "supports version 3" in validation.errors[0] +if __name__ == "__main__": + unittest.main()