[英]How can I mock the created field of a model that inherits from TimeStampedModel using model_mommy?
I am trying to test a date filter but have been unable to set the created date using mommy.make(). 我正在尝试测试日期过滤器,但无法使用mommy.make()设置创建的日期。 When I make the objects with model mommy the created field is set to the time the objects were created rather than what I passed in with mommy.make()
当我使用模型mommy制作对象时,创建的字段设置为创建对象的时间,而不是我使用mommy.make()传递的时间
def test_mommy(self):
today = arrow.now()
yesterday = today.replace(days=-1)
mommy.make('Model', created=today.naive)
mommy.make('Model', created=yesterday.naive)
model_1_created = Model.objects.all()[0].created
model_2_created = Model.objects.all()[1].created
self.assertNotEqual(model_1_created.strftime('%Y-%m-%d'), model_2_created.strftime('%Y-%m-%d'))
This test fails with the Assertion Error: 该测试失败并出现断言错误:
AssertionError: '2018-03-15' == '2018-03-15'
I may have a misunderstanding of how model_mommy creates these objects. 我可能对model_mommy如何创建这些对象有误解。 But I would think this should create it and set the created dates properly.
但是我认为这应该创建它并正确设置创建日期。 Though it looks like the default TimeStampedObject behavior is taking over.
虽然看起来默认的TimeStampedObject行为正在接管。
I was able to save the created by dates after the objects had been created. 创建对象后,我能够保存创建日期。 I think this could have also been achieved by overriding the save method on TimeStampedModel.
我认为也可以通过重写TimeStampedModel上的save方法来实现。 But this seemed like the simpler solution.
但这似乎是更简单的解决方案。
def test_mommy(self):
today = arrow.now()
yesterday = today.replace(days=-1)
foo = mommy.make('Model')
bar = mommy.make('Model')
foo.created = today.naive
foo.save()
bar.created = yesterday.naive
bar.save()
model_1_created = Model.objects.all()[0].created
model_2_created = Model.objects.all()[1].created
self.assertNotEqual(model_1_created.strftime('%Y-%m-%d'), model_2_created.strftime('%Y-%m-%d'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.