断言在特定实例上调用了 PropertyMock



我已经成功地用PropertyMock模拟了一个属性,但我无法弄清楚如何检查该类的哪个实例调用了该属性。如何断言在一个对象上调用了该属性,而不是在另一个对象上调用了该属性?

下面是一个示例,我想断言foo1.is_big被调用,而foo2.is_big不是:

from mock import PropertyMock, patch

class Foo(object):
    def __init__(self, size):
        self.size = size
    @property
    def is_big(self):
        return self.size > 5
f = Foo(3)
g = Foo(10)
assert not f.is_big
assert g.is_big
with patch('__main__.Foo.is_big', new_callable=PropertyMock) as mock_is_big:
    mock_is_big.return_value = True
    foo1 = Foo(4)
    foo2 = Foo(9)
    should_pass = False
    if should_pass:
        is_big = foo1.is_big
    else:
        is_big = foo2.is_big
    assert is_big
    # How can I make this pass when should_pass is True, and fail otherwise?
    mock_is_big.assert_called_once_with()
print('Done.')

当前代码将在调用其中任何一个时传递。

也许有更好的方法,但我通过创建一个 PropertyMock 子类来让它工作,该子类将调用它的实例记录为模拟调用的参数之一。

from mock import PropertyMock, patch

class Foo(object):
    def __init__(self, size):
        self.size = size
    @property
    def is_big(self):
        return self.size > 5

class PropertyInstanceMock(PropertyMock):
    """Like PropertyMock, but records the instance that was called."""
    def __get__(self, obj, obj_type):
        return self(obj)
    def __set__(self, obj, val):
        self(obj, val)

with patch("__main__.Foo.is_big", new_callable=PropertyInstanceMock) as mock_is_big:
    mock_is_big.return_value = True
    foo1 = Foo(4)
    foo2 = Foo(9)
    should_pass = False
    if should_pass:
        is_big = foo1.is_big
    else:
        is_big = foo2.is_big
    assert is_big
    # Now this passes when should_pass is True, and fails otherwise.
    mock_is_big.assert_called_once_with(foo1)
print("Done.")

最新更新