| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import datetime |
| 4 |
import io |
| 5 |
|
| 6 |
import pytest |
| 7 |
|
| 8 |
from babel.support import Format, LazyProxy, Translations |
| 9 |
from tests.benchmarks.helpers import build_catalog, dump_mo |
| 10 |
|
| 11 |
|
| 12 |
@pytest.fixture() |
| 13 |
def translations() -> Translations: |
| 14 |
return Translations(fp=io.BytesIO(dump_mo(build_catalog(20)))) |
| 15 |
|
| 16 |
|
| 17 |
def _greeting(name: str) -> str: |
| 18 |
return f"Hei, {name}!" |
| 19 |
|
| 20 |
|
| 21 |
def test_format_decimal(benchmark): |
| 22 |
fmt = Format("fi") |
| 23 |
assert benchmark(lambda: fmt.decimal(1234567.891)) == "1\xa0234\xa0567,891" |
| 24 |
|
| 25 |
|
| 26 |
def test_format_date(benchmark): |
| 27 |
fmt = Format("fi") |
| 28 |
d = datetime.date(2025, 10, 15) |
| 29 |
assert benchmark(lambda: fmt.date(d, "long")) == "15. lokakuuta 2025" |
| 30 |
|
| 31 |
|
| 32 |
def test_lazy_proxy(benchmark): |
| 33 |
# Cache disabled so every access re-evaluates the wrapped function. |
| 34 |
proxy = LazyProxy(_greeting, "maailma", enable_cache=False) |
| 35 |
assert benchmark(lambda: f"{proxy} {proxy.upper()}") == "Hei, maailma! HEI, MAAILMA!" |
| 36 |
|
| 37 |
|
| 38 |
def test_translations_gettext(benchmark, translations: Translations): |
| 39 |
# ugettext is an alias of gettext on Translations, so it measures the same path. |
| 40 |
assert benchmark(lambda: translations.gettext("Message number 19")) == "Viesti numero 19" |
| 41 |
|
| 42 |
|
| 43 |
def test_translations_ngettext(benchmark, translations: Translations): |
| 44 |
assert benchmark(lambda: translations.ngettext("10 apple", "10 apples", 3)) == "10 omenaa" |