Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 断言对特定实例调用了PropertyMock_Python_Unit Testing_Mocking - Fatal编程技术网

Python 断言对特定实例调用了PropertyMock

Python 断言对特定实例调用了PropertyMock,python,unit-testing,mocking,Python,Unit Testing,Mocking,我已经成功地用PropertyMock模拟了一个属性,但是我不知道如何检查类的哪个实例调用了该属性。我如何断言该属性是在一个对象上调用的,而不是在另一个对象上调用的 下面是一个示例,我想断言调用了foo1.is\u big,而foo2.is\u big没有: from mock import PropertyMock, patch class Foo(object): def __init__(self, size): self.size = size @p

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

下面是一个示例,我想断言调用了
foo1.is\u big
,而
foo2.is\u 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 3.6.2
@mock.patch(“object.property”,new\u callable=mock.PropertyMock)
中,这对我来说很有用,@sonance207,但是你怎么知道
对象的哪个实例调用了它的属性呢?所以我发现我无法测试@property函数返回的模拟对象;只有当它被访问时。因此,我最终执行了与测试属性访问相同的模拟上下文测试,以及另一个测试从属性返回的模拟对象,因为我希望避免分配返回值。