Use freezegun in DST tests (#58939)

This commit is contained in:
Erik Montnemery 2021-11-02 18:11:39 +01:00 committed by GitHub
parent 2df1ba2346
commit 30f7bc0f18
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 166 additions and 162 deletions

View file

@ -9,6 +9,7 @@ import threading
from unittest.mock import MagicMock, patch
from aiohttp.test_utils import make_mocked_request
import freezegun
import multidict
import pytest
import pytest_socket
@ -63,15 +64,24 @@ def pytest_configure(config):
def pytest_runtest_setup():
"""Throw if tests attempt to open sockets.
"""Prepare pytest_socket and freezegun.
pytest_socket:
Throw if tests attempt to open sockets.
allow_unix_socket is set to True because it's needed by asyncio.
Important: socket_allow_hosts must be called before disable_socket, otherwise all
destinations will be allowed.
freezegun:
Modified to include https://github.com/spulec/freezegun/pull/424
"""
pytest_socket.socket_allow_hosts(["127.0.0.1"])
disable_socket(allow_unix_socket=True)
freezegun.api.datetime_to_fakedatetime = ha_datetime_to_fakedatetime
freezegun.api.FakeDatetime = HAFakeDatetime
@pytest.fixture
def socket_disabled(pytestconfig):
@ -126,6 +136,43 @@ def disable_socket(allow_unix_socket=False):
socket.socket = GuardedSocket
def ha_datetime_to_fakedatetime(datetime):
"""Convert datetime to FakeDatetime.
Modified to include https://github.com/spulec/freezegun/pull/424.
"""
return freezegun.api.FakeDatetime(
datetime.year,
datetime.month,
datetime.day,
datetime.hour,
datetime.minute,
datetime.second,
datetime.microsecond,
datetime.tzinfo,
fold=datetime.fold,
)
class HAFakeDatetime(freezegun.api.FakeDatetime):
"""Modified to include https://github.com/spulec/freezegun/pull/424."""
@classmethod
def now(cls, tz=None):
"""Return frozen now."""
now = cls._time_to_freeze() or freezegun.api.real_datetime.now()
if tz:
result = tz.fromutc(now.replace(tzinfo=tz))
else:
result = now
# Add the _tz_offset only if it's non-zero to preserve fold
if cls._tz_offset():
result += cls._tz_offset()
return ha_datetime_to_fakedatetime(result)
def check_real(func):
"""Force a function to require a keyword _test_real to be passed in."""