Skip to main content
 首页 » 编程设计

python之补丁不模拟模块

2024年10月01日6lhb25

我正在尝试模拟 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 .