diff --git a/src/humanize/i18n.py b/src/humanize/i18n.py index 42447b0..dd94c7a 100644 --- a/src/humanize/i18n.py +++ b/src/humanize/i18n.py @@ -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: @@ -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() diff --git a/tests/test_i18n.py b/tests/test_i18n.py index f3721c9..83eecc8 100644 --- a/tests/test_i18n.py +++ b/tests/test_i18n.py @@ -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") @@ -198,3 +198,35 @@ def test_default_locale_path_undefined__spec__( 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") + + finally: + humanize.i18n.deactivate() + + assert test_str == humanize.naturaltime(three_seconds)