Python模拟类实例变量

clw*_*wen 13 python unit-testing mocking

我正在使用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'
Run Code Online (Sandbox Code Playgroud)

但是,尝试模拟类实例变量但不起作用(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'
Run Code Online (Sandbox Code Playgroud)

基本上,我想instance.labelssome_function得到我想要的价值.任何提示?

twi*_*wil 19

这个版本的some_function()打印模拟了labels属性:

def some_function():
    instance = module.Foo()
    print instance.labels
    return instance.method()
Run Code Online (Sandbox Code Playgroud)

我的module.py:

class Foo(object):

    labels = [5, 6, 7]

    def method(self):
        return 'some'
Run Code Online (Sandbox Code Playgroud)

修补与您的相同:

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
Run Code Online (Sandbox Code Playgroud)

完整控制台会话:

>>> 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]
>>>
Run Code Online (Sandbox Code Playgroud)

对我来说,你的代码有效的.