Skip to content Skip to sidebar Skip to footer

Max Recursion Depth While Trying To Mock Instance Method

I want to mock an instance method. First I want to modify the arguments and then I want to call the original method. I tried this: import mock class Foo(object): def my_method

Solution 1:

You replaced the Foo.my_method with a method that calls Foo.my_method, so yes, you'll get an infinite recursion.

If you must have the original method, you need to store it before you patch it:

def mock_method_factory(original):
    def wrapped_method(data):
        return original(data.replace('x', 'o'))
    return wrapped_method

with mock.patch.object(Foo, 'my_method', wraps=mock_method_factory(Foo.my_method)):
    # ...

However, wraps does not handle binding; original is an unbound function and wrapped_method won't be passed in self.

The mock library is perhaps not the best choice here. What you are essentially doing is apply a temporary decorator. Either subclass Foo or apply the decorator manually to Foo.my_method:

def mock_method_factory(original):
    def wrapped_method(self, data):
        return original(self, data.replace('x', 'o'))
    return wrapped_method

class MockedFoo(Foo):
    my_method = mock_method_factory(Foo.my_method)

foo = MockedFoo()
foo.my_method('axe')  # should print "aoe"

or

def mock_method_factory(original):
    def wrapped_method(self, data):
        return original(self, data.replace('x', 'o'))
    return wrapped_method

original = Foo.my_method
try:
    Foo.my_method = mock_method_factory(original)
    foo = Foo()
    foo.my_method('axe')  # should print "aoe"
finally:
    Foo.my_method = original

Solution 2:

I encountered the same issue. Tried with Martijn's solution, but had the self problem. Solved by the following:

real_constructor = CLASS_NAME.__init__
def mock_constructor(self, **args):
    return real_constructor.(self=self, **args)

with mock.patch.object(Foo, '__init__', side_effect=mock_constructor):
    ...

Post a Comment for "Max Recursion Depth While Trying To Mock Instance Method"