作者:大市低开_127 | 来源:互联网 | 2023-08-14 10:30
Imtryingtowriteunittestsforadjangoappthatdoesalotofdatetimeoperations.Ihaveinsta
I'm trying to write unit tests for a django app that does a lot of datetime operations. I have installed mock to monkey patch django's timezone.now
for my tests.
我正在为django应用程序编写单元测试,该应用程序执行大量的datetime操作。我为monkey patch django的时区安装了mock。现在对我的测试。
While I am able to successfully mock timezone.now
when it is called normally (actually calling timezone.now()
in my code, I am not able to mock it for models that are created with a DateTimeField
with default=timezone.now
.
当我能够成功模拟时区时。现在,在我的代码中,当它被正常调用时(实际上是调用timezone.now()时,我无法对使用默认=timezone.now的DateTimeField创建的模型进行模拟。
I have a User
model that contains the following:
我的用户模型包含以下内容:
from django.utils import timezone
...
timestamp = models.DateTimeField(default=timezone.now)
modified = models.DateTimeField(default=timezone.now)
...
def save(self, *args, **kwargs):
if kwargs.pop('modified', True):
self.modified = timezone.now()
super(User, self).save(*args, **kwargs)
My unit test looks like this:
我的单元测试是这样的:
from django.utils import timezone
def test_created(self):
dt = datetime(2010, 1, 1, tzinfo=timezone.utc)
with patch.object(timezone, 'now', return_value=dt):
user = User.objects.create(username='test')
self.assertEquals(user.modified, dt)
self.assertEquals(user.timestamp, dt)
assertEquals(user.modified, dt)
passes, but assertEquals(user.timestamp, dt)
does not.
assertequal(用户。修改,dt)通过,但是assertEquals(用户)。时间戳,dt)没有。
How can I mock timezone.now
so that even default=timezone.now
in my models will create the mock time?
我怎么能模拟时区呢?现在,即使是default=timezone。在我的模型中会创建模拟时间吗?
Edit
编辑
I know that I could just change my unit test to pass a timestamp
of my choice (probably generated by the mocked timezone.now
)... Curious if there is a way that avoids that though.
我知道我可以更改我的单元测试来通过我所选择的时间戳(可能是由模拟的timezone生成的)……我很好奇是否有什么方法可以避免这种情况。
4 个解决方案