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

标签 python unit-testing mocking

我已经成功地用 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.")

关于python - 断言在特定实例上调用了 PropertyMock,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37553552/

相关文章:

unit-testing - 摆脱子组件对象的 'new' 运算符

javascript - Jest 模拟未覆盖函数或返回错误

java - Mockito:如何部分使用 @InjectMocks-Annotation 进行 MockMvc 测试?

javascript - 单元测试 Javascript Web worker 。并在 Web Worker 中模拟 http 调用

python - 使用正则表达式解析 winerror.h 和 ntstatus.h 状态/定义

python - 如何从字典列表中删除 ('u' )unicode?

asp.net-mvc-3 - MVC .NET 单元测试 : how to test arguments are sent to view from controller

c# - 更改生成的单元测试文件的目录

python - 如何将时间戳插入 GQL DateTimeProperty() 中?

python - 使用python的线性支持向量机中的软边距