这是一个简单的例子:
class Foo:
def say_it(self):
return self.say()
def say(self):
print("Hello!")
return 123
def test_call_count():
with patch("Foo.say") as say_call:
amount = Foo().say_it()
assert amount == 123
assert say_call.call_count == 1
我需要.say()
来保留其原始功能。
未经测试但这应该让你开始(好吧,这个确切的片段未经测试 - 我做过类似的黑客工作正常):
def test_call_count():
real_say = Foo.say.im_func
call_count = [0]
def patched_say(self, *args, **kw):
call_count[0] += 1
return real_say(self, *args, **kw)
Foo.say = patched_say
amount = Foo().say_it()
Foo.say = real_say
assert amount == 123
assert call_count[0] == 1
我最终使用了wraps=...
论证:
class Foo:
def say_it(self):
self.say()
def say(self):
print("Hello!")
return 123
def test_call_count():
with patch("Foo.say", wraps=Foo.say) as say_call:
amount = Foo().say_it()
assert amount == 123
assert say_call.call_count == 1