补丁不模拟模块

发布于 2021-01-29 15:00:48

我想嘲笑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
关注者
0
被浏览
77
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

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

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

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

    from subprocess import Popen, PIPE
    

    即,它应该看起来像:

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

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



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看