21

我正在使用 Python 的mock库。我知道如何通过遵循文档来模拟类实例方法:

>>> 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.labelssome_function价值。有什么提示吗?

4

1 回答 1

28

此版本的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]
>>>

对我来说,您的代码正在运行。

于 2013-07-18T19:08:09.633 回答