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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 09:02:12  来源:igfitidea点击:

Python mock class instance variable

pythonunit-testingmocking

提问by clwen

I'm using Python's mocklibrary. 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.labelsin 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.labelsunder some_functionget the value I want. Any hints?

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

采纳答案by twil

This version of some_function()prints mocked labelsproperty:

此版本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.

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