How to test auto_now_add in django How to test auto_now_add in django django django

How to test auto_now_add in django


You can use mock:

import pytzfrom unittest import mockdef test_get_registration_date(self):    mocked = datetime.datetime(2018, 4, 4, 0, 0, 0, tzinfo=pytz.utc)    with mock.patch('django.utils.timezone.now', mock.Mock(return_value=mocked)):        user = factories.UserFactory.create()        self.assertEqual(user.get_registration_date(), mocked)


You can use the package freeze gun. https://github.com/spulec/freezegun which patchs datetime.now().

from freezegun import freeze_time...    @freeze_time("2017-06-23 07:28:00")    def test_get_registration_date(self):        user = factories.UserFactory.create()        self.assertEqual(            datetime.strftime(user.get_registration_date(), "%Y-%m-%d %H:%M:%S")            "2017-06-23 07:28:00"        )


Just use the factory.post_generation decorator:

class UserFactory(factory.DjangoModelFactory):    ...    @factory.post_generation    def registration_date(self, create, extracted, **kwargs):        if extracted:            self.registration_date = extracted