小编Har*_*ddy的帖子

模拟子进程.Popen

我有一个模块 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
Run Code Online (Sandbox Code Playgroud)

我使用模拟和此链接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': …
Run Code Online (Sandbox Code Playgroud)

python subprocess mocking python-2.7

3
推荐指数
1
解决办法
4377
查看次数

标签 统计

mocking ×1

python ×1

python-2.7 ×1

subprocess ×1