Python mock patch a function called by another function Python mock patch a function called by another function python python

Python mock patch a function called by another function


First example suggests that f1() and f2() defined in the same module. Hence the following should work:

from foo.bar import f2from mock import patchclass MyTest(TestCase):    @patch('foo.bar.f1')    def test_f2_2(self, some_func):        some_func.return_value = (20, False)        num, stat = f2()        self.assertEqual((num, stat), (40, False))

Patch is on the same as import: @patch('foo.bar.f1')

Here is a good answer on the issue:

http://bhfsteve.blogspot.nl/2012/06/patching-tip-using-mocks-in-python-unit.html


Assuming that you're using this mock libary:

def f1():    return 10, Truedef f2():    num, stat = f1()    return 2*num, statimport mockprint f2()   # Unchanged f1 -> prints (20, True)with mock.patch('__main__.f1') as MockClass:       # replace f1 with MockClass     MockClass.return_value = (30, True)     # Change the return value    print f2()     # f2 with changed f1 -> prints (60, True)

If your code is divided into modules you would probably need to replace __main__.f1 with the path to your module/function.