Python 出于测试目的访问原始修饰函数
我正在视图函数中使用装饰器(Python 出于测试目的访问原始修饰函数,python,testing,decorator,python-decorators,introspection,Python,Testing,Decorator,Python Decorators,Introspection,我正在视图函数中使用装饰器(django\u包中的@render\u to) 但问题是,我想得到view函数返回的原始dict,用于测试目的,而不是decorator返回的HttpResponse对象 装饰器使用@wrapps(来自functools) 如果无法访问此项,那么您是否知道如何测试此项?包装的函数将作为函数闭包单元提供。哪个单元格取决于闭包变量的数量 对于一个简单的包装器,其中唯一的闭包变量是要包装的函数,它将是第一个: wrapped = decorated.func_closur
django\u
包中的@render\u to
)
但问题是,我想得到view函数返回的原始dict,用于测试目的,而不是decorator返回的HttpResponse
对象
装饰器使用@wrapps
(来自functools
)
如果无法访问此项,那么您是否知道如何测试此项?包装的函数将作为函数闭包单元提供。哪个单元格取决于闭包变量的数量 对于一个简单的包装器,其中唯一的闭包变量是要包装的函数,它将是第一个:
wrapped = decorated.func_closure[0].cell_contents
但您可能必须检查所有func_闭包值
演示使用:
如果您可以访问decorator代码本身,也可以在Python 2代码中轻松添加相同的引用:
def my_decorator(f):
@wraps(f)
def wrapper(*args, **kwds):
# implementation
wrapper.__wrapped__ = f
return wrapper
让内省变得简单一点。下面是一段代码,它递归地搜索在多个级别上修饰过的原始函数。
这背后的逻辑与@Martin提到的答案相同
def get_original_decorated_function(deco_func, org_func_name= None):
if not deco_func.func_closure:
if deco_func.__name__ == org_func_name:
return deco_func
else:
return None
for closure in deco_func.func_closure:
func = closure.cell_contents
if func.__name__ == org_func_name:
# This is the original function name
return func
else:
# Recursively call the intermediate function
return get_original_decorated_function(func, org_func_name)
我删除了django
标签;这并不是Django特有的,真的。在这里测试过,而且有效!!感谢您提供的详细答案=)和Python3信息。
def my_decorator(f):
@wraps(f)
def wrapper(*args, **kwds):
# implementation
wrapper.__wrapped__ = f
return wrapper
def get_original_decorated_function(deco_func, org_func_name= None):
if not deco_func.func_closure:
if deco_func.__name__ == org_func_name:
return deco_func
else:
return None
for closure in deco_func.func_closure:
func = closure.cell_contents
if func.__name__ == org_func_name:
# This is the original function name
return func
else:
# Recursively call the intermediate function
return get_original_decorated_function(func, org_func_name)