Python模拟类实例变量 [英] Python mock class instance variable

查看:77
本文介绍了Python模拟类实例变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Python的mock库.我知道如何通过遵循文档来模拟类实例方法:

I'm using Python's mock library. I know how to mock a class instance method by following the 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):

However, tried to mock a class instance variable but doesn't work (instance.labels in the following example):

>>> 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'

基本上我希望some_function下的instance.labels得到我想要的值.有提示吗?

Basically I want instance.labels under some_function get the value I want. Any hints?

推荐答案

此版本的some_function()打印模拟的labels属性:

This version of some_function() prints mocked labels property:

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'

修补程序与您的修补程序相同:

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

完整的控制台会话:

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

对我来说,您的代码正在工作.

这篇关于Python模拟类实例变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆