From 1c63e4c16a608a744b649d74b2ce53197c6463bb Mon Sep 17 00:00:00 2001 From: Matt Pegler Date: Fri, 19 Nov 2021 14:05:10 -0800 Subject: [PATCH] fix ignoring packages that are imported after freezing fixes #420 --- freezegun/api.py | 17 ++++++++++++++--- tests/another_module.py | 15 +++++++++++++++ tests/test_class_import.py | 18 ++++++++++++++++++ 3 files changed, 47 insertions(+), 3 deletions(-) diff --git a/freezegun/api.py b/freezegun/api.py index 81d4da17..85eb8293 100644 --- a/freezegun/api.py +++ b/freezegun/api.py @@ -322,7 +322,11 @@ def __sub__(self, other): @classmethod def today(cls): - result = cls._date_to_freeze() + cls._tz_offset() + if _should_use_real_time(): + result = real_date.today() + else: + result = cls._date_to_freeze() + cls._tz_offset() + return date_to_fakedate(result) @staticmethod @@ -383,7 +387,11 @@ def timestamp(self): @classmethod def now(cls, tz=None): - now = cls._time_to_freeze() or real_datetime.now() + if _should_use_real_time(): + now = real_datetime.now() + else: + now = cls._time_to_freeze() or real_datetime.now() + if tz: result = tz.fromutc(now.replace(tzinfo=tz)) + cls._tz_offset() else: @@ -407,7 +415,10 @@ def today(cls): @classmethod def utcnow(cls): - result = cls._time_to_freeze() or real_datetime.utcnow() + if _should_use_real_time(): + result = real_datetime.utcnow() + else: + result = cls._time_to_freeze() or real_datetime.now() return datetime_to_fakedatetime(result) @staticmethod diff --git a/tests/another_module.py b/tests/another_module.py index 637c889b..fc4a119b 100644 --- a/tests/another_module.py +++ b/tests/another_module.py @@ -61,3 +61,18 @@ def get_fake_gmtime(): def get_fake_strftime(): return fake_strftime + + +# Getters + + +def get_datetime_now(): + return datetime.now() + + +def get_datetime_utcnow(): + return datetime.utcnow() + + +def get_date_today(): + return date.today() \ No newline at end of file diff --git a/tests/test_class_import.py b/tests/test_class_import.py index 709dc6e1..643613c8 100644 --- a/tests/test_class_import.py +++ b/tests/test_class_import.py @@ -180,6 +180,24 @@ def test_import_after_start(): assert another_module.get_fake_strftime() is fake_strftime del sys.modules['tests.another_module'] + +def test_ignore_import_after_start(): + with freeze_time("2012-01-14", ignore=["tests.another_module"]): + assert "tests.another_module" not in sys.modules.keys() + from tests import another_module + + utcnow = another_module.get_datetime_utcnow() + assert utcnow != FakeDatetime(2012, 1, 14) + + now = another_module.get_datetime_now() + assert now != FakeDatetime(2012, 1, 14) + + today = another_module.get_date_today() + assert today != FakeDate(2012, 1, 14) + + del sys.modules["tests.another_module"] + + def test_none_as_initial(): with freeze_time() as ft: ft.move_to('2012-01-14')