Search code examples
pythondjangounit-testingdatetimefactory-boy

How to test auto_now_add in django


I have django 1.11 app and I want to write unit test for my solution.

I want to test registration date feature.

model.py:

class User(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    registration_date = models.DateTimeField(auto_now_add=True)

    def get_registration_date(self):
        return self.registration_date

I'm using also django-boy for models factories: factories.py

  class UserFactory(factory.DjangoModelFactory):
        class Meta:
            model = models.User
        first_name = 'This is first name'
        last_name = 'This is last name'
        registration_date = timezone.now()

test.py

def test_get_registration_date(self):
    user = factories.UserFactory.create()
    self.assertEqual(user.get_registration_date(), timezone.now())

Problem is that I recived AssertionError:

AssertionError: datetime.datetime(2018, 4, 17, 9, 39, 36, 707927, tzinfo=<UTC>) != datetime.datetime(2018, 4, 17, 9, 39, 36, 708069, tzinfo=<UTC>)

Solution

  • You can use mock:

    import pytz
    from unittest import mock
    
    def 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)