Python 模拟类实例变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17731477/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python mock class instance variable
提问by clwen
I'm using Python's mock
library. I know how to mock a class instance method by following the document:
我正在使用 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'
However, tried to mock a class instance variable but doesn't work (instance.labels
in the following example):
但是,尝试模拟类实例变量但不起作用(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'
Basically I want instance.labels
under some_function
get the value I want. Any hints?
基本上,我想instance.labels
下some_function
得到我想要的价值。任何提示?
采纳答案by twil
This version of some_function()
prints mocked labels
property:
此版本some_function()
打印模拟labels
属性:
def some_function():
instance = module.Foo()
print instance.labels
return instance.method()
My module.py
:
我的module.py
:
class Foo(object):
labels = [5, 6, 7]
def method(self):
return 'some'
Patching is the same as yours:
修补程序与您的相同:
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
Full console session:
完整的控制台会话:
>>> 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]
>>>
For me your code isworking.
对我来说,您的代码正在运行。