I am trying to write unit tests for a django application that does a lot of datetime operations. I installed mock in the django timezone.now monkey patch for my tests.
While I can successfully mock timezone.now when it is called normally (it actually calls timezone.now() in my code, I cannot simulate it for models created using DateTimeField with default=timezone.now .
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 work.
How can I make fun of timezone.now so that even default=timezone.now in my models creates layout time?
Edit
I know that I can just change my unit test to pass the timestamp of my choice (possibly generated by the mocked timezone.now ) ... I wonder if there is a way that avoids this.
python django unit-testing mocking python-mock
dgel
source share