python - 如何模拟List类型的全局变量?

标签 python unit-testing mocking python-unittest

我正在尝试模拟一个列表类型的全局变量。

下面是插图 -

这是first_main.py -

url=[] -- url.append(hello.replace(-test','')) 的结果存储在此处,其中位于 method_a() 中,这是全局变量

def method_a():
    url.append(hello.replace(-test',''))
    return something

现在,url=[] 用于另一种方法中。

def method_b():
    *Some codes and url=[] is used here in this code.*
    print url
    return True

现在,我正在测试 method_b -

@mock.patch('first_main.url')
def test_method_b(self, mock_url_list):
    mock_url_list.return_value.url.return_value = [['a','b'],['c','d']]
    reponse = method_b()
    print response

现在,如果我为在 method_b 中使用的 url 放置一条打印语句,它应该返回 [['a','b' ],['c','d']] 而不是 id。

------------控制台------------

MagicMock name='url' id='090909090'

我想要列表中的 return_type ,即。 [['a','b'],['c','d']] 而不是 id。

谢谢

如果需要澄清,请告诉我。

最佳答案

mock.patch() 的默认行为是用 MagicMock 替换目标对象。因此 print url 将始终打印 MagicMock 实例。

但是,mock.patch() 支持 new_callable 参数,该参数允许您指定不同类型的对象。在您的情况下,您应该能够提供列表

@mock.patch('first_main.url', new_callable=list)
def test_method_b(self, mock_url_list):
    mock_url_list.extend([['a','b'],['c','d']])
    reponse = method_b()
    print response

请注意,在上面的示例中,您不需要使用 return_value 因为您没有使用模拟。您可以将 mock_url_list 作为列表进行操作。

patch 装饰器确保原始全局列表在测试完成后按原样放回原样。

关于python - 如何模拟List类型的全局变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48541863/

相关文章:

python - 如何创建在缩放时动态调整标记大小的 html 绘图

python - 需要从 lxml.etree 模块模拟 ElementTree 类的 write() 方法

python - 如何使用 python3 创建虚拟环境

Python:枚举值与命名单元

android - 使用改造和 Rx android 进行单元测试

java - 模拟接口(interface)存储库

unit-testing - 单元测试停止工作并停留在挂起状态 VS2012

unit-testing - 单元测试Web Api 2模拟用户

python - 如何模拟补丁 django 模型字段?

python - 尽管在 matplotlib 中设置了不可见轴,但 eps 图像中的幻影轴