简体   繁体   English

如何断言一个方法是用 python unittest 装饰的?

[英]How to assert that a method is decorated with python unittest?

I have a decorator and I want to assert that certain methods in my code are decorated with it.我有一个装饰器,我想断言我代码中的某些方法是用它装饰的。

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

How do I assert with unittest (unitttest2) that my_method has @decorator and no-one removed it, and it was not forgotten?我如何用 unittest (unitttest2) 断言my_method@decorator并且没有人删除它,而且它没有被遗忘?

If for some reason you can't modify the decorator, you could also try checking for some characteristic of a closed variable.如果由于某种原因您无法修改装饰器,您也可以尝试检查封闭变量的某些特征。

In your example, you know that the original my_method is the only variable closed by the decorator, so you could:在您的示例中,您知道原始my_method是装饰器关闭的唯一变量,因此您可以:

assert (my_method.__closure__ and 
           my_method.__closure__[0].cell_contents.__name__ == my_method.__name__)

You can do that by relying on your decorator to mark the wrapper function with an attribute, that you then assert.您可以依靠您的装饰器使用一个属性标记包装器 function 来做到这一点,然后您声明该属性。

A good practice is to have the decorator set a __wrapped__ attribute pointing to the original function on the returned wrapper.一个好的做法是让装饰器在返回的包装器上设置一个指向原始 function 的__wrapped__属性。

thus:因此:

def decorator(func):
    @functools.wraps(func)
    def _check_something(*args, **kwargs):
        # some logic in here
        return func(*args, **kwargs)
    _check_something.__wrapped__ = func   # <== add this
    return _check_something

and then, on your test code:然后,在您的测试代码上:

assert getattr(MyClass.my_method, "__wrapped__").__name__ == 'my_method'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM