小编典典

补丁不模拟模块

python

我想嘲笑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

阅读 198

收藏
2021-01-20

共1个答案

小编典典

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

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

您需要修补Popen导入的位置,即在编写此行的“模块代码”中:

from subprocess import Popen, PIPE

即,它应该看起来像:

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

要获得快速指南,请阅读文档中的部分:修补位置

2021-01-20