本文介绍了如何在Python模拟中调用模拟方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个模拟方法,该方法调用被模拟的基础方法.

I want to create a mock method that calls the underlying method being mocked.

我正在想象类似以下的内容,但是我找不到任何有关模拟对象的文档,其中包含对被模拟对象的引用,我在下面将其表示为[[wrapped_method_foo]]:

I'm imagining something like the following, but I can't find any documentation about the mock object holding a reference to the object being mocked, which I've denoted as [[wrapped_method_foo]] below:

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)

推荐答案

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

The simplest way is to grab your own reference to the original function before patching. Patching can be done on an individual instance of the class:

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)

...或通过对类的未绑定方法进行修补:

...or by patching the unbound method on the class:

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)

这篇关于如何在Python模拟中调用模拟方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 04:39