我正在学习Django的测试,并且有一个我想测试的视图。只有员工用户才能访问此视图。假设视图是:
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
访问?
答案 0 :(得分:3)
您需要做的只是decorate
您要保护的视图,如下所示:
@staff_member_required
def staff_users(request):
....
# some logic
return HttpResponseRedirect('/repositories/')
如果您想要一个自定义逻辑进行测试而不是使用django decorator,那么您也可以编写自己的装饰器。
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...