mirror of
https://github.com/db9979/uconsole_asw_game.git
synced 2026-12-05 20:34:16 +01:00
AGENTS.md describes the mixin composition; the i18n prose scans and the manual key-binding scan read all game modules and the stations package instead of the old monolith. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
283 lines
12 KiB
Python
283 lines
12 KiB
Python
import ast
|
||
import json
|
||
from pathlib import Path
|
||
import re
|
||
|
||
import pytest
|
||
|
||
from src.core.help import get_help
|
||
from src.core.i18n import (
|
||
DISPLAY_KEYS,
|
||
TranslationError,
|
||
Translator,
|
||
detect_system_language,
|
||
load_catalog,
|
||
display_value,
|
||
localize,
|
||
message,
|
||
raw_text,
|
||
pseudolocale,
|
||
translation_scope,
|
||
validate_catalog,
|
||
)
|
||
from src.core.station import Station
|
||
|
||
|
||
def test_catalogs_have_exact_key_and_placeholder_parity():
|
||
english = load_catalog("en")
|
||
german = load_catalog("de")
|
||
assert english.keys() == german.keys()
|
||
validate_catalog(german, english)
|
||
|
||
|
||
def test_translation_formats_named_values_and_falls_back_to_english():
|
||
assert Translator("de").t("menu.seed", seed=42) == "Seed: 42"
|
||
assert Translator("fr").language == "en"
|
||
assert Translator("de").t("missing.key") == "missing.key"
|
||
with pytest.raises(TranslationError, match="missing placeholders"):
|
||
Translator("en").t("menu.seed")
|
||
|
||
|
||
def test_system_language_normalization():
|
||
assert detect_system_language("de_DE.UTF-8") == "de"
|
||
assert detect_system_language("en-US") == "en"
|
||
assert detect_system_language("fr_FR") == "en"
|
||
|
||
|
||
def test_pseudolocale_preserves_keys_and_placeholders():
|
||
source = load_catalog("en")
|
||
pseudo = pseudolocale(source)
|
||
assert pseudo.keys() == source.keys()
|
||
assert pseudo["menu.seed"].format(seed=7).startswith("[!!")
|
||
validate_catalog(pseudo, source)
|
||
|
||
|
||
def test_commander_confirmation_catalog_contract():
|
||
required = {
|
||
"commander.confirm.title", "commander.confirm.target",
|
||
"commander.confirm.navigation", "commander.confirm.unchanged",
|
||
"commander.confirm.accept", "commander.confirm.reject",
|
||
"commander.confirm.hint.single", "commander.confirm.hint.multiple",
|
||
}
|
||
for catalog in (load_catalog("en"), load_catalog("de"),
|
||
pseudolocale(load_catalog("en"))):
|
||
assert required <= catalog.keys()
|
||
validate_catalog(catalog, load_catalog("en"))
|
||
|
||
|
||
def test_commander_guide_catalog_contract():
|
||
topics = {
|
||
"access", "operations", "observations", "proposals", "eloka",
|
||
"analyzer", "connection", "authority",
|
||
}
|
||
required = {
|
||
"commander.web.guide_title", "commander.web.guide_intro",
|
||
"commander.web.guide_navigation", "commander.web.guide_lookout",
|
||
"commander.web.guide_target_proposal",
|
||
"commander.web.guide_navigation_proposal",
|
||
"commander.web.guide_message_box",
|
||
"commander.web.guide_reconciliation", "commander.web.guide_emcon",
|
||
"commander.web.guide_security", "commander.web.guide_reconnect",
|
||
"commander.web.guide_authority_forbidden",
|
||
}
|
||
required |= {f"commander.web.guide_nav_{topic}" for topic in topics}
|
||
required |= {f"commander.web.guide_{topic}_title" for topic in topics}
|
||
english = load_catalog("en")
|
||
for catalog in (english, load_catalog("de"), pseudolocale(english)):
|
||
assert required <= catalog.keys()
|
||
assert all(catalog[key] for key in required)
|
||
validate_catalog(catalog, english)
|
||
|
||
|
||
def test_exact_legacy_literals_work_but_composed_text_is_not_parsed():
|
||
english = Translator("en")
|
||
german = Translator("de")
|
||
|
||
assert english.display("Brücke / Nautik") == "Bridge / Navigation"
|
||
assert english.display("K3 klassifiziert: U-Boot") == \
|
||
"K3 klassifiziert: U-Boot"
|
||
assert german.t("Saved") == "Gespeichert"
|
||
assert german.display("STOWED") == "VERSTAUT"
|
||
|
||
|
||
def test_structured_messages_retranslate_and_keep_authored_braces_opaque():
|
||
value = message("runtime.mission.started", name=raw_text("{author.name}"),
|
||
level=message("level.custom"),
|
||
objective=raw_text("Reach {sector[0]}"))
|
||
json.dumps(value)
|
||
assert localize(value, Translator("en").t) == \
|
||
"Mission: {author.name} (Custom) - Reach {sector[0]}"
|
||
assert localize(value, Translator("de").t) == \
|
||
"Mission: {author.name} (Individuell) - Reach {sector[0]}"
|
||
|
||
|
||
def test_raw_text_bypasses_catalog_literals():
|
||
assert localize(raw_text("Saved"), Translator("de").t) == "Saved"
|
||
assert localize("Saved", Translator("de").t) == "Gespeichert"
|
||
|
||
|
||
def test_display_mappings_cover_required_persisted_enum_families():
|
||
required = {"station", "classification", "affiliation", "array", "tow",
|
||
"tma", "fusion", "weapon_mode", "profile_kind", "side",
|
||
"weather", "objective", "event", "placement", "used_by"}
|
||
assert required <= DISPLAY_KEYS.keys()
|
||
assert display_value("classification", "U_BOOT", Translator("de").t) == "U-Boot"
|
||
assert display_value("weather", "storm", Translator("en").t) == "Storm"
|
||
|
||
|
||
def test_help_and_open_editor_literals_follow_the_current_draw_scope():
|
||
intro_en, controls_en, _, _ = get_help(Station.BRIDGE, Translator("en").t)
|
||
intro_de, controls_de, _, _ = get_help(Station.BRIDGE, Translator("de").t)
|
||
assert intro_en.startswith("Bridge / Navigation")
|
||
assert intro_de.startswith("Brücke / Nautik")
|
||
assert controls_en[0][1] == "Rudder: change target course"
|
||
assert controls_de[0][1] == "Ruder: Zielkurs ändern"
|
||
|
||
with translation_scope(Translator("de").t):
|
||
from src.core.i18n import localize
|
||
assert localize("Mission library") == "Missionsbibliothek"
|
||
with translation_scope(Translator("en").t):
|
||
assert localize("Mission library") == "Mission library"
|
||
|
||
|
||
# The Game class is composed from mixin modules (plan 1.3, phase 2); every
|
||
# scan of "the game's prose" covers all of them, and the station views live
|
||
# in the src/ui/stations package beside the flat src/ui modules.
|
||
CORE_GAME_FILES = sorted(Path("src/core").glob("game*.py")) + [Path("src/core/mission_bridge.py")]
|
||
UI_FILES = sorted(Path("src/ui").rglob("*.py"))
|
||
|
||
|
||
def test_ui_direct_font_literals_are_explicitly_technical_allowlist():
|
||
"""New prose must use bounded/localized helpers, not Font.render directly."""
|
||
allowed = {"[ ]", "ASM", "ESM", "HOJ", "HSP-5"}
|
||
violations = []
|
||
paths = CORE_GAME_FILES + UI_FILES
|
||
for path in paths:
|
||
tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
|
||
for node in ast.walk(tree):
|
||
if not (isinstance(node, ast.Call)
|
||
and isinstance(node.func, ast.Attribute)
|
||
and node.func.attr == "render" and node.args):
|
||
continue
|
||
value = node.args[0]
|
||
if (isinstance(value, ast.Constant) and isinstance(value.value, str)
|
||
and value.value not in allowed):
|
||
violations.append(f"{path}:{node.lineno}: {value.value!r}")
|
||
assert not violations, "hardcoded Font.render UI literals:\n" + "\n".join(violations)
|
||
|
||
|
||
def test_static_text_sent_to_ui_helpers_is_cataloged_or_technical():
|
||
"""Audit every bounded rendering entry point, not only Font.render."""
|
||
english = load_catalog("en")
|
||
catalog_text = set(english) | set(english.values()) | set(load_catalog("de").values())
|
||
proper_names = {"U-JAGD – FREGATTE F-217"}
|
||
technical = {"N", "PING", "U-JAGD / ASW", "RADAR", "VLS:", "ESM:",
|
||
"HSP-5 DL", "ROE", "HSP-5", "CIWS:"}
|
||
text_arguments = {
|
||
"tr": (0,), "translate": (0,), "center": (0,),
|
||
"blit_line": (1,), "blit_block": (1,), "draw_text": (1,), "_text": (1,),
|
||
"box": (2,), "panel": (2,), "status_line": (4, 5),
|
||
"tooltip_payload": tuple(range(8)),
|
||
}
|
||
violations = []
|
||
paths = [*CORE_GAME_FILES, Path("src/core/help.py"), *UI_FILES]
|
||
for path in paths:
|
||
tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
|
||
for node in ast.walk(tree):
|
||
if not isinstance(node, ast.Call) or not node.args:
|
||
continue
|
||
name = (node.func.attr if isinstance(node.func, ast.Attribute) else
|
||
node.func.id if isinstance(node.func, ast.Name) else "")
|
||
for index in text_arguments.get(name, ()):
|
||
if index >= len(node.args):
|
||
continue
|
||
value = node.args[index]
|
||
if (not isinstance(value, ast.Constant)
|
||
or not isinstance(value.value, str) or not value.value):
|
||
continue
|
||
if (value.value not in catalog_text and value.value not in proper_names
|
||
and value.value not in technical):
|
||
violations.append(f"{path}:{node.lineno}: {value.value!r}")
|
||
assert not violations, "uncataloged static UI text:\n" + "\n".join(violations)
|
||
|
||
|
||
@pytest.mark.parametrize("language,opposite_words", [
|
||
("en", {"HOERSTRAHL", "SCHMALBAND", "SEITE", "KONTAKT", "STRAHL",
|
||
"ZIEL", "TORPEDOTIEFE", "BOJE", "LUFTTORPEDO", "ZUGEHOERIGKEIT",
|
||
"SCHADENSABWEHR", "FLUTUNG", "TREIBSTOFF", "FAHRT", "LAERM",
|
||
"MASCHINERIE", "SONARBOJEN"}),
|
||
("de", {"BEARING", "RANGE", "PAGE", "CONTACT", "BEAM", "TARGET",
|
||
"DAMAGE", "FLOODING", "FUEL", "SPEED", "NOISE", "MACHINERY",
|
||
"SONOBUOYS", "AFFILIATION", "ENGINE"}),
|
||
])
|
||
def test_every_station_and_sonar_page_excludes_opposite_language_operational_words(
|
||
language, opposite_words):
|
||
from src.core.game import Game
|
||
from src.ui import layout
|
||
|
||
game = Game(seed=41, fullscreen=False, window_size=(1280, 720),
|
||
audio_enabled=False)
|
||
translator = Translator(language)
|
||
game.translator = translator
|
||
game.tr = translator.t
|
||
captures = []
|
||
for station in Station:
|
||
game.station = station
|
||
pages = range(6) if station is Station.SONAR else range(1)
|
||
for page in pages:
|
||
game.sonar_page = page
|
||
with layout.capture_text() as rendered:
|
||
game.draw()
|
||
assert rendered, f"no instrumented text for {station.name} page {page}"
|
||
captures.extend(item["text"] for item in rendered)
|
||
|
||
visible = "\n".join(captures).upper()
|
||
leaked = sorted(word for word in opposite_words
|
||
if re.search(rf"(?<![A-Z]){re.escape(word)}(?![A-Z])", visible))
|
||
assert not leaked, f"{language} rendering contains opposite-language words: {leaked}"
|
||
|
||
|
||
def test_runtime_message_sinks_do_not_receive_composed_prose():
|
||
"""Runtime notices must remain structured so a language switch can redraw them."""
|
||
violations = []
|
||
composed = (ast.Constant, ast.JoinedStr, ast.BinOp, ast.IfExp)
|
||
for path in CORE_GAME_FILES:
|
||
tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
|
||
for node in ast.walk(tree):
|
||
if not isinstance(node, ast.Call) or not node.args:
|
||
continue
|
||
name = node.func.attr if isinstance(node.func, ast.Attribute) else ""
|
||
if name in ("flash", "hq_msg"):
|
||
value = node.args[0]
|
||
elif (name == "add" and isinstance(node.func.value, ast.Attribute)
|
||
and node.func.value.attr == "feed" and len(node.args) >= 3):
|
||
value = node.args[2]
|
||
else:
|
||
continue
|
||
if isinstance(value, composed):
|
||
violations.append(f"{path}:{node.lineno}: {ast.unparse(value)}")
|
||
assert not violations, "composed runtime UI prose:\n" + "\n".join(violations)
|
||
|
||
|
||
def test_game_does_not_send_composed_text_to_exact_localization():
|
||
violations = []
|
||
for path in CORE_GAME_FILES:
|
||
tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
|
||
for node in ast.walk(tree):
|
||
if not isinstance(node, ast.Call) or not node.args:
|
||
continue
|
||
name = (node.func.attr if isinstance(node.func, ast.Attribute) else
|
||
node.func.id if isinstance(node.func, ast.Name) else "")
|
||
if name in ("localize", "display") and isinstance(
|
||
node.args[0], (ast.JoinedStr, ast.BinOp)):
|
||
violations.append(f"{path}:{node.lineno}: {ast.unparse(node.args[0])}")
|
||
assert not violations, "composed exact-localization input:\n" + "\n".join(violations)
|
||
|
||
|
||
def test_legacy_ascii_german_literals_resolve_to_umlaut_catalog():
|
||
# The German catalog uses real umlauts; older code literals spelled them
|
||
# as ae/oe/ue/ss and must still find their key in both languages.
|
||
assert "Zurück zum Spiel" in Translator("de").catalog.values()
|
||
assert Translator("de").t("Zurueck zum Spiel") == "Zurück zum Spiel"
|
||
assert Translator("en").t("Zurueck zum Spiel") == "Return to game"
|