如何测试 403 错误? [英] How can I test a 403 error?
问题描述
我有一个测试类,用于测试不同用户对所有页面的访问.
I have a Test Class, that test the access of all page with different user.
这些访问权限由装饰器在我的每个视图上定义.
Those access are defined by decorator on each of my views.
views.py :
@login_required
def afficher(request):
...
...
@creation_permission_required
def ajouter(request):
...
...
其中一些装饰器是我定义的.
Some of these decorator are defined by me.
decorators.py :
def creation_permission_required(function):
@wraps(function)
@login_required
def decorateur(request, *k, **a):
user = get_object_or_404(User, username__iexact=request.user.username)
if user.is_superuser or user.get_profile().creation:
return function(request, *k, **a)
else:
return HttpResponseRedirect(reverse("non_autorise"))# <--- PROBLEM
return decorateur
return function
当我测试它们时,我使用 status_code 属性来验证用户是否可以访问该页面
When I test them, I use the status_code attribute to verify if the user can access or not the page
test.py :
c = Client()
c.login(username='aucun', password='aucun')
for url in self.url_aucun:
r = c.get(reverse(url['url'], args=url['args']))
self.assertEqual(r.status_code, 200)
for url in self.url_creation:
r = c.get(reverse(url['url'], args=url['args']))
self.assertEqual(r.status_code, 302) # <--- SECOND PROBLEM
当用户无权访问某个页面时,该页面应返回 403 错误(禁止).我该如何测试 403 而不是 302?
When a user doesn't have the right to access a page, the page should return a 403 error (forbidden). How can I do to test 403 instead of 302 ?
我尝试使用 HttpResponseForbidden(reverse("non_autorise")),但无法获取任何内容.然后我尝试制作自己的 HttpResponse ,它是 HttpResponseRedirect 的精确副本,但使用另一个 status_code (403) 仍然没有得到任何内容...
EDIT : I tried to use HttpResponseForbidden(reverse("non_autorise")), but couldn't get any content. So then I tried to make my own HttpResponse which is an exact copy of HttpResponseRedirect but with another status_code (403) still didn't get any content...
decorators.py :
class HttpResponseTest(HttpResponse):
def __init__(self, redirect_to):
super(HttpResponseTest, self).__init__()
self['Location'] = iri_to_uri(redirect_to)
self.status_code = 403
def creation_permission_required(function):
@wraps(function)
@login_required
def decorateur(request, *k, **a):
user = get_object_or_404(User, username__iexact=request.user.username)
if user.is_superuser or user.get_profile().creation:
return function(request, *k, **a)
else:
return HttpResponseTest(reverse("non_autorise"))# <--- PROBLEM
return decorateur
return function
推荐答案
如果你想要 403 响应,你可以提出一个 PermissionDenied 异常.或者,您可以在你的装饰者.您还必须构建自定义 login_required 装饰器.
If you want a 403 response, you can raise a PermissionDenied exception in your decorator if you are using Django 1.4. Alternatively, you can return a HttpResponseForbidden in your decorator. You will also have to build a custom login_required decorator.
这篇关于如何测试 403 错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!