我有一个模块 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)