Overwrite auto_now for unittest

后端 未结 3 376
北荒
北荒 2021-01-12 15:50

I\'ve defined some timestamps for events in the database as auto_now_add, as the information should be stored with it\'s timestamp the same time the event is st

3条回答
  •  青春惊慌失措
    2021-01-12 16:50

    The problem with fixtures for me, is that I need to test that certain records that are older than 30 days are not returned, and ones that are not 30 days old are returned ... using static fixtures this cannot be done (in a lazy way). So what I chose to do is mock the timezone.now function which django uses to get the datetime to use.

    from django.utils import timezone 
    
    class SomeTestCase(TestCase):
        def test_auto_add(self):
            now = timezone.now()
            now_31 = now - datetime.timedelta(days=31)
            self.mock('timezone.now', returns=now_31, tracker=None)
            SomeObject.objects.create() # has auto_now_add field ...   
    

    for mocking I use minimocktest

提交回复
热议问题