I have a test where I create a few objects:
def test_get_courier_task_returns_couriers_tasks(self):
with patch('django.utils.timezone.now', return_value=make_aware(datetime(2018, 1, 24, 11, 57))):
task1 = TaskFactory()
response = json.loads(MyAPI.get_tasks_list(self.user.username))
print('[*] Response timestamp: {}'.format(response['content'][0]['timestamp']))
The Task
has created_timestamp
field with auto_add_now
set to True and to_json()
method which is used in get_tasks_list()
above:
class Task(models.Model):
created_timestamp = models.DateTimeField(auto_now_add=True)
def to_json(self):
to_return = {
'timestamp': self.created_timestamp.strftime('%d-%m-%Y %H:%M')
}
return to_return
Unfortunately tests give this output:
[*] Response timestamp: 24-01-2018 10:57
I have checked that this is timezone aware, but instead of giving me UTC+1 it gives UTC+0 on saving. What do I have to do? I have USE_TZ = True
in my settings and I have applied migrations. This question did not help with my problem.
事实证明,给时区明确表示有助于:
with patch('django.utils.timezone.now', return_value=datetime(2018, 1, 24, 11, tzinfo=pytz.timezone('utc'))):
Try providing make_aware
with the timezone you want.
Also checking for a specific time in the test is a bit circular, probably don't need to check for it and just make sure it runs and produces a timestamp.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.