Python的模拟补丁另一个函数中的一个函数(Python mock patch a functio

2019-06-23 20:30发布

def f1():
    return 10, True

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

我如何使用Python的模拟库修补f1()并返回一个自定义的结果,所以我可以测试f2()

编辑:有什么错我的测试? 这似乎并不奏效,所有的测试失败的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 1:

第一示例表明,F1()和f2()相同的模块中定义。 因此,下面应该工作:

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('foo.bar.f1')

下面是对这个问题一个很好的答案:

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



Answer 2:

假设你正在使用这个模拟 libary:

def f1():
    return 10, True

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

import mock

print 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)

如果您的代码模块分为你可能需要更换__main__.f1的路径,以你的模块/功能。



文章来源: Python mock patch a function within another function