Skip to main content
 首页 » 编程设计

python之如何测试 View 是否仅由 Django 中的员工用户访问

2024年08月23日41shanyou

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

def staff_users(request): 
    .... 
    # some logic 
 
    return HttpResponseRedirect('/repositories/') 

如果请求来自员工用户,它应该重定向到存储库,否则我应该得到类似 permission denied 的信息。我从 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 访问?

请您参考如下方法:

您需要做的就是装饰您想要保护的 View ,如下所示:

@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/') 

编辑

关联sessions根据请求对象进行测试可以按以下方式完成:

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

此外,使用 django Client 会是一个更好的主意。测试库:

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