我正在使用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.labels
下 some_function
得到我想要的价值。任何提示?
这个版本 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]
>>>
对我来说你的代码 是 加工。
这个版本 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]
>>>
对我来说你的代码 是 加工。