Skip to content
9 changes: 7 additions & 2 deletions src/humanize/i18n.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,14 +55,15 @@ def get_translation() -> gettext_module.NullTranslations:


def activate(
locale: str, path: str | os.PathLike[str] | None = None
locale: str | None, path: str | os.PathLike[str] | None = None
) -> gettext_module.NullTranslations:
"""Activate internationalisation.

Set `locale` as current locale. Search for locale in directory `path`.

Args:
locale (str): Language name, e.g. `en_GB`.
locale (str | None): Language name, e.g. `en_GB`. If `None`, defaults to no
transaltion. Similar to calling ``deactivate()``.
path (str | pathlib.Path): Path to search for locales.

Returns:
Expand All @@ -71,6 +72,10 @@ def activate(
Raises:
Exception: If humanize cannot find the locale folder.
"""
if locale is None or locale.startswith("en"):
_CURRENT.locale = None
return _TRANSLATIONS[None]

if path is None:
path = _get_default_locale_path()

Expand Down
34 changes: 33 additions & 1 deletion tests/test_i18n.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
import humanize

with freeze_time("2020-02-02"):
NOW = dt.datetime.now()
NOW = dt.datetime.now(tz=dt.timezone.utc)


@freeze_time("2020-02-02")
Expand Down Expand Up @@ -198,3 +198,35 @@
with pytest.raises(Exception) as excinfo:
i18n.activate("ru_RU")
assert str(excinfo.value) == self.expected_msg

@freeze_time("2020-02-02")
def test_en_locale(self) -> None:
three_seconds = NOW - dt.timedelta(seconds=3)
test_str = humanize.naturaltime(three_seconds)

humanize.i18n.activate("en_US")
assert test_str == humanize.naturaltime(three_seconds)

humanize.i18n.activate("en_GB")
assert test_str == humanize.naturaltime(three_seconds)

humanize.i18n.deactivate()

@freeze_time("2020-02-02")
def test_none_locale(self) -> None:
three_seconds = NOW - dt.timedelta(seconds=3)

try:
humanize.i18n.activate("fr")
assert humanize.naturaltime(three_seconds) == "il y a 3 secondes"

humanize.i18n.activate(None)
test_str = humanize.naturaltime(three_seconds)
assert test_str == "3 seconds ago"
except FileNotFoundError:
pytest.skip("Generate .mo with scripts/generate-translation-binaries.sh")

Check warning on line 227 in tests/test_i18n.py

View check run for this annotation

Codecov / codecov/patch

tests/test_i18n.py#L226-L227

Added lines #L226 - L227 were not covered by tests

finally:
humanize.i18n.deactivate()

assert test_str == humanize.naturaltime(three_seconds)
Loading