Skip to content

Commit b06baf0

Browse files
author
Daniel Gillet
committed
Refactor test_i18n to use NOW as a fixture
The global variable NOW came with a gotcha. When using it, it was also needed to decorate the test with freeze_time. NOW is now a fixture which keeps the time frozen for the duration of the test using it.
1 parent f7dcb08 commit b06baf0

1 file changed

Lines changed: 20 additions & 9 deletions

File tree

tests/test_i18n.py

Lines changed: 20 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,18 +4,32 @@
44

55
import datetime as dt
66
import importlib
7+
from collections.abc import Generator
78

89
import pytest
910
from freezegun import freeze_time
1011

1112
import humanize
1213

13-
with freeze_time("2020-02-02"):
14-
NOW = dt.datetime.now()
1514

15+
@pytest.fixture
16+
def NOW() -> Generator[dt.datetime, None, None]:
17+
"""
18+
Using this fixture will give you a datetime frozen in 2020-02-02 00:00:00+00:00
1619
17-
@freeze_time("2020-02-02")
18-
def test_i18n() -> None:
20+
In a test using this fixture, further calls to datetime.now() or date.today() would
21+
return also a frozen date / datetime in 2020-02-02.
22+
23+
Yields:
24+
Generator[datetime, None, None]: UTC aware datetime 2020-02-02 00:00:00+00:00
25+
"""
26+
with freeze_time("2020-02-02"):
27+
# TODO: Python 3.11+: replace dt.timezone.utc with dt.UTC
28+
NOW = dt.datetime.now(tz=dt.timezone.utc)
29+
yield NOW
30+
31+
32+
def test_i18n(NOW: dt.datetime) -> None:
1933
three_seconds = NOW - dt.timedelta(seconds=3)
2034
one_min_three_seconds = dt.timedelta(milliseconds=67_000)
2135

@@ -199,8 +213,7 @@ def test_default_locale_path_undefined__spec__(
199213
i18n.activate("ru_RU")
200214
assert str(excinfo.value) == self.expected_msg
201215

202-
@freeze_time("2020-02-02")
203-
def test_en_locale(self) -> None:
216+
def test_en_locale(self, NOW: dt.datetime) -> None:
204217
three_seconds = NOW - dt.timedelta(seconds=3)
205218
test_str = humanize.naturaltime(three_seconds)
206219

@@ -212,10 +225,8 @@ def test_en_locale(self) -> None:
212225

213226
humanize.i18n.deactivate()
214227

215-
@freeze_time("2020-02-02")
216-
def test_None_locale(self) -> None:
228+
def test_None_locale(self, NOW: dt.datetime) -> None:
217229
three_seconds = NOW - dt.timedelta(seconds=3)
218-
test_str = humanize.naturaltime(three_seconds)
219230

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

0 commit comments

Comments
 (0)