[Solved]-How to mock in python and still allow the actual code of mocked function to execute

5👍

You could set the Mock#side_effect attribute to your original function.

orig = funct
funct = Mock(side_effect=orig)

I do find loganasherjones’ answer more elegant.

Just adding another possibility for those who may need it.

13👍

To mock a method called, you should use the wraps keyword. Consider the following:

class Foo(object):

    def do_thing(self, a):
        print("A: %s" % a)
        self._do_private_thing(a)

    def _do_private_thing(self, a):
        print("PRIVATE STUFF HAPPENING.")
        print("A: %s" % a)

Then In your test you would have something like:

import mock
a = Foo()
with mock.patch.object(a, '_do_private_thing', wraps=a._do_private_thing) as private_mock:
    a.do_thing("lol")
    private_mock.assert_called_with("lol")

Hope this helps.

Leave a comment