python MagicMock返回值不返回元组?

时间:2017-01-11 08:20:47

标签: python testing mocking

我进行了快速测试,看看是否有效......

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

似乎像我预期的那样工作,然后我尝试在我的测试中修补这样的东西......

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

在command.download中,代码看起来像这样......

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

我的第一个猜测是我正在修补错误的命名空间,但是当我打印communicate()时,我看到了这个......

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

这意味着它正在被嘲笑,但它只是没有注册我的新返回值进行沟通......我不知道从哪里开始。

1 个答案:

答案 0 :(得分:2)

您在communicate上致电process,这是Popen的返回值。所以你需要在该补丁调用中使用另一个级别:

m_Popen.return_value.communicate.return_value = (0, 0)