Python mock:包装实例方法

时间:2017-06-26 20:51:51

标签: python-2.7 python-mock

我想要的是什么: 确保Foo语句中创建的with的所有实例都将foo实例方法通过wraps=Foo.foo包含在MagicMock中。我希望这样做的原因是,我可以针对创建的call_count的所有实例跟踪方法foo上的Foo。现在我说它似乎有点不可能......

>>> from mock import patch
...
... class Foo(object):
...
...     def foo(self):
...         return "foo"
...
... with patch("__main__.Foo.foo", wraps=Foo.foo) as m:
...     foo = Foo()
...     print(foo.foo())

Traceback (most recent call last):
  File "a.py", line 12, in <module>
    print(foo.foo())
  File "/disk/software/lib/python27/mock/mock.py", line 1062, in __call__
    return _mock_self._mock_call(*args, **kwargs)
  File "/disk/software/lib/python27/mock/mock.py", line 1132, in _mock_call
    return self._mock_wraps(*args, **kwargs)
TypeError: unbound method foo() must be called with Foo instance as first argument (got nothing instead)

问题 模拟的foo方法未绑定到通过foo创建的foo = Foo()实例,因为它包含未绑定的方法Foo.foo。有谁知道如何确保模拟方法绑定到实例?

我已经知道的事情:

>>> foo = Foo()
... with patch.object(foo, "foo", wraps=foo.foo) as m:
...     print(foo.foo())
"foo"

但这不符合我的约束,即必须在patch上下文中实例化对象。

2 个答案:

答案 0 :(得分:2)

我上面提出的错误解决方案存在问题

with patch("__main__.Foo.foo", wraps=Foo.foo) as m:
    ...

是对foo上的Foo方法进行了模拟,使其包装了未绑定方法Foo.foo,这自然不起作用,因为未绑定方法Foo.foo具有不知道稍后再调用它会附加到哪个实例。

我能想到的最简单的解决方案

from mock import patch, MagicMock

class Foo:

    def foo(self):
        return "foo"

class MockFoo(Foo):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # Every instance of MockFoo will now have its `foo` method 
        # wrapped in a MagicMock
        self.foo = MagicMock(wraps=self.foo)

with patch("__main__.Foo", MockFoo) as m:
    foo = Foo()
    print(foo.foo())
    assert foo.foo.call_count == 1

答案 1 :(得分:0)

这对 Python 模拟来说太糟糕了,所以我最终构建了一个自定义补丁实现(如果需要,可以扩展其他功能)。

import contextlib

class Patcher:
    UNCHANGED_RET = object()

    def __init__(self):
        self.call_count = 0
        self.return_value = Patcher.UNCHANGED_RET


@contextlib.contextmanager
def patch(klass, method_name):
    patcher = Patcher()
    orig_method = getattr(klass, method_name)

    def new_method(myself, *args, **kwargs):
        patcher.call_count += 1
        orig_return_value = orig_method(myself, *args, **kwargs)

        if patcher.return_value != Patcher.UNCHANGED_RET:
            return patcher.return_value

        return orig_return_value

    setattr(klass, method_name, new_method)
    yield patcher
    setattr(klass, method_name, orig_method)

使用如下:

class MyClass:
    def f(self):
        return 42


x = MyClass()
with patch(MyClass, 'f') as f_patcher:
    y = MyClass()  # inside or outside -- does not matter
    assert x.f() == 42
    assert f_patcher.call_count == 1
    f_patcher.return_value = 7
    assert y.f() == 7
    assert f_patcher.call_count == 2