Skip to content

Instantly share code, notes, and snippets.

@heathhenley
Last active December 1, 2023 14:22
Show Gist options
  • Save heathhenley/f9a61cda170d99f7066af71573e995ba to your computer and use it in GitHub Desktop.
Save heathhenley/f9a61cda170d99f7066af71573e995ba to your computer and use it in GitHub Desktop.
Tests for Django model that uses columns with auto_now
""" A way to test columns with auto_now
Columns with auto_now auto update with the current time when
the model is saved - this patches function django uses to
get the current time when the model is saved to use whatever
time you want.
Base on answers on SO: https://stackoverflow.com/questions/49874923/how-to-test-auto-now-add-in-django
"""
from contextlib import contextmanager
from unittest.mock import patch
from django.test import TestCase
from django.utils import timezone
from .models import MyModel # model w/ auto_now col
@contextmanager
def freeze_time(at: dt.datetime):
with patch.object(timezone, 'now', return_value=at): # patch django.utils.timezone.now()
yield
class TestMyApp(TestCase):
def test_create_model_that_uses_autonow(self):
# this one will have the current time
my_obj = MyModel.objects.create(...)
# some time other than now that you want to use
at = dt.datetime(...)
with freeze_time(at):
my_obj_freeze = MyModel.objects.create(...)
# do testy stuff...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment