Python模拟类实例变量

27

我正在使用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'

基本上我想让some_function下的instance.labels得到我想要的值。有什么提示吗?
1个回答

33

这个版本的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]
>>>

对我来说,你的代码有效


1
它不起作用。我得到了与instance.labels = [1, 1, 2, 2]相同的结果,这意味着这个模拟变量没有被some_function使用。在文档中,它是模拟方法而不是变量。 - clwen
更新了我的回答。现在我迷失了,因为你的代码正在运行。 - twil
在我的代码中,labels 只会在调用某个函数后出现。而且这个函数是在我想要测试的函数内部被调用的。也许这就是原因。最终我选择模拟类的初始化,以便返回我想要的行为的模拟对象。 - clwen
我想在创建dule.Foo实例时引发异常。因此,我尝试了mock.side_effect和mock.return_value。但两者都没有起作用。为什么? - Hussain
这是一个不同的问题,我们无法查看任何代码,但我猜这个问题是你正在寻找的 https://dev59.com/kF4c5IYBdhLWcg3wHHGY - twil

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接