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))
答案 0 :(得分:19)
假设你正在使用这个mock图书馆:
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
替换为模块/函数的路径。
答案 1 :(得分:19)
第一个例子表明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