我最近开始在
python中使用mock框架.似乎如果我修补一个函数,实际的代码就不会被调用 – 这意味着这个实际函数所做的数据库更改等没有实现.
我一直试图通过先调用函数并存储返回值并将其作为arg传递给patch()来绕过它,但是
有更好的方法吗?理想情况下,我想要一个作为静默观察者的代码,我可以简单地询问它是否调用某个观察到的函数,多少次,以及什么参数
我目前的代码
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")
希望这可以帮助.