我正在尝试模拟一个列表类型的全局变量。
下面是插图 -
这是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/