How to Use freezegun in Django Tests to Set the Date One Day Ahead with USE_TZ=True

Django
2019-03-26 08:57 (5 years ago) ytyng

reezegun is a Python library.

It hooks into the current time retrieval with datetime, allowing you to perform tests that assume "the next day" and similar scenarios.

If you want to perform tests in Django that assume "the next day":

今日のログインボーナス()
with freezegun.freeze_time(datetime.timedelta(days=1)):
    明日のログインボーナス()

This might cause issues such as test failures before 9:00 AM when developing in the JST timezone.

from django.utils import timezone

今日のログインボーナス()
with freezegun.freeze_time(timezone.now() + datetime.timedelta(days=1)):
    明日のログインボーナス()

The same goes for this case.

If you pass a timezone-aware datetime other than UTC to the freeze_time argument, the timezone may not be handled correctly in a development environment using the JST timezone.

To correctly determine the next day, you should do:

import datetime

今日のログインボーナス()
with freezegun.freeze_time(datetime.datetime.now() + datetime.timedelta(days=1)):
    明日のログインボーナス()

or

import datetime

今日のログインボーナス()
with freezegun.freeze_time(datetime.timedelta(days=1), tz_offset=9):
    明日のログインボーナス()
import datetime
from django.utils import timezone
tz = timezone.get_current_timezone()

今日のログインボーナス()
with freezegun.freeze_time(datetime.timedelta(days=1), tz_offset=tz._utcoffset):
    明日のログインボーナス()

You need to set it up like this.

To generally freeze_time with an aware datetime

aware_datetime = ...

with freezegun.freeze_time(
    aware_datetime, tz_offset=aware_datetime._utcoffset):
    ...
Currently unrated

Comments

Archive

2024
2023
2022
2021
2020
2019
2018
2017
2016
2015
2014
2013
2012
2011