作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有 django 1.11 应用程序,我想为我的解决方案编写单元测试。
我想测试注册日期功能。
模型.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
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()
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>)
最佳答案
您可以使用 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)
关于python - 如何在 Django 中测试 auto_now_add,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49874923/
我是一名优秀的程序员,十分优秀!