如何冻结时间并在模板中的时间戳上声明?

时间:2019-05-22 11:17:03

标签: python django django-unittest freezegun

p1/urls.py

from django.urls import path
from . import views
urlpatterns = [
    path('t1/', views.t1),
]

p1/views.py

from django.shortcuts import render
def t1(request):
    return render(request, 'p1/t1.html')

p1/templates/p1/t1.html

<?xml version="1.0" encoding="UTF-8"?>
<root timestamp="{% now 'Y-m-d H:i:s' %}">...</root>

p1/settings.py

TIME_ZONE = 'Asia/Tokyo'
USE_TZ = True
INSTALLED_APPS = [
    ...
    'p1',
]

p1/tests.py

from django.test import TestCase
from freezegun import freeze_time

class MyTestCase(TestCase):
    @freeze_time('2019-01-02 03:04:05')
    def test_freezegun(self):
        expected_response = '''
            <?xml version="1.0" encoding="UTF-8"?>
            <root timestamp="2019-01-02 03:04:05">...</root>
        '''
        response = self.client.get('/t1/')
        self.assertXMLEqual(expected_response, response.content.decode(response.charset))

然后

$ ./manage.py test
Creating test database for alias 'default'...
F
======================================================================
FAIL: test_freezegun (p1.tests.MyTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/yuri/_/1/env/lib/python3.7/site-packages/freezegun/api.py", line 658, in wrapper
    result = func(*args, **kwargs)
  File "/home/yuri/_/1/p1/p1/tests.py", line 12, in test_freezegun
    self.assertXMLEqual(expected_response, response.content.decode('utf-8'))
  File "/home/yuri/_/1/env/lib/python3.7/site-packages/django/test/testcases.py", line 854, in assertXMLEqual
    self.fail(self._formatMessage(msg, standardMsg))
AssertionError: '\n            <?xml version="1.0" encoding="UTF-8"?>\n            <root timesta [truncated]... != '<?xml version="1.0" encoding="UTF-8"?>\n<root timestamp="2019-01-02 12:04:05">. [truncated]...
- 
-             <?xml version="1.0" encoding="UTF-8"?>
? ------------

+ <?xml version="1.0" encoding="UTF-8"?>
-             <root timestamp="2019-01-02 03:04:05">...</root>
? ------------                            ^^

+ <root timestamp="2019-01-02 12:04:05">...</root>
?                             ^^

-         

----------------------------------------------------------------------
Ran 1 test in 0.031s

FAILED (failures=1)
Destroying test database for alias 'default'...
System check identified no issues (0 silenced).

我在做什么错?将tz_offset添加到freeze_time并没有帮助。

1 个答案:

答案 0 :(得分:0)

这里的事情是,大多数时候Django将时间戳存储在UTC中。并且仅在向data展示user时才转换为本地时间。因此,我传递给freeze_time的时间被视为UTC,但是随后模板中的now将其转换为本地时间。因此,我必须在expected_response2019-01-02 12:04:05)中指定本地时间,或者在“冻结时间”字符串(2019-01-02 03:04:05 JST)中指定时区,或者添加tz_offset (JST是UTC + 9h,所以tz_offset=-9)。