在 Django 上进行测试的问题

Problems to make tests on Django

我是测试新手,教程对我一点帮助都没有(它们要么太旧,要么不适用于我的情况)。

我想在 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 是这样设置的:

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

-- 编辑

例如,现在我被困在一些本来应该是基本的事情上......

测试:

导入单元测试 来自 django.test 导入 RequestFactory 来自 twist.views 导入 *

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''

嗯,最简单的方法是编写测试整个视图流的集成测试。这可以使用 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 返回的函数中创建的 class 实例。通常我更喜欢集成测试而不是测试视图,但有时如果你真的需要对某些部分进行单元测试,你可以像 --

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})

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

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

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

而不是

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