Skip to content

Instantly share code, notes, and snippets.

@voidnologo
Last active November 3, 2015 19:44
Show Gist options
  • Save voidnologo/63b2fc9d5447bd714b4c to your computer and use it in GitHub Desktop.
Save voidnologo/63b2fc9d5447bd714b4c to your computer and use it in GitHub Desktop.
Testing Django model fields with 'auto_now'
class MyModel(models.Model):
  time_field = models.DateTimeField(auto_now=True)

This makes testing difficult, because the created field will always be the current time. If you try changeing it with

myobject.time_field = _sometime
myobject.save()

it will get reset to the current time when saving.

Here's how to change the time that it gets set to in a test:

testtime = datetime.strptime('2015-10-31', '%Y-%m-%d')
with mock.patch('django.utils.timezone.now') as mock_now:
  mock_now.return_value = testtime
  MyModel.objects.create()

When the with block is over, further models will be created with current time.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment