【发布时间】:2016-11-19 07:12:37
【问题描述】:
我试图模拟 Django 的 now() 函数,以欺骗我的应用程序中使用的时间。我可以轻松地在我的测试文件中模拟 now() 函数,但模拟替换似乎并没有递归地渗透到我的应用程序函数中。这是我正在使用的代码:
# file - tests.py:
import datetime
import pytz
import mock
from django.test import TestCase
# this is the fake time I am using
TESTING_DJNOW = pytz.timezone('US/Central').localize(datetime.datetime(2016, 6, 14, 8, 0))
# This is the function that replaces django.utils.timezone.now()
def mocked_djnow():
return TESTING_DJNOW
@mock.patch('django.utils.timezone.now', side_effect=mocked_djnow)
class ViewsTestCase(TestCase):
fixtures = ['users.json', 'views_data.json'] # our initial test data
def setUp(self):
self.client = Client()
self.client.login(username='fred', password='secret')
def test_view(self, *args):
from django.utils.timezone import now
tm = now() # returns datetime.datetime(2016, 6, 14, 8, 0,
# tzinfo=<DstTzInfo 'US/Central' CDT-1 day, 19:00:00 DST>)
resp = self.client.get(reverse('myapp:viewfunc1'))
# file - myapp.views.py:
from django.utils.timezone import localtime, now
@login_required
def viewfunc1(request):
# returns datetime.datetime(2016, 7, 16, 1, 11, 6, 964624, tzinfo=<UTC>)
tm = now() # returns current datetime
是否可以在整个应用程序中修补像 now() 这样的 Django 函数?如果是这样,我做错了什么?还有其他建议吗?
【问题讨论】:
标签: python django unit-testing mocking