简体   繁体   English

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

[英]How to call mocked method in Python mock

I want to create a mock method that calls the underlying method being mocked. 我想创建一个模拟方法,该方法调用被模拟的基础方法。

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: 我正在想象类似以下的内容,但是找不到关于模拟对象的文档,其中包含对被模拟对象的引用,在下面将其表示为[[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)

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)

patch objects have an undocumented temp_original attribute that you can use. 修补程序对象具有可以使用的未记录的temp_original属性。

Here is what I usually do in that case: 在这种情况下,我通常会这样做:

from __future__ import print_function
import mock

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)

fake_foo = mock.patch.object(Foo, 'foo', autospec=True)
# def side_effect(*args, **kwargs):  # generic version
def side_effect(self, a):
    print("mock foo", a)
    return fake_foo.temp_original(self, a*2)

with fake_foo as mock_foo:
    mock_foo.side_effect = side_effect

    assert f.foo(2) == 2004

I'm using this when I only use mock to assert that functions where called during tests 当我仅使用模拟来断言在测试期间调用的函数时,我正在使用此函数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM