Skip to content

Commit 31acb37

Browse files
authored
Handle en_GB and en_US locale (#230)
2 parents de8b8a1 + 35562f8 commit 31acb37

File tree

2 files changed

+40
-3
lines changed

2 files changed

+40
-3
lines changed

src/humanize/i18n.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -55,14 +55,15 @@ def get_translation() -> gettext_module.NullTranslations:
5555

5656

5757
def activate(
58-
locale: str, path: str | os.PathLike[str] | None = None
58+
locale: str | None, path: str | os.PathLike[str] | None = None
5959
) -> gettext_module.NullTranslations:
6060
"""Activate internationalisation.
6161
6262
Set `locale` as current locale. Search for locale in directory `path`.
6363
6464
Args:
65-
locale (str): Language name, e.g. `en_GB`.
65+
locale (str | None): Language name, e.g. `en_GB`. If `None`, defaults to no
66+
transaltion. Similar to calling ``deactivate()``.
6667
path (str | pathlib.Path): Path to search for locales.
6768
6869
Returns:
@@ -71,6 +72,10 @@ def activate(
7172
Raises:
7273
Exception: If humanize cannot find the locale folder.
7374
"""
75+
if locale is None or locale.startswith("en"):
76+
_CURRENT.locale = None
77+
return _TRANSLATIONS[None]
78+
7479
if path is None:
7580
path = _get_default_locale_path()
7681

tests/test_i18n.py

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
import humanize
1212

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

1616

1717
@freeze_time("2020-02-02")
@@ -198,3 +198,35 @@ def test_default_locale_path_undefined__spec__(
198198
with pytest.raises(Exception) as excinfo:
199199
i18n.activate("ru_RU")
200200
assert str(excinfo.value) == self.expected_msg
201+
202+
@freeze_time("2020-02-02")
203+
def test_en_locale(self) -> None:
204+
three_seconds = NOW - dt.timedelta(seconds=3)
205+
test_str = humanize.naturaltime(three_seconds)
206+
207+
humanize.i18n.activate("en_US")
208+
assert test_str == humanize.naturaltime(three_seconds)
209+
210+
humanize.i18n.activate("en_GB")
211+
assert test_str == humanize.naturaltime(three_seconds)
212+
213+
humanize.i18n.deactivate()
214+
215+
@freeze_time("2020-02-02")
216+
def test_none_locale(self) -> None:
217+
three_seconds = NOW - dt.timedelta(seconds=3)
218+
219+
try:
220+
humanize.i18n.activate("fr")
221+
assert humanize.naturaltime(three_seconds) == "il y a 3 secondes"
222+
223+
humanize.i18n.activate(None)
224+
test_str = humanize.naturaltime(three_seconds)
225+
assert test_str == "3 seconds ago"
226+
except FileNotFoundError:
227+
pytest.skip("Generate .mo with scripts/generate-translation-binaries.sh")
228+
229+
finally:
230+
humanize.i18n.deactivate()
231+
232+
assert test_str == humanize.naturaltime(three_seconds)

0 commit comments

Comments
 (0)