如何在 Python 模拟中调用模拟方法

cba*_*are 3 python unit-testing mocking python-mock

我想创建一个模拟方法来调用被模拟的底层方法。

我正在想象类似以下内容,但我找不到任何关于持有对被模拟对象的引用的模拟对象的文档,我已将其表示[[wrapped_method_foo]]如下:

from mock import patch

class Foo(object):
    def __init__(self, state):
        self.state = state
    def foo(self, a):
        print "real foo", a
        return a + self.state

f = Foo(2000)
f.foo(1)

with patch.object(Foo, 'foo', autospec=True) as mock_foo:
    def side_effect(self, a):
        print "mock foo", a
        return mock_foo.[[wrapped_method_foo]](self, a*2)
    mock_foo.side_effect = side_effect

    f.foo(2)
Run Code Online (Sandbox Code Playgroud)

Eri*_*all 5

最简单的方法是在修补之前获取自己对原始函数的引用。可以在类的单个实例上进行修补:

original_foo = f.foo
with patch.object(f, 'foo') as mock_foo:
    def side_effect(a):
        print "mock foo", a
        return original_foo(a*2)
    mock_foo.side_effect = side_effect

    f.foo(2)
Run Code Online (Sandbox Code Playgroud)

...或通过修补类上的未绑定方法:

original_foo = Foo.foo
with patch.object(Foo, 'foo', autospec=True) as mock_foo:
    def side_effect(self, a):
        print "mock foo", a
        return original_foo(self, a*2)
    mock_foo.side_effect = side_effect

    f.foo(3)
Run Code Online (Sandbox Code Playgroud)