【发布时间】:2016-05-31 18:55:23
【问题描述】:
我已经成功地用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.')
当其中任何一个被调用时,当前代码都会通过。
【问题讨论】:
标签: python unit-testing mocking