cjds
cjds

Reputation: 8426

Patch not mocking a module

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

Test Code:

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

Upvotes: 2

Views: 474

Answers (1)

wim
wim

Reputation: 362717

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

with patch('subprocess.Popen', mock_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.

Upvotes: 2

Related Questions