我想模拟时间以便能够set特定时间到某个类型的字段DateTimeField
with auto_now_add=True
在我的测试期间,例如:
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
我知道当前日期是always https://docs.djangoproject.com/en/1.9/ref/models/fields/用于此类字段,这就是为什么我正在寻找一种替代方法来模拟系统计时,但是只是在一个上下文中.
我尝试过一些方法,例如,创建一个上下文freeze_time
但没有用:
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
.
我不想删除auto_now_add=True
和/或使用默认值。
有没有一种方法可以模拟时间,以便我们可以使这种类型的字段在特定上下文中获得我想要的时间?
我在用着Django 1.9.6
and Python 3.4
好的,我已经找到了解决方案,它基于mock https://pypi.python.org/pypi/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 mocked 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 :)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)