Max recursion depth while trying to mock instance method

Viewed 3645

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(data):
        print(data)

def wrapped_method(data):
    return Foo.my_method(data.replace('x', 'o'))

with mock.patch.object(Foo, 'my_method', wraps=wrapped_method):
    foo = Foo()
    foo.my_method('axe')  # should print "aoe"

But I get this exception:

/home/foo/bin/python /home/foo/src/wrap-instance-method.py
Traceback (most recent call last):
  File "/home/foo/src/wrap-instance-method.py", line 15, in <module>
    foo.my_method('axe')  # should print "aoe"
  File "/home/foo/local/lib/python2.7/site-packages/mock.py", line 955, in __call__
    return _mock_self._mock_call(*args, **kwargs)
  File "/home/foo/local/lib/python2.7/site-packages/mock.py", line 1024, in _mock_call
    return self._mock_wraps(*args, **kwargs)
.....
    return self._mock_wraps(*args, **kwargs)
  File "/home/foo/src/wrap-instance-method.py", line 10, in wrapped_method
    return Foo.my_method(data.replace('x', 'o'))
  File "/home/foo/local/lib/python2.7/site-packages/mock.py", line 955, in __call__
    return _mock_self._mock_call(*args, **kwargs)
  File "/home/foo/local/lib/python2.7/site-packages/mock.py", line 960, in _mock_call
    self.called = True
RuntimeError: maximum recursion depth exceeded while calling a Python object

Process finished with exit code 1

How can I call the original method which was wrapped without recursion exception?

2 Answers

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):
    ...
Related