如果您在测试中使用freezegun包,您可能需要进行更智能的 isinstance 检查,这与FakeDate和原始日期/日期时间在freeze_time上下文中运行良好:
def isinstance_date(value):
"""Safe replacement for isinstance date which works smoothly also with Mocked freezetime"""
import datetime
if isinstance(value, datetime.date) and not isinstance(value, datetime.datetime):
return True
elif type(datetime.datetime.today().date()) == type(value):
return True
else:
return False
def isinstance_datetime(value):
"""Safe replacement for isinstance datetime which works smoothly also with Mocked freezetime """
import datetime
if isinstance(value, datetime.datetime):
return True
elif type(datetime.datetime.now()) == type(value):
return True
else:
return False
和测试以验证实现
class TestDateUtils(TestCase):
def setUp(self):
self.date_orig = datetime.date(2000, 10, 10)
self.datetime_orig = datetime.datetime(2000, 10, 10)
with freeze_time('2001-01-01'):
self.date_freezed = datetime.date(2002, 10, 10)
self.datetime_freezed = datetime.datetime(2002, 10, 10)
def test_isinstance_date(self):
def check():
self.assertTrue(isinstance_date(self.date_orig))
self.assertTrue(isinstance_date(self.date_freezed))
self.assertFalse(isinstance_date(self.datetime_orig))
self.assertFalse(isinstance_date(self.datetime_freezed))
self.assertFalse(isinstance_date(None))
check()
with freeze_time('2005-01-01'):
check()
def test_isinstance_datetime(self):
def check():
self.assertFalse(isinstance_datetime(self.date_orig))
self.assertFalse(isinstance_datetime(self.date_freezed))
self.assertTrue(isinstance_datetime(self.datetime_orig))
self.assertTrue(isinstance_datetime(self.datetime_freezed))
self.assertFalse(isinstance_datetime(None))
check()
with freeze_time('2005-01-01'):
check()