我最近开始使用 python 中的模拟框架。似乎如果我修补一个函数,则不会调用实际代码 - 这意味着该实际函数所做的数据库更改等未实现。
我一直试图通过预先调用该函数并存储返回值并将其作为 arg 在 patch() 中传递来绕过它,但是
有更好的方法吗?理想情况下,我想要一个可以作为silent observer
我可以简单地询问它是否有某个observed
函数是否被调用、调用了多少次以及使用了什么参数
我当前的代码
return_val = funct()
# C: Now call me again and assert that these intensive computation functions are not called but taken from cache
with patch('funct', return_value=return_val) as mock_task:
me_response = self.client.get(me_url, format='json') #should fetch from cache
assert not mock_task.called
要模拟调用的方法,您应该使用wraps关键词。考虑以下:
class Foo(object):
def do_thing(self, a):
print("A: %s" % a)
self._do_private_thing(a)
def _do_private_thing(self, a):
print("PRIVATE STUFF HAPPENING.")
print("A: %s" % a)
然后在你的测试中你会得到类似的东西:
import mock
a = Foo()
with mock.patch.object(a, '_do_private_thing', wraps=a._do_private_thing) as private_mock:
a.do_thing("lol")
private_mock.assert_called_with("lol")
希望这可以帮助。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)