mocking subprocess.Popen

时间:2018-06-09 15:47:27

标签: python python-2.7 mocking subprocess

我有一个模块utils.py,它有这个run_cmd()方法

def run_cmd(cmd):
    pipe = subprocess.Popen(cmd,
                            shell=True,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE)
    print(pipe.communicate())
    print(pipe.returncode)
    stdout, stderr = [stream.strip() for stream in pipe.communicate()]
    output = ' - STDOUT: "%s"' % stdout if len(stdout) > 0 else ''
    error = ' - STDERR: "%s"' % stdout if len(stderr) > 0 else ''
    logger.debug("Running [{command}] returns: [{rc}]{output}{error}".format(
                 command=cmd,
                 rc=pipe.returncode,
                 output=output,
                 error=error))

    return pipe.returncode, stdout, stderr

我使用mock编写了一个单元测试,并将此链接stackoverflow作为参考

  @patch('subprocess.Popen')
  @patch('utils.logger.debug')
  def test_run_cmd(self, mock_popen, mock_log):
    cmd = 'mock_command'
    mocked_pipe = Mock()
    attrs = {'communicate.return_value': ('output', 'error'), 'returncode': 0}
    mocked_pipe.configure_mock(**attrs)
    mock_popen.return_value = mocked_pipe
    log_calls = [call('Running [mock_command] returns: [0]outputerror')]
    utils.run_cmd(cmd)
    mock_popen.assert_called_once_with(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    mock_log.assert_has_calls(log_calls)

当我运行nosetest时,我得到了这个输出

        stdout, stderr = [stream.strip() for stream in pipe.communicate()]
ValueError: need more than 0 values to unpack
-------------------- >> begin captured stdout << ---------------------
<MagicMock name='Popen().communicate()' id='140197276165008'>
<MagicMock name='Popen().returncode' id='140197276242512'>

--------------------- >> end captured stdout << ----------------------
FAILED (errors=1)

为什么pipe.communicate()不打印(&#39;输出&#39;,&#39;错误&#39;)或pipe.returncode不打印0,但是他们的模拟方法?哪里出错了?我怎么能解决这个问题?

1 个答案:

答案 0 :(得分:3)

啊,你已经回答了你的问题。仔细观察,你会知道为什么。你必须像对logger那样嘲笑。您在创建模拟对象时忘了提及utils

@patch('utils.subprocess.Popen')

现在,使用多个值模拟嵌套函数,我认为您应该查看side_effectshere

我没有测试过下面的代码,但我希望它能够起作用,或者至少能给你带来一些好处。

mocked_open.return_value.communicate.return_value = ('output', 'error')
mocked_open.return_value.returncode = 0

希望这会有所帮助!