Python: 如何在不替换原方法的情况下测试一个方法被调用了多少次?

Python: How to test how many times a method is called without replacing the original method?

这是一个过于简化的例子:

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