Python mock 修补另一个函数调用的函数
- 作者: 我叫常冰川10319618
- 来源: 51数据库
- 2022-10-20
问题描述
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
推荐阅读
热点文章
Discord.py(重写)on_member_update 无法正常工作
0
Discord.py 在 vc 中获取用户分钟数
0
discord.py 重写 |为我的命令出错
0
Discord.py rewrite 如何 DM 命令?
0
播放音频时,最后一部分被切断.如何解决这个问题?(discord.py)
0
在消息删除消息 Discord.py
0
如何使 discord.py 机器人私人/直接消息不是作者的人?
0
(Discord.py) 如何获取整个嵌入内容?
0
Discord bot 尽管获得了许可,但不能提及所有人
0
Discord.py discord.NotFound 异常
0
