from __future__ import annotations import unittest from concurrent.futures import ThreadPoolExecutor from backend.sql_catalog.i18n import localize_error, negotiate_locale, translate class I18nTest(unittest.TestCase): def test_accept_language_negotiation_honors_quality_and_fallback(self) -> None: self.assertEqual("zh-CN", negotiate_locale("zh-CN, en;q=0.8")) self.assertEqual("en", negotiate_locale("fr;q=0.9, en-US;q=0.7")) self.assertEqual("zh-CN", negotiate_locale("en;q=0.4, zh-Hans;q=0.9")) self.assertEqual("en", negotiate_locale(None)) def test_structured_errors_keep_stable_codes_and_localize_text(self) -> None: english = localize_error({"error": "finding_not_found"}, "en") chinese = localize_error({"error": "finding_not_found"}, "zh-CN") self.assertEqual("finding_not_found", english["error"]["code"]) self.assertEqual("finding_not_found", chinese["error"]["code"]) self.assertEqual("api:errors.finding_not_found", chinese["error"]["message"]["key"]) self.assertNotEqual( english["error"]["message"]["text"], chinese["error"]["message"]["text"], ) def test_localized_errors_do_not_leak_raw_internal_messages(self) -> None: localized = localize_error( { "error": "invalid_query", "message": "q must be at most 200 characters", "limit": 200, }, "zh-CN", ) self.assertEqual("搜索条件无效。", localized["error"]["message"]["text"]) self.assertEqual({"limit": 200}, localized["error"]["details"]) self.assertNotIn("q must be", str(localized)) def test_parallel_translation_has_no_cross_request_locale_state(self) -> None: requests = ["en", "zh-CN"] * 100 def render(locale: str) -> tuple[str, str]: return locale, translate("domain:entity.catalog", locale) with ThreadPoolExecutor(max_workers=12) as executor: results = list(executor.map(render, requests)) for locale, value in results: self.assertEqual("Catalog" if locale == "en" else "SQL 目录", value) if __name__ == "__main__": unittest.main()