本文介绍了补丁不模拟模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to mock subprocess.Popen. When I run the following code however, the mock is completely ignored and I'm not sure why

测试代码:

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")


模块代码:


Module Code:

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的位置修补:

You're not patching in the right place. You patch where Popen is defined:

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

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

You need to patch where Popen is imported, i.e. in the "Module Code" where you have written this line:

from subprocess import Popen, PIPE

即,它看起来应该像这样:

I.e., it should look something like:

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

要获得快速指南,请阅读文档中的部分:在哪里修补.

For a quick guide, read the section in the docs: Where to patch.

这篇关于补丁不模拟模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 20:49