Python mock patch a function called by another function(Python mock 修补另一个函数调用的函数)
问题描述
def f1():
return 10, True
def f2():
num, stat = f1()
return 2*num, stat
如何使用 python 的模拟库修补 f1()
并返回自定义结果以便我可以测试 f2()
?
How do I use python's mock library to patch f1()
and return a custom result so I could test f2()
?
已我的测试有问题吗?这似乎不起作用,所有测试都因 AssertionError 而失败
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))
推荐答案
第一个例子表明 f1() 和 f2() 定义在同一个模块中.因此,以下应该有效:
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('foo.bar.f1')
这是一个很好的答案:
http://bhfsteve.blogspot.nl/2012/06/patching-tip-using-mocks-in-python-unit.html
这篇关于Python mock 修补另一个函数调用的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python mock 修补另一个函数调用的函数


基础教程推荐
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 筛选NumPy数组 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01