2

I ran a quick test to see if something would work...

>>> from unittest.mock import MagicMock
>>> x = MagicMock()
>>> x.func.return_value = (0, 0)
>>> y, z = x.func()

seems to work like I expected, and then I try to patch something in my tests like this...

def setUp(self):
    """Setting up the command parameters"""
    self.command = up.Command()
    self.command.stdout = MagicMock()
    self.command.directory = '{}/../'.format(settings.BASE_DIR)
    self.command.filename = 'test_csv.csv'

@patch('module.Popen')
@patch('module.popen')
def test_download(self, m_popen, m_Popen):
    """Testing that download calls process.communicate"""
    m_Popen.communicate.return_value = (0, 0)
    self.command.download()
    m_popen.assert_called()
    m_Popen.communicate.assert_called()

in command.download, the code looks like this...

command = 'wget --directory-prefix=%s \
        https://www.phoenix.gov/OpenDataFiles/Crime%%20Stats.csv' \
        % self.directory
process = Popen(command.split(), stdin=PIPE, stdout=PIPE)
print(process.communicate())
stdout, stderr = process.communicate()

my first guess would be that I was patching the wrong namespace, but when I print communicate() I see this...

<MagicMock name='mock().communicate()' id='4438712160'>

which means that it is getting mocked, but it is just not registering my new return value for communicate...I don't know where to go from here.

1 Answer 1

3

You call communicate on process, which is the return value of Popen. So you need another level in that patch call:

m_Popen.return_value.communicate.return_value = (0, 0)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, seems obvious now

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.