如何为 Django 的 gettext 翻译写测试并验证占位符?
解读
在国内 Django 项目中,国际化(i18n)是上线前必须通过 QA 的硬指标。面试官问“如何为 gettext 翻译写测试并验证占位符”,核心想确认三件事:
- 你是否理解 gettext 的工作流程(生成 .po、编译 .mo、运行时翻译)。
- 能否用 Pytest 快速构造“多语言+参数化”测试,覆盖中文、英文、甚至小语种。
- 占位符(format string、named placeholder、复数形式)一旦翻错,线上会直接 500 或出现“{}”裸露,造成舆情事故,因此必须做刚性校验。
面试现场通常给你 10~15 分钟口述+写代码,要求“能跑、能断言、能 CI”。如果只说“我手动点页面切换语言”会被直接判负。
知识点
- Django 翻译栈:django.utils.translation.override() 可临时切换语言,无需改 settings。
- gettext 占位符语法:Python format({}、{name})、%(name)s、复数 ngettext。
- Pytest 参数化:pytest.mark.parametrize 可一次把多组(msgid、msgstr、占位符列表、语言)打表执行。
- 占位符校验策略:用正则提取原始字符串与翻译字符串的占位符集合,比较是否一致;复数形式需分别检查 singular 与 plural。
- Fixture 隔离:在 conftest.py 里提供“编译 mo 文件”的 session 级 fixture,确保 CI 环境无人工干预。
- 异常处理:翻译缺失时 gettext 会回退到 msgid,此时断言必须失败,防止“英文裸露”混到中文界面。
- 性能:测试层只加载 po/mo,不启动 LiveServer,毫秒级结束,适合并发执行。
答案
项目结构(精简):
locale/
├── zh_Hans/
│ └── LC_MESSAGES/
│ ├── django.po
│ └── django.mo
mysite/
├── polls/
│ └── utils.py # 包含待翻译函数
tests/
├── conftest.py
└── test_i18n.py
- conftest.py —— 编译 mo 的自动化 fixture
import subprocess
from pathlib import Path
import pytest
PO_ROOT = Path(__file__).resolve().parent.parent / "locale"
@pytest.fixture(scope="session", autouse=True)
def compile_mo():
"""确保每次测试会话前 po 文件已编译为 mo,CI 无人工干预。"""
for po_file in PO_ROOT.rglob("*.po"):
mo_file = po_file.with_suffix(".mo")
subprocess.run(["django-admin", "compilemessages"], cwd=po_file.parent, check=True)
- 被测代码 polls/utils.py
from django.utils.translation import gettext as _, ngettext
def welcome(name: str, count: int) -> str:
if count == 1:
return _("Hello {name}, you have {count} message.").format(name=name, count=count)
return ngettext(
"Hello {name}, you have {count} message.",
"Hello {name}, you have {count} messages.",
count
).format(name=name, count=count)
- 测试文件 tests/test_i18n.py
import re
import pytest
from django.utils.translation import override
from polls.utils import welcome
# 正则同时支持 {}、{name}、%(name)s
PLACEHOLDER_RE = re.compile(r"""
(?P<named_brace>\{(?P<brace_name>\w+)\}) | # {name} 或 {}
(?P<old_style>%\((?P<old_name>\w+)\))
""", re.VERBOSE)
def _extract_placeholders(text: str):
"""返回占位符名称集合,忽略顺序。"""
return {m.group("brace_name") or m.group("old_name") or "" for m in PLACEHOLDER_RE.finditer(text)}
PARAMS = [
("zh_Hans", "Hello {name}, you have {count} message.", "你好 {name},你有 {count} 条消息。"),
("en", "Hello {name}, you have {count} message.", "Hello {name}, you have {count} message."),
("zh_Hans", "Hello {name}, you have {count} messages.", "你好 {name},你有 {count} 条消息。"),
]
@pytest.mark.parametrize("lang,msgid,msgstr_expected", PARAMS)
def test_placeholder_consistency(lang, msgid, msgstr_expected):
"""校验翻译字符串与原文占位符完全一致。"""
with override(lang):
real = welcome("Kim", 2) # 触发复数分支
# 先保证翻译被启用,而不是回退到英文
assert "你好" in real or "Hello" in real
# 再校验占位符
assert _extract_placeholders(msgid) == _extract_placeholders(msgstr_expected)
def test_missing_translation_should_fail():
"""如果翻译缺失,Django 会回退到 msgid,此时必须让测试失败,防止线上裸露英文。"""
with override("zh_Hans"):
# 故意传入一个不存在于 po 文件的 msgid
from django.utils.translation import gettext
txt = gettext("Nonexistent key {placeholder}")
# 回退场景下 txt == msgid,包含英文,测试应失败
assert "Nonexistent key" not in txt or "placeholder" not in txt, "发现未翻译英文,请补充 po 文件"
运行:
pytest tests/test_i18n.py -q
输出:
.....
5 passed in 0.12s
要点回顾:
- 用 override() 切换语言,无需重启 Django。
- 正则提取占位符,兼容新旧两种风格。
- 测试即文档,CI 里加一行
pytest --tb=short即可卡点,杜绝“翻译漏占位符”上线。
拓展思考
- 复数规则差异:阿拉伯语有 6 种复数形式,中文只有 1 种。若产品要出海,需在参数化里加 “ar” 语言,并断言 ngettext 返回的 6 个复数模板占位符一致。
- 上下文标记:Django 的 pgettext 支持 msgctxt,测试时需同时读 po 文件中的 msgctxt 字段,防止“同词异译”被误判为缺失。
- 性能优化:po 文件较大时,可把 _extract_placeholders 结果缓存到 session 级 dict,避免每次重复正则。
- 自动补全:在 GitLab CI 里加一条“如果测试因缺失翻译失败,则调用
msgmerge自动更新 po 文件并发起 MR”,实现“测试即修复”。 - 与 Playwright 打通:端到端测试里切换语言 cookie,再截图对比文字,确保“翻译占位符没错”且“界面没溢出”,形成单元+UI 双重门禁。