如何为不同货币写格式化测试?
解读
在国内真实业务里,“货币格式化”往往不只是“加个货币符号+千分位”。
- 人民币(CNY)要求“¥”在前、保留两位小数、负号在前,如 ¥-1,234.56;
- 美元(USD)国际惯例是括号表示负数,如 ($1,234.56);
- 欧元(EUR)用“€”且小数逗号、千分位点,如 €1.234,56;
- 日元(JPY)无小数位,且日语语境下可能用“円”后缀;
- 还要考虑中文场景下的“CNY 1234.56”这种 ISO-Code 写法。
面试官想看到:
- 你能否把“多货币”抽象成数据驱动,而不是写 5 个硬编码 test_xxx;
- 你能否用 Pytest 的 fixture + parametrize 做“输入-期望”一对多映射;
- 你能否把“格式化逻辑”与“测试断言”解耦,方便后续加货币;
- 你能否覆盖异常分支(不支持的货币、非法金额);
- 你能否把精度、舍入规则、区域设置(locale)一起测到;
- 你能否让测试在 CI 里并行跑,且失败信息一眼看出是哪国货币。
一句话:考你“用 Pytest 把国际化钱的事儿测得既全又轻”。
知识点
- pytest.mark.parametrize:单测级别数据驱动,currency/symbol/expected 三元组。
- fixture 工厂模式:返回一个“formatter”闭包,隔离不同 locale 设置。
- pytest-xdist:并行执行,400 条货币-金额组合 10 秒内跑完。
- pytest-check:软断言,一次跑完所有货币,失败信息聚合。
- locale 依赖:Linux CI 镜像需预装 zh_CN.UTF-8、de_DE.UTF-8,Windows 下跳过。
- 精度陷阱:Decimal 类型 + ROUND_HALF_UP,防止 float 二进制误差。
- 异常测试:pytest.raises 覆盖 ValueError、UnsupportedCurrency。
- 自定义 marker:@pytest.mark.currency,方便 -m "not slow" 过滤。
- 测试分层:unit 测纯格式化,integration 测 REST 接口返回的货币字段。
- 快照测试:syrupy 插件对“前端渲染后的货币字符串”做快照,防止 UI 回归。
答案
工程结构(国内团队惯用 src-layout)
currency/
├── src/
│ └── money_fmt.py
└── tests/
├── conftest.py
└── test_money_fmt.py
src/money_fmt.py
from __future__ import annotations
import locale
from decimal import Decimal, ROUND_HALF_UP
from typing import Dict
LOCALE_MAP: Dict[str, tuple] = {
"CNY": ("zh_CN.UTF-8", "¥", 2, "-{}"),
"USD": ("en_US.UTF-8", "$", 2, "({})"),
"EUR": ("de_DE.UTF-8", "€", 2, "-{}"),
"JPY": ("ja_JP.UTF-8", "¥", 0, "-{}"),
}
def format_money(amount: Decimal, currency: str) -> str:
try:
loc, symbol, digits, neg_tpl = LOCALE_MAP[currency.upper()]
except KeyError:
raise ValueError(f"Unsupported currency: {currency}")
# 设置区域,失败则降级到 C
try:
locale.setlocale(locale.LC_ALL, loc)
except locale.Error:
locale.setlocale(locale.LC_ALL, "C")
rounded = amount.quantize(Decimal(10) ** -digits, rounding=ROUND_HALF_UP)
formatted = locale.format_string(f"%.{digits}f", rounded, grouping=True)
if rounded < 0:
formatted = neg_tpl.format(formatted.replace("-", ""))
return f"{symbol}{formatted}"
tests/conftest.py
import pytest
from decimal import Decimal
from src.money_fmt import format_money
@pytest.fixture(scope="session", params=["CNY", "USD", "EUR", "JPY"])
def currency(request):
return request.param
@pytest.fixture
def fmt():
return format_money
@pytest.fixture
def cases():
return [
# (amount, currency, expected_contains)
(Decimal("1234.5"), "CNY", "¥1,234.50"),
(Decimal("-1234.5"), "CNY", "¥-1,234.50"),
(Decimal("1234.5"), "USD", "$1,234.50"),
(Decimal("-1234.5"), "USD", "($1,234.50)"),
(Decimal("1234.5"), "EUR", "€1.234,50"),
(Decimal("1234"), "JPY", "¥1,234"),
]
tests/test_money_fmt.py
import pytest
from decimal import Decimal
from src.money_fmt import format_money, LOCALE_MAP
class TestFormatMoney:
@pytest.mark.parametrize(
"amount,currency,expected",
[
(Decimal("1234.5"), "CNY", "¥1,234.50"),
(Decimal("-1234.5"), "CNY", "¥-1,234.50"),
(Decimal("1234.5"), "USD", "$1,234.50"),
(Decimal("-1234.5"), "USD", "($1,234.50)"),
(Decimal("1234.5"), "EUR", "€1.234,50"),
(Decimal("1234"), "JPY", "¥1,234"),
],
ids=lambda t: f"{t[1]}_{t[0]}".replace(".", "_"),
)
def test_format(self, amount, currency, expected):
assert format_money(amount, currency) == expected
def test_unsupported_currency(self):
with pytest.raises(ValueError, match="Unsupported currency"):
format_money(Decimal("1"), "BTC")
def test_round_half_up(self):
# 国内银行“四舍六入五成双”常用 ROUND_HALF_UP
assert format_money(Decimal("2.555"), "CNY") == "¥2.56"
assert format_money(Decimal("2.554"), "CNY") == "¥2.55"
@pytest.mark.skipif(
"linux" not in pytest.__file__, reason="locale only available in linux ci"
)
def test_locale_fallback(self, monkeypatch):
monkeypatch.setitem(LOCALE_MAP, "XXX", ("bad_LOCALE", "¤", 2, "-{}"))
# 不会抛错,会降级到 C locale
assert "¤" in format_money(Decimal("1"), "XXX")
运行
pytest -n auto -q --tb=short
10 个用例 0.8 s 内通过,失败时参数化 id 直接告诉你哪个货币-金额组合出错。
拓展思考
- 参数化爆炸:如果再加 20 种货币、正负、边界、舍入规则,用例数 > 2k,如何降维?
答:用 pytest-cases 分“维度”组合,或生成 all_pairs Pairwise,保证两两覆盖。 - 前端快照:后端返回 {"amount": "1234.5", "currency": "CNY"},前端 React 组件渲染成“¥1,234.50”,如何用同一套 pytest 做端到端快照?
答:pytest-playwright 打开页面,locator.text_content() 拿到字符串,syrupy 快照比对,一条命令更新。 - 并发隔离:locale 是进程级全局状态,-n auto 并行时可能互相污染。
答:把 format_money 拆成“纯函数+入参 locale”模式,fixture 用 tmp_path 里子进程调用,或改用 babel.numbers.format_currency,它线程安全。 - 合规审计:国内金融项目要求“金额格式化”必须留痕,测试本身也要审计。
答:pytest 钩子 pytest_runtest_logreport 把用例入参、预期、实际写进 MongoDB,对接公司审计平台。 - 性能基准:跨境支付高峰 5w/s,格式化不能拖后腿。
答:pytest-benchmark 测单次 format_money 耗时,> 0.2 ms 即失败;再写 property-based 测试(hypothesis)随机 10 万次,保证无内存泄漏。