2

我正在 Django 中学习测试,并且有一个我想测试的视图。此视图只能由员工用户访问。假设视图是:

def staff_users(request):
    ....
    # some logic

    return HttpResponseRedirect('/repositories/')

如果请求来自员工用户,它应该重定向到存储库,否则我应该得到类似permission denied. 我从类似 in 的东西开始tests.py

 def test_request_object(self):
        self.user = User.objects.create_user(
        username='abc', email='abc@gmail.com', password='1234')
        request = HttpRequest()
        # User send a request to access repositories
        response = staff_users(request)
        self.assertIsNone(response)

问题出在这里我没有将我的请求对象与任何用户相关联,而且我也了解from django.contrib.admin.views.decorators import staff_member_required但不确定如何在这里使用它们。谁能告诉我应该如何测试我的view应该只能被访问staff users

4

1 回答 1

4

您需要做的就是decorate您想要保护的视图,如下所示:

@staff_member_required
def staff_users(request):
    ....
    # some logic

    return HttpResponseRedirect('/repositories/')

如果您想要一个自定义逻辑来测试而不是使用 django 装饰器,那么您也可以编写自己的装饰器。

def staff_users_only(function):
  def wrap(request, *args, **kwargs):

        profile = request.session['user_profile']
        if profile is True: #then its a staff member
             return function(request, *args, **kwargs)
        else:
            return HttpResponseRedirect('/')

  wrap.__doc__=function.__doc__
  wrap.__name__=function.__name__
  return wrap

并将其用作:

@staff_users_only
def staff_users(request):
    ....
    # some logic

    return HttpResponseRedirect('/repositories/')

编辑

用于测试的请求对象上的会话关联可以如下完成:

def test_request_object(self):
    self.user = User.objects.create_user(
    username='abc', email='abc@gmail.com', password='1234')
    request = HttpRequest()
    #create a session which will hold the user profile that will be used in by our custom decorator
    request.session = {} #Session middleware is not available in UnitTest hence create a blank dictionary for testing purpose
    request.session['user_profile'] = self.user.is_staff #assuming its django user.

    # User send a request to access repositories
    response = staff_users(request)

    #Check the response type for appropriate action
    self.assertIsNone(response)

编辑 2

Client使用 django库进行测试也是一个更好的主意:

>>> from django.test import Client
>>> c = Client()
>>> response = c.post('/login/', {'username': 'abc', 'password': '1234'})
>>> response.status_code
200
>>> response = c.get('/user/protected-page/')
>>> response.content
b'<!DOCTYPE html...
于 2015-11-08T03:42:23.193 回答