How can I mock / fix a decorator in python?

Temporary solution:

I was unable to fix the decorator and still have access to the wrapped function. but the workaround for checking the function wrapped in the decorator was the following:

def un_some_method(self):
...

some_method = some_var.some_decorator('somestring')(un_some_method)    

This still decorates my function, but gives me access to the function, if I want to test it, reuse it elsewhere ...

This is the problem:

I have a module in which there is a class, and variables that create an instance of the class that exposes the decorator.

Then inside the class inside my module, I use this variable with an instance of my class and decorate the method in my class ... To be clear, let's look at some code:

some_var = ClassX()

class SomeClass(object):

    @some_var.some_decorator('somestring')
    def some_method(self):
        ...

some_method, ... ... , :

@patch('path_to_classx.ClassX.some_decorator')
@patch('path_to_someclassmodule.some_var')
@patch('path_to_someclassmodule.ClassX')

... , ?

+4
1

some_var , some_decorator , .

import mock
class ClassX(object):
    def some_decorator(self, f):
        def g(*args, **kwargs):
            print("Hello")
            return f(*args, **kwargs)
        return g

some_var = ClassX()

with mock.patch.object(some_var, 'some_decorator', side_effect=lambda f: f):

    class SomeClass(object):
        @some_var.some_decorator
        def some_method(self):
            print "World"


SomeClass().some_method()
+2

Source: https://habr.com/ru/post/1619216/


All Articles