Python:如何在不替换原始方法的情况下测试方法的调用次数?

问题描述 投票:0回答:2

这是一个简单的例子:

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()来保留其原始功能。

python python-unittest
2个回答
1
投票

未经测试但这应该让你开始(好吧,这个确切的片段未经测试 - 我做过类似的黑客工作正常):

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

0
投票

我最终使用了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
© www.soinside.com 2019 - 2024. All rights reserved.