Django测试返回_wrapped_view作为视图名称而不是正确的视图名称

时间:2012-01-15 13:05:20

标签: django view decorator

在我的django项目中,我通常使用以下方法测试被调用的视图是否正确:

viewName = resolve(response.request["PATH_INFO"])[0].func_name
self.assertEqual(viewName,'correct_view_name')

我成功地做到了,直到我添加了装饰器。从那时起,我的观点正常工作,但我无法测试(至少像这样)正确的视图名称。

我添加的装饰者看起来像这样:

def owner_required(view_func, Model):
    '''
    checks if the object is being accessed but its owner
    '''
    def decorator(view_func):
        def _wrapped_view(request, *args, **kwargs):
            obj = Model.objects.get(pk=int(kwargs['pk']))
            if obj.user == request.user:
                return view_func(request, *args, **kwargs)
            return HttpResponse('You don't have access to this page.')
        return _wrapped_view
    return decorator(view_func)

应用此装饰器时resolve(response.request["PATH_INFO"])[0].func_name的结果始终为“_wrapped_view”

如何让视图名称恢复正常?

由于

1 个答案:

答案 0 :(得分:3)

您可以在装饰器中使用functools.wraps

try:
    from functools import wraps
except ImportError:
    from django.utils.functional import wraps  # Python 2.4 fallback.
from django.utils.decorators import available_attrs

def owner_required(view_func, Model):
    '''
    checks if the object is being accessed but its owner
    '''
    def decorator(view_func):
        @wraps(view_func, assigned=available_attrs(view_func))
        def _wrapped_view(request, *args, **kwargs):
            obj = Model.objects.get(pk=int(kwargs['pk']))
            if obj.user == request.user:
                return view_func(request, *args, **kwargs)
            return HttpResponse('You don't have access to this page.')
        return _wrapped_view
    return decorator(view_func)