Josh Brown
Josh Brown

Reputation: 1

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(). 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()

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. 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.

Upvotes: 0

Views: 484

Answers (1)

Josh Brown
Josh Brown

Reputation: 1

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. 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'))

Upvotes: 0

Related Questions