补丁没有嘲笑模块

时间:2017-03-21 19:36:10

标签: python unit-testing mocking

我试图模仿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

1 个答案:

答案 0 :(得分:2)

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

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

您需要修补导入Popen的位置,即在&#34;模块代码&#34;你写过这一行的地方:

from subprocess import Popen, PIPE

即,它应该看起来像:

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

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