自从Django 1.7.x更新到Django 1.8.x后,我的测试在检查正确的模板时失败了。我正在使用ResearchFactory:
class AdminUnitTest(TestCase):
"""Sets up the testing environment for an admin"""
def setUp(self):
self.factory = RequestFactory()
user = User.objects.create_user(
username="cj123",
email="chuck.jones@acme.edu",
password="xxx",
first_name="Chuck",
last_name="Jones"
)
admin = Staff.objects.create(user=user, role='admin')
self.user = user
然后实际测试如下:
class YearViewTest(AdminUnitTest):
def test_year_view_uses_right_template(self):
request = self.factory.get('/year_view/all')
request.user = self.user
response = year_view(request, 'all')
self.assertTemplateUsed(response, 'year_view.html')
这种方法完美无缺,直到更新到1.8。从那时起,我收到以下错误:
ValueError: assertTemplateUsed() and assertTemplateNotUsed() are only usable on responses fetched using the Django test Client.
在Django的源代码(http://django.readthedocs.org/en/latest/_modules/django/test/testcases.html)中,我只能发现这种情况会引发我得到的错误:
if template_name is not None and response is not None and not hasattr(response, 'templates'):
raise ValueError(
"assertTemplateUsed() and assertTemplateNotUsed() are only "
"usable on responses fetched using the Django test Client."
)
我很难看出我的错误在哪里。任何人都可以帮助我吗?
答案 0 :(得分:2)
错误似乎很清楚:您只能对通过测试客户端获取的响应使用该断言。您没有使用它,而是直接制作视图。
你应该使用客户端:它会大大简化你的测试。它会变成:
def test_year_view_uses_right_template(self):
self.client.login('cj123', 'xxx')
response = self.client.get('/year_view/all')
self.assertTemplateUsed(response, 'year_view.html')