Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
1 change: 0 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
5 changes: 3 additions & 2 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
import zoneinfo

import pytest
from freezegun import freeze_time

from tests.freeze_time import freeze_time

try:
import pytz
Expand Down Expand Up @@ -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
64 changes: 64 additions & 0 deletions tests/freeze_time.py
Original file line number Diff line number Diff line change
@@ -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
25 changes: 12 additions & 13 deletions tests/messages/frontend/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
import pathlib
import shutil
import sys
import time
from datetime import datetime, timedelta
from io import StringIO

Expand Down Expand Up @@ -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',
Expand All @@ -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 <EMAIL@ADDRESS>, {time.strftime('%Y')}.
# FIRST AUTHOR <EMAIL@ADDRESS>, {frozen_time.year}.
#
#, fuzzy
msgid ""
Expand Down Expand Up @@ -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',
Expand All @@ -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 <EMAIL@ADDRESS>, {time.strftime('%Y')}.
# FIRST AUTHOR <EMAIL@ADDRESS>, {frozen_time.year}.
#
#, fuzzy
msgid ""
Expand Down Expand Up @@ -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``
Expand All @@ -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 <EMAIL@ADDRESS>, {time.strftime('%Y')}.
# FIRST AUTHOR <EMAIL@ADDRESS>, {frozen_time.year}.
#
#, fuzzy
msgid ""
Expand Down Expand Up @@ -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)
"""
Expand All @@ -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 <EMAIL@ADDRESS>, {time.strftime('%Y')}.
# FIRST AUTHOR <EMAIL@ADDRESS>, {frozen_time.year}.
#
#, fuzzy
msgid ""
Expand Down
2 changes: 1 addition & 1 deletion tests/messages/frontend/test_concat.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
14 changes: 6 additions & 8 deletions tests/messages/frontend/test_extract.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,6 @@

from __future__ import annotations

import time

import pytest

from babel import __version__ as VERSION
Expand Down Expand Up @@ -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 <EMAIL@ADDRESS>, {time.strftime('%Y')}.
# FIRST AUTHOR <EMAIL@ADDRESS>, {frozen_time.year}.
#
#, fuzzy
msgid ""
Expand Down Expand Up @@ -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 <EMAIL@ADDRESS>, {time.strftime('%Y')}.
# FIRST AUTHOR <EMAIL@ADDRESS>, {frozen_time.year}.
#
#, fuzzy
msgid ""
Expand Down Expand Up @@ -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 <EMAIL@ADDRESS>, {time.strftime('%Y')}.
# FIRST AUTHOR <EMAIL@ADDRESS>, {frozen_time.year}.
#
#, fuzzy
msgid ""
Expand Down
2 changes: 1 addition & 1 deletion tests/messages/frontend/test_merge.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
6 changes: 3 additions & 3 deletions tests/test_dates.py
Original file line number Diff line number Diff line change
Expand Up @@ -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():
Expand Down Expand Up @@ -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'
Expand Down Expand Up @@ -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


Expand Down
Loading