我想模拟计时,以便能够将特定时间设置为 DateTimeField
类型的字段,在 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用于此类字段,这就是为什么我正在寻找一种替代方法来以某种方式模拟系统计时,但只是在上下文中。
我尝试了一些方法,例如,使用 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
和 Python 3.4
最佳答案
好的,我找到了解决方案,它基于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 :)
关于python - 在上下文中模拟计时以创建具有字段 DateTimeField 和 auto_now_add=True 的模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37284183/