如何在django中测试auto_now_add

时间:2018-04-17 09:50:11

标签: python django unit-testing datetime factory-boy

我有django 1.11 app,我想为我的解决方案编写单元测试。

我想测试注册日期功能。

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

我还使用django-boy作为模型工厂: 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())

问题是我收到了AssertionError

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

3 个答案:

答案 0 :(得分:4)

您可以使用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)

答案 1 :(得分:1)

您可以使用包冷冻枪。修补datetime.now()的https://github.com/spulec/freezegun

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"
        )

答案 2 :(得分:0)

只需使用factory.post_generation装饰器:

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