如何模拟列表类型的全局变量?

How to mock global variable of List Type?

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

下面是插图 -

这是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 的打印语句,它应该 return 我 [['a','b'],['c','d']] 而不是 id。

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

MagicMock name='url' id='090909090'

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

谢谢

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

提供答案-

无需嘲笑。只需导入模块并更改 setUp():

中的全局值

参考下面给出的link-

谢谢:)

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

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

@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装饰器确保原始全局列表在测试完成后恢复原状。