我有一个装饰器,我想断言我代码中的某些方法是用它装饰的。
import functools
def decorator(func):
def _check_something(*args, **kwargs):
# some logic in here
return func(*args, **kwargs)
return functools.wraps(func)(_check_something)
class MyClass(object):
@decorator
def my_method(foo, bar):
pass
我如何使用 unittest (unitttest2) 断言 my_method
有 @decorator
并且没有人删除它,并且它没有被遗忘?
最佳答案
如果由于某种原因您无法修 retrofit 饰器,您也可以尝试检查封闭变量的某些特征。
在您的示例中,您知道原始 my_method
是装饰器关闭的唯一变量,因此您可以:
assert (my_method.__closure__ and
my_method.__closure__[0].cell_contents.__name__ == my_method.__name__)
关于python - 如何断言一个方法是用 python unittest 装饰的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10012161/