我正在尝试编写一个测试来验证从基于类的通用视图返回的 HTML。假设我有这个基于函数的视图,它只是呈现一个模板:
# views.py
from django.shortcuts import render
def simple_view(request, template='template.html'):
return render(request, template)
有了这个,在测试期间我可以这样做:
# tests.py
from django.http import HttpRequest
from .views import simple_view
request = HttpRequest()
response = simple_view(request)
然后在response
. 现在我想将上面的转换为从 TemplateView 继承的基于类的视图:
# views.py
from django.views.generic import TemplateView
class SimpleView(TemplateView):
template_name = 'template.html'
现在基本上相同的测试方法失败了:
# tests.py
from django.http import HttpRequest
from .views import SimpleView
request = HttpRequest()
view_func = SimpleView.as_view()
response = view_func(request).render()
结果是
Traceback (most recent call last):
File "tests.py", line 30, in test_home_page_returns_correct_html
response = view_func(request).render()
File "lib/python2.7/site-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "lib/python2.7/site-packages/django/views/generic/base.py", line 82, in dispatch
if request.method.lower() in self.http_method_names:
AttributeError: 'NoneType' object has no attribute 'lower'
我尝试request.method
手动设置为GET
,但这只会引发另一个错误,抱怨session
不在request
.
有没有办法从 TemplateView 获得“空”请求的响应?