Python mock patch a function within another function

Nam Ngo picture Nam Ngo · Apr 23, 2012 · Viewed 47.7k times · Source
def f1():
    return 10, True

def f2():
    num, stat = f1()
    return 2*num, stat

How do I use python's mock library to patch f1() and return a custom result so I could test f2()?

Edited: Is there something wrong with my test? This doesn't seem to be working, all the tests failed with AssertionError

from foo.bar import f2
from mock import patch

class MyTest(TestCase):

    def test_f2_1(self):
        with patch('project.module.f1') as some_func:
            some_func.return_value = (20, False)
            num, stat = f2()
            self.assertEqual((num, stat), (40, False))

   @patch('project.module.f1')
   def test_f2_2(self, some_func):
       some_func.return_value = (20, False)
       num, stat = f2()
       self.assertEqual((num, stat), (40, False))

Answer

Vasiliy picture Vasiliy · Mar 15, 2015

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

from foo.bar import f2
from mock import patch

class 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