如何使用 model_mommy 模拟从 TimeStampedModel 继承的模型的创建字段?
How can I mock the created field of a model that inherits from TimeStampedModel using model_mommy?
我正在尝试测试日期过滤器,但无法使用 mommy.make() 设置创建日期。当我用模型妈妈制作对象时,创建的字段设置为创建对象的时间,而不是我用 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'))
此测试因断言错误而失败:
AssertionError: '2018-03-15' == '2018-03-15'
我可能对model_mommy如何创建这些对象有误解。但我认为这应该创建它并正确设置创建日期。虽然看起来默认的 TimeStampedObject 行为正在接管。
我能够在创建对象后保存创建日期。我认为这也可以通过覆盖 TimeStampedModel 上的保存方法来实现。但这似乎是更简单的解决方案。
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'))
我正在尝试测试日期过滤器,但无法使用 mommy.make() 设置创建日期。当我用模型妈妈制作对象时,创建的字段设置为创建对象的时间,而不是我用 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'))
此测试因断言错误而失败:
AssertionError: '2018-03-15' == '2018-03-15'
我可能对model_mommy如何创建这些对象有误解。但我认为这应该创建它并正确设置创建日期。虽然看起来默认的 TimeStampedObject 行为正在接管。
我能够在创建对象后保存创建日期。我认为这也可以通过覆盖 TimeStampedModel 上的保存方法来实现。但这似乎是更简单的解决方案。
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'))