我正在嘗試編寫一個測試,用於驗證從泛型類視圖返回的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以「空」請求獲得響應?
http://stackoverflow.com/questions/8603035/how-tdd-can-be -applied-to-django-class-based-generic-views – dm03514 2013-04-21 16:13:35