gpt4 book ai didi

Python模拟类实例变量

转载 作者:太空狗 更新时间:2023-10-29 17:28:15 26 4
gpt4 key购买 nike

我正在使用 Python 的 mock 库。我知道如何通过遵循 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):

>>> 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 获得我想要的值。有什么提示吗?

最佳答案

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

完整的控制台 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]
>>>

对我来说,你的代码正在工作。

关于Python模拟类实例变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17731477/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com