使用django测试客户端

时间:2017-04-11 19:44:54

标签: python django integration-testing

我使用UserPassesTestMixin保护了基于django类的视图。它的test_func采用一个名为division的参数,检查当前用户是否是该部门的负责人。

该视图在网站中运行良好,但我无法编写成功的测试。似乎在client.get和test_func之间,用户正在消失。

我已经使用RequestFactory和Client尝试过此操作。我试图强制登录。确保正确的中间件到位。

mixin的测试并没有帮助我看到这个问题。 (https://github.com/django/django/blob/29f607927fe82e2c8baab171dfa8baf710cd9b83/tests/auth_tests/test_mixins.py

现在我无法针对受UserPassesTestMixin保护的视图测试各种角色。当我使用 client.login(用户名=' div1chair',密码=' basicpassword')登录时,我很欣赏为什么会这样做,视图中有一个空的 self.request.user

def test_permissions_to_access_division_summary_view(self):
        """
        This test ensures that only department chairs and the division
        director for the specific division detail can see the division
        summary.
        """
        url = "/division1"

        client = Client()
        client.login(username='div1chair', password='basicpassword')

        # ipdb here confirms that div1chair is logged in
        # ETA: ut oh.  looks like this is not accurate. Now I'm really confused. client.login is giving False.

        response = client.get(url,follow=True)
        self.assertEqual(response.status_code, 200) # AssertionError: 404 != 200

以下是我正在测试的观点。

class DivisionDirectorView(UserPassesTestMixin, View):

    def test_func(self):     

        division = Division.objects.get(short_name=self.kwargs['division'])

        # ipdb here confirms that there is no user, or at least username is ''
        if self.request.user == division.director:
            return True

        return False

ETA:这是urls.py:

from django.conf.urls import url
from fds.apps.professionalmetrics import views

urlpatterns = [
    url(r'^$', views.metrics_default, name='metrics_default'),
    # SNIP
    url(r'(?P<division>[\w-]+)/$',
        views.DivisionDirectorView.as_view(),
        name='div-metric-summary'),
    ]

1 个答案:

答案 0 :(得分:0)

您的test_funcdispatch方法不常见 - test_func mixin的UserPassesTest不应接受self以外的任何参数。我会将test_func简化为以下内容:

def test_func(self):     
    division = Division.objects.get(short_name=self.kwargs['division'])
    return self.request.user == division.director

然后,您应该可以从dispatch方法中删除自定义代码。

但是,我不确定这是否能解决您在测试中发现的问题。您尚未显示您的网址,因此我无法确定client.get(url, follow=True)是否应返回200或是否预期404。您可以通过设置follow = False并检查response来尝试调试。