gpt4 book ai didi

python - 补丁不模拟模块

转载 作者:太空宇宙 更新时间:2023-11-04 02:54:13 24 4
gpt4 key购买 nike

我正在尝试模拟 subprocess.Popen。但是,当我运行以下代码时,模拟被完全忽略,我不确定为什么

测试代码:

def test_bring_connection_up(self):
# All settings should either overload the update or the run method
mock_popen = MagicMock()
mock_popen.return_value = {'communicate': (lambda: 'hello','world')}
with patch('subprocess.Popen', mock_popen):
self.assertEqual(network_manager.bring_connection_up("test"), "Error: Unknown connection: test.\n")

模块代码:

from subprocess import Popen, PIPE
# ........
def list_connections():
process = Popen(["nmcli", "-t", "-fields", "NAME,TYPE", "con", "list"], stdout=PIPE, stderr=PIPE)
stdout, stderr = process.communicate() # <--- Here's the failure
return stdout

最佳答案

你没有在正确的地方打补丁。您在定义 Popen 的地方打补丁:

with patch('subprocess.Popen', mock_popen):

您需要在导入 Popen 的地方打补丁,即在您编写此行的“模块代码”中:

from subprocess import Popen, PIPE

即,它应该看起来像:

with patch('myapp.mymodule.Popen', mock_popen):

有关快速指南,请阅读文档中的部分:Where to patch .

关于python - 补丁不模拟模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42936606/

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