6

我正在尝试编写一个测试来验证从基于类的通用视图返回的 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 获得“空”请求的响应?

4

2 回答 2

6

感谢dm03513的指点!事实上,我必须使用 RequestFactory,但还要确保它request包含一个空的session(尽管SessionMiddleware首先列出):

# tests.py
from django.test import TestCase
from django.test.client import RequestFactory

class SimpleTest(TestCase):
    def setUp(self):
        self.factory = RequestFactory()

    def test_home_page_returns_correct_html(self):
        request = self.factory.get('/')
        request.session = {}
        view_func = SimpleView.as_view()
        response = view_func(request)
        response.render()
        self.assertIn('<html>', response.content)
于 2013-04-21T16:45:17.087 回答
2

您可以使用内置测试客户端的 djangos来完成此操作,而不是直接实例化和调用视图

测试客户端允许您通过 django url 路由器发出请求

response = self.get('/url/to/invoke/simpleview/')

此外,我还发现了一些关于如何测试基于类的视图的博文,其中之一是http://tech.novapost.fr/django-unit-test-your-views-en.html

于 2013-04-21T16:12:22.700 回答