Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions tests/test_i18n.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@
import importlib
import shutil
import subprocess
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from threading import Event

import pytest
from freezegun import freeze_time
Expand Down Expand Up @@ -458,6 +460,46 @@ def test_none_locale(self) -> None:
assert test_str == humanize.naturaltime(three_seconds)


def test_locale_is_thread_local(monkeypatch: pytest.MonkeyPatch) -> None:
german = gettext.NullTranslations()
french = gettext.NullTranslations()
monkeypatch.setitem(humanize.i18n._TRANSLATIONS, "de_DE", german)
monkeypatch.setitem(humanize.i18n._TRANSLATIONS, "fr_FR", french)
ready = Event()
proceed = Event()

def worker() -> None:
try:
# A new thread starts with the default locale, not its parent's locale.
assert humanize.i18n.get_translation() is humanize.i18n._TRANSLATIONS[None]
assert humanize.intcomma(1234.5) == "1,234.5"
humanize.activate("fr_FR")
ready.set()
assert proceed.wait(timeout=5)
# Deactivation in the main thread must not reset this thread.
assert humanize.i18n.get_translation() is french
assert humanize.intcomma(1234.5) == "1 234,5"
finally:
humanize.deactivate()
assert humanize.intcomma(1234.5) == "1,234.5"

try:
humanize.activate("de_DE")
with ThreadPoolExecutor(max_workers=1) as executor:
future = executor.submit(worker)
try:
assert ready.wait(timeout=5)
assert humanize.i18n.get_translation() is german
assert humanize.intcomma(1234.5) == "1.234,5"
humanize.deactivate()
finally:
proceed.set()
future.result(timeout=5)
assert humanize.intcomma(1234.5) == "1,234.5"
finally:
humanize.deactivate()


@pytest.mark.parametrize(
"locale", sorted(p.name for p in LOCALE_DIR.iterdir() if p.is_dir())
)
Expand Down