Python模拟类实例变量

时间:2013-07-18 18:42:48

标签: python unit-testing mocking

我正在使用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获得我想要的价值。任何提示?

1 个答案:

答案 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]
>>>

对我来说,你的代码正在工作。