模拟上下文中的计时,以使用具有auto_now_add = True的字段DateTimeField创建模型 [英] Mock timing in a context to create models with a field DateTimeField with auto_now_add=True
问题描述
我想模拟计时,以便在测试期间可以将DateTimeField
的字段,例如:
I'd like to mock timing so that be able to set certain time to a field of type DateTimeField
with auto_now_add=True
during my tests e.g:
class MyModel:
...
created_at = models.DateTimeField(auto_now_add=True)
...
class TestMyModel(TestCase):
...
def test_something(self):
# mock current time so that `created_at` be something like 1800-02-09T020000
my_obj = MyModel.objects.create(<whatever>)
# and here my_obj.created_at == 1800-02-09T000000
我知道当前日期为 总是 用于这种类型的字段,这就是为什么我正在寻找一种替代方法,以某种方式模拟系统时序,但只是在上下文中.
我尝试了一些方法,例如,使用freeze_time
创建上下文,但是没有用:
I've tried some approaches, for instance, creating a context with freeze_time
but didn't work:
with freeze_now("1800-02-09"):
MyModel.objects.create(<whatever>)
# here the created_at doesn't fit 1800-02-09
我猜是Ofc,这是由于auto_now_add=True
时在幕后创建对象的机制.
Ofc I guess, this is due to the machinery behind the scene to create the object when auto_now_add=True
.
我不想删除auto_now_add=True
和/或使用默认值.
I don't want to remove auto_now_add=True
and/or use default values.
有没有一种方法可以模拟时间安排,以便我们可以使这种类型的字段在某些情况下获得我想要的时间?
Is there a way we can mock the timing so that we can make this type of field to get the time that I want in certain context?
我正在使用Django 1.9.6
和Python 3.4
推荐答案
好的,我找到了一个解决方案,它基于模拟:
Okay, I have found a solution, it is based on mock:
def mock_now():
return <mock time>
class TestMyModel(TestCase):
...
@mock.patch('django.utils.timezone.now', mock_now)
def test_as_decorator(self):
...
my_obj = MyModel.objects.create(<whatever>)
...
# here the created_at field has the mocking time :)
def test_as_context_manager(self):
mocked_dt = datetime.datetime(2015, 9, 3, 11, 15, 0)
with mock.patch('django.utils.timezone.now', mock.Mock(return_value=mocked_dt)):
my_obj = MyModel.objects.create(<whatever>)
# here the created_at field has the mocking time :)
这篇关于模拟上下文中的计时,以使用具有auto_now_add = True的字段DateTimeField创建模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!