我正在使用Python的mock
库。我知道如何通过遵循document:
>>> def some_function():
... instance = module.Foo()
... return instance.method()
...
>>> with patch('module.Foo') as mock:
... instance = mock.return_value
... instance.method.return_value = 'the result'
... result = some_function()
... assert result == 'the result'
但是,尝试模拟类实例变量但不起作用(在以下示例中为instance.labels
):
>>> with patch('module.Foo') as mock:
... instance = mock.return_value
... instance.method.return_value = 'the result'
... instance.labels = [1, 1, 2, 2]
... result = some_function()
... assert result == 'the result'
基本上我希望instance.labels
下的some_function
获得我想要的价值。任何提示?
答案 0 :(得分:18)
此some_function()
版本打印模拟labels
属性:
def some_function():
instance = module.Foo()
print instance.labels
return instance.method()
我的module.py
:
class Foo(object):
labels = [5, 6, 7]
def method(self):
return 'some'
补丁与你的相同:
with patch('module.Foo') as mock:
instance = mock.return_value
instance.method.return_value = 'the result'
instance.labels = [1,2,3,4,5]
result = some_function()
assert result == 'the result
完整的控制台会话:
>>> from mock import patch
>>> import module
>>>
>>> def some_function():
... instance = module.Foo()
... print instance.labels
... return instance.method()
...
>>> some_function()
[5, 6, 7]
'some'
>>>
>>> with patch('module.Foo') as mock:
... instance = mock.return_value
... instance.method.return_value = 'the result'
... instance.labels = [1,2,3,4,5]
... result = some_function()
... assert result == 'the result'
...
...
[1, 2, 3, 4, 5]
>>>
对我来说,你的代码正在工作。