在Django上进行测试的问题

时间:2015-09-23 14:22:25

标签: python django testing integration-testing bdd

我是测试的新手,教程根本没有帮助我(他们要么老了,要么不适合我的情况)。

我想在Django上测试一些功能。让我们说我想测试一下:

class PageDetailView(AuthorizedView, PermissionRequiredMixin, DetailView):
    """
    Page Detail View

    This view will load the whole dataset for a Page
    """
    permission_required = 'view_page'
    # This is temporary. The idea is to redirect user to a call_to_action page
    redirect_field_name = 'panel'
    model = Page
    template_name = 'twist/entity_topic_detail.html'

    def get_context_data(self, **kwargs):
        context = super(PageDetailView, self).get_context_data(**kwargs)
        evaluated_news = EvaluatedNews(self.object,
                                   self.request.user)
        context['evaluated_news'] = evaluated_news()
        context['modules'] = [
            'sources',
            'ranking',
            'topics',
            'locations_coord',
            'terms',
            'news',
            'relations',
            'twitterterms',
            'twittertweets',
            'twitterheatmap'
            ]
        return context

我该如何申请考试?

这是网址的设置方式:

url(r'detail/(?P<pk>[\d]+)/$', views.PageDetailView.as_view(), name='detail'),

- 编辑

例如,现在我陷入了应该是基本的东西......

试验:

导入unittest 来自django.test导入RequestFactory 来自twist.views import *

class PageDetailTest(unittest.TestCase):
    def test_get(self):
         self.user = User.objects.create_user(username="admin", password="123")
         request = RequestFactory().get("/detail/2/")
         view = PageDetailView.as_view(template_name="twist/entity_topic_detail.html")
         response = view(request)
         self.assertEqual(response.status_code, 200)

错误:

'if test_func(request.user):                                          │~                                                          
AttributeError: 'WSGIRequest' object has no attribute 'user''

1 个答案:

答案 0 :(得分:4)

嗯,最简单的方法是编写测试整个视图流的集成测试。这可以使用django测试客户端轻松完成: -

from django.test import TestCase

class TestPageDetailView(TestCase):

    def setUp(self):
        self.id = '234' # some valid id for your use cacse
        self.url = "/detail/{0}/".format(url = self.id)

        self.response = self.client.get(self.url)

    def test_returns_valid_response(self):
        self.assertEqual(self.response.status_code, 200)

    def test_returns_correct_context_variables(self):
        expected_context_vars = ['sources', 'ranking', 'topic'] # ...

        map(lambda context_var: self.assertIn(context_var, self.response.context), expected_context_vars)

显然,它并非详尽无遗,而且您需要处理身份验证和其他内容,但这些内容仍然存在。

虽然,如果你想单独测试一些方法,你需要掌握as_view返回的函数中的类实例。通常我更喜欢集成测试来测试视图,但有时如果你真的需要对某些部分进行单元测试,你可以做类似的事情 -

from django.http import HttpRequest

class TestViewMixin(object):

    def create_view_object(self, view, request, args = [], kwargs = {}):
        view_object = view()
        view_object.request, view_object.args, view_object.kwargs = request, args, kwargs

        return view_object

class TestUnitPageDetailView(TestViewMixin, TestCase):

    def setUp(self):
        self.id = '234'
        self.request = HttpRequest()
        self.request.method = 'GET'

        self.view = self.create_view_object(PageDetailView, self.request, kwargs = {'pk': self.id})

现在,您可以像测试普通类一样测试视图。

就您的已编辑的答案而言,您需要将user分配给请求,而不是测试类实例

request.user = User.objects.create_user(username="admin", password="123")

而不是

self.user = User.objects.create_user(username="admin", password="123")