From b8d2ea25d35d2d94e901e6b07eff9ec88a7e0bd4 Mon Sep 17 00:00:00 2001 From: Aarni Koskela Date: Sun, 29 Nov 2026 14:47:44 +0200 Subject: [PATCH] Replace freezegun dependency with a small custom context manager --- .pre-commit-config.yaml | 2 +- pyproject.toml | 1 - tests/conftest.py | 5 +- tests/freeze_time.py | 64 +++++++++++++++++++++++++ tests/messages/frontend/test_cli.py | 25 +++++----- tests/messages/frontend/test_concat.py | 2 +- tests/messages/frontend/test_extract.py | 14 +++--- tests/messages/frontend/test_merge.py | 2 +- tests/test_dates.py | 6 +-- 9 files changed, 91 insertions(+), 30 deletions(-) create mode 100644 tests/freeze_time.py diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 85a150744..a49eabd82 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -19,6 +19,6 @@ repos: exclude: (tests/messages/data/) - id: name-tests-test args: [ '--django' ] - exclude: (tests/benchmarks|tests/messages/data/|.*(consts|utils).py) + exclude: (tests/benchmarks|tests/messages/data/|.*(consts|utils|freeze_time).py) - id: requirements-txt-fixer - id: trailing-whitespace diff --git a/pyproject.toml b/pyproject.toml index a5453c6d1..6e45f90d3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -40,7 +40,6 @@ classifiers = [ [project.optional-dependencies] # TODO: use a `dev` dependency group instead dev = [ - "freezegun~=1.0", "jinja2>=3.0", "pytest-cov", "pytest>=6.0", diff --git a/tests/conftest.py b/tests/conftest.py index e1819fffa..85dfcb0a2 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -2,7 +2,8 @@ import zoneinfo import pytest -from freezegun import freeze_time + +from tests.freeze_time import freeze_time try: import pytz @@ -40,4 +41,4 @@ def timezone_getter(request): @pytest.fixture def frozen_time() -> datetime.datetime: with freeze_time(FROZEN_DATETIME) as frozen: - yield frozen.time_to_freeze + yield frozen diff --git a/tests/freeze_time.py b/tests/freeze_time.py new file mode 100644 index 000000000..0b101339a --- /dev/null +++ b/tests/freeze_time.py @@ -0,0 +1,64 @@ +""" +Freeze the datetime module enough for Babel's tests. + +Inspired by `freezegun`, but minimal and self-contained. + +Note that `from datetime import ...` style imports are understandably not supported. +Babel currently doesn't do those, and it shouldn't, either. +""" + +from __future__ import annotations + +import contextlib +import datetime +from collections.abc import Iterator +from unittest import mock + +_frozen: datetime.datetime # naive, UTC + + +class _IsInstanceOfBase(type): + # Make `isinstance(real_datetime_obj, datetime.datetime)` still work while patched. + def __instancecheck__(cls, obj) -> bool: + return isinstance(obj, cls.__base__) + + +class _FrozenDatetime(datetime.datetime, metaclass=_IsInstanceOfBase): + @classmethod + def now(cls, tz=None): + if tz is None: + return _frozen + return _frozen.replace(tzinfo=datetime.timezone.utc).astimezone(tz) + + +class _FrozenDate(datetime.date, metaclass=_IsInstanceOfBase): + @classmethod + def today(cls): + return _frozen.date() + + +class _FrozenTime(datetime.time, metaclass=_IsInstanceOfBase): + @classmethod + def now(cls, tz=None): + if tz is None: + return _frozen.time() + return _frozen.replace(tzinfo=datetime.timezone.utc).astimezone(tz).time() + + +@contextlib.contextmanager +def freeze_time(time_to_freeze: str | datetime.datetime) -> Iterator[datetime.datetime]: + """ + Freeze "now" to the given naive UTC datetime or ISO 8601 string. + + Yields the frozen datetime. + """ + global _frozen + if isinstance(time_to_freeze, str): + time_to_freeze = datetime.datetime.fromisoformat(time_to_freeze) + _frozen = time_to_freeze + with ( + mock.patch.object(datetime, "datetime", _FrozenDatetime), + mock.patch.object(datetime, "date", _FrozenDate), + mock.patch.object(datetime, "time", _FrozenTime), + ): + yield _frozen diff --git a/tests/messages/frontend/test_cli.py b/tests/messages/frontend/test_cli.py index 22d7dfcc4..561088949 100644 --- a/tests/messages/frontend/test_cli.py +++ b/tests/messages/frontend/test_cli.py @@ -17,7 +17,6 @@ import pathlib import shutil import sys -import time from datetime import datetime, timedelta from io import StringIO @@ -122,7 +121,7 @@ def test_help(cli): assert all(command in content for command in ('init', 'update', 'compile', 'extract')) -def test_extract_with_default_mapping(formatted_frozen_time, cli, pot_file): +def test_extract_with_default_mapping(frozen_time, formatted_frozen_time, cli, pot_file): cli.run([ 'pybabel', 'extract', @@ -135,10 +134,10 @@ def test_extract_with_default_mapping(formatted_frozen_time, cli, pot_file): '-o', pot_file, 'project', ]) # fmt: skip expected_content = rf"""# Translations template for TestProject. -# Copyright (C) {time.strftime('%Y')} FooBar, Inc. +# Copyright (C) {frozen_time.year} FooBar, Inc. # This file is distributed under the same license as the TestProject # project. -# FIRST AUTHOR , {time.strftime('%Y')}. +# FIRST AUTHOR , {frozen_time.year}. # #, fuzzy msgid "" @@ -182,7 +181,7 @@ def formatted_frozen_time(frozen_time) -> str: return format_datetime(frozen_time, 'yyyy-MM-dd HH:mmZ', tzinfo=LOCALTZ, locale='en') -def test_extract_with_mapping_file(formatted_frozen_time, cli, pot_file): +def test_extract_with_mapping_file(frozen_time, formatted_frozen_time, cli, pot_file): cli.run([ 'pybabel', 'extract', @@ -196,10 +195,10 @@ def test_extract_with_mapping_file(formatted_frozen_time, cli, pot_file): '-o', pot_file, 'project', ]) # fmt: skip expected_content = rf"""# Translations template for TestProject. -# Copyright (C) {time.strftime('%Y')} FooBar, Inc. +# Copyright (C) {frozen_time.year} FooBar, Inc. # This file is distributed under the same license as the TestProject # project. -# FIRST AUTHOR , {time.strftime('%Y')}. +# FIRST AUTHOR , {frozen_time.year}. # #, fuzzy msgid "" @@ -232,7 +231,7 @@ def test_extract_with_mapping_file(formatted_frozen_time, cli, pot_file): def test_extract_with_mapping_file_from_pyproject_toml_config( - formatted_frozen_time, cli, pot_file, pyproject_toml_file, + frozen_time, formatted_frozen_time, cli, pot_file, pyproject_toml_file, ): """ Test the same as ``test_extract_with_mapping_file()`` but with ``pyproject.toml`` @@ -251,10 +250,10 @@ def test_extract_with_mapping_file_from_pyproject_toml_config( cli.run(['pybabel', 'extract', 'project']) expected_content = rf"""# Translations template for TestProject. -# Copyright (C) {time.strftime('%Y')} FooBar, Inc. +# Copyright (C) {frozen_time.year} FooBar, Inc. # This file is distributed under the same license as the TestProject # project. -# FIRST AUTHOR , {time.strftime('%Y')}. +# FIRST AUTHOR , {frozen_time.year}. # #, fuzzy msgid "" @@ -303,7 +302,7 @@ def test_extract_with_mapping_file_from_pyproject_toml_config( assert expected_content == pot_file.read_text() -def test_extract_with_exact_file(formatted_frozen_time, cli, pot_file): +def test_extract_with_exact_file(frozen_time, formatted_frozen_time, cli, pot_file): """Tests that we can call extract with a particular file and only strings from that file get extracted. (Note the absence of strings from file1.py) """ @@ -321,10 +320,10 @@ def test_extract_with_exact_file(formatted_frozen_time, cli, pot_file): '-o', pot_file, file_to_extract, ]) # fmt: skip expected_content = rf"""# Translations template for TestProject. -# Copyright (C) {time.strftime('%Y')} FooBar, Inc. +# Copyright (C) {frozen_time.year} FooBar, Inc. # This file is distributed under the same license as the TestProject # project. -# FIRST AUTHOR , {time.strftime('%Y')}. +# FIRST AUTHOR , {frozen_time.year}. # #, fuzzy msgid "" diff --git a/tests/messages/frontend/test_concat.py b/tests/messages/frontend/test_concat.py index e55fbc175..25c3f82d1 100644 --- a/tests/messages/frontend/test_concat.py +++ b/tests/messages/frontend/test_concat.py @@ -17,10 +17,10 @@ import sys import pytest -from freezegun import freeze_time from babel.messages import Catalog, frontend, pofile from babel.messages.frontend import OptionError +from tests.freeze_time import freeze_time from tests.messages.consts import TEST_PROJECT_DISTRIBUTION_DATA from tests.messages.utils import Distribution, run_command, write_po_file diff --git a/tests/messages/frontend/test_extract.py b/tests/messages/frontend/test_extract.py index a6dfe33bf..22d022e23 100644 --- a/tests/messages/frontend/test_extract.py +++ b/tests/messages/frontend/test_extract.py @@ -12,8 +12,6 @@ from __future__ import annotations -import time - import pytest from babel import __version__ as VERSION @@ -109,10 +107,10 @@ def test_extraction_with_default_mapping(frozen_time, extract_cmd, pot_file): date = format_datetime(frozen_time, 'yyyy-MM-dd HH:mmZ', tzinfo=LOCALTZ, locale='en') expected_content = rf"""# Translations template for TestProject. -# Copyright (C) {time.strftime('%Y')} FooBar, Inc. +# Copyright (C) {frozen_time.year} FooBar, Inc. # This file is distributed under the same license as the TestProject # project. -# FIRST AUTHOR , {time.strftime('%Y')}. +# FIRST AUTHOR , {frozen_time.year}. # #, fuzzy msgid "" @@ -162,10 +160,10 @@ def test_extraction_with_mapping_file(frozen_time, extract_cmd, pot_file): date = format_datetime(frozen_time, 'yyyy-MM-dd HH:mmZ', tzinfo=LOCALTZ, locale='en') expected_content = rf"""# Translations template for TestProject. -# Copyright (C) {time.strftime('%Y')} FooBar, Inc. +# Copyright (C) {frozen_time.year} FooBar, Inc. # This file is distributed under the same license as the TestProject # project. -# FIRST AUTHOR , {time.strftime('%Y')}. +# FIRST AUTHOR , {frozen_time.year}. # #, fuzzy msgid "" @@ -215,10 +213,10 @@ def test_extraction_with_mapping_dict(frozen_time, extract_cmd, pot_file, ignore date = format_datetime(frozen_time, 'yyyy-MM-dd HH:mmZ', tzinfo=LOCALTZ, locale='en') expected_content = rf"""# Translations template for TestProject. -# Copyright (C) {time.strftime('%Y')} FooBar, Inc. +# Copyright (C) {frozen_time.year} FooBar, Inc. # This file is distributed under the same license as the TestProject # project. -# FIRST AUTHOR , {time.strftime('%Y')}. +# FIRST AUTHOR , {frozen_time.year}. # #, fuzzy msgid "" diff --git a/tests/messages/frontend/test_merge.py b/tests/messages/frontend/test_merge.py index 61c98f150..378435e40 100644 --- a/tests/messages/frontend/test_merge.py +++ b/tests/messages/frontend/test_merge.py @@ -17,10 +17,10 @@ import sys import pytest -from freezegun import freeze_time from babel.messages import Catalog, frontend, pofile from babel.messages.frontend import OptionError +from tests.freeze_time import freeze_time from tests.messages.consts import TEST_PROJECT_DISTRIBUTION_DATA from tests.messages.utils import Distribution, run_command, write_po_file diff --git a/tests/test_dates.py b/tests/test_dates.py index e9b618ca1..a1a3dfdbb 100644 --- a/tests/test_dates.py +++ b/tests/test_dates.py @@ -13,12 +13,12 @@ import calendar from datetime import date, datetime, time, timedelta -import freezegun import pytest from babel import Locale, dates from babel.dates import NO_INHERITANCE_MARKER, UTC, _localize, parse_pattern from babel.util import FixedOffsetTimezone +from tests.freeze_time import freeze_time def test_format_date_with_time_fields_in_pattern(): @@ -669,7 +669,7 @@ def test_format_time(timezone_getter): custom = dates.format_time(t, "hh 'o''clock' a, zzzz", tzinfo=eastern, locale='en') assert custom == "09 o'clock AM, Eastern Daylight Time" - with freezegun.freeze_time("2023-01-01"): + with freeze_time("2023-01-01"): t = time(15, 30) paris = dates.format_time(t, format='full', tzinfo=paris, locale='fr_FR') assert paris == '15:30:00 heure normale d’Europe centrale' @@ -737,7 +737,7 @@ def test_parse_date(): ('2090-06-01', '11', 2011), ]) def test_parse_date_two_digit_year(today, yy, expected): - with freezegun.freeze_time(today): + with freeze_time(today): assert dates.parse_date(f'1/1/{yy}', locale='en_US').year == expected