Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 236
Evgeny Avatar asked Apr 04 '12 13:04

Evgeny


2 Answers

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:

assert (my_method.__closure__ and 
           my_method.__closure__[0].cell_contents.__name__ == my_method.__name__)
like image 192
agf Avatar answered Oct 19 '22 12:10

agf


You can do that by relying on your decorator to mark the wrapper function with an attribute, that you then assert.

A good practice is to have the decorator set a __wrapped__ attribute pointing to the original function on the returned wrapper.

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'
like image 28
jsbueno Avatar answered Oct 19 '22 12:10

jsbueno