Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何测试auto_now_插件django_Python_Django_Unit Testing_Datetime_Factory Boy - Fatal编程技术网

Python 如何测试auto_now_插件django

Python 如何测试auto_now_插件django,python,django,unit-testing,datetime,factory-boy,Python,Django,Unit Testing,Datetime,Factory Boy,我有django 1.11应用程序,我想为我的解决方案编写单元测试 我想测试注册日期功能 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

我有django 1.11应用程序,我想为我的解决方案编写单元测试

我想测试注册日期功能

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: 工厂.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: datetime.datetime(2018, 4, 17, 9, 39, 36, 707927, tzinfo=<UTC>) != datetime.datetime(2018, 4, 17, 9, 39, 36, 708069, tzinfo=<UTC>)
AssertionError:datetime.datetime(2018,4,17,9,39,36,707927,tzinfo=)!=datetime.datetime(2018,4,17,9,39,36,708069,tzinfo=)
您可以使用:


你可以用包裹冷冻枪。哪个补丁程序是datetime.now()


只需使用
工厂。生成后
装饰器:

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

为什么不给虚拟的具体时间来简化呢谢谢!也适用于auto_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"
        )
class UserFactory(factory.DjangoModelFactory):
    ...
    @factory.post_generation
    def registration_date(self, create, extracted, **kwargs):
        if extracted:
            self.registration_date = extracted