在Python中模拟子流程调用 [英] Mocking a subprocess call in Python

查看:81
本文介绍了在Python中模拟子流程调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要测试的方法(run_script).具体来说,我想测试是否发生了对subprocess.Popen的调用.测试用特定参数调用subprocess.Popen甚至会更好.但是,当我运行测试时,我得到TypeError: 'tuple' object is not callable.

I have a method (run_script) would like to test. Specifically I want to test that a call to subprocess.Popenoccurs. It would be even better to test that subprocess.Popen is called with certain parameters. When I run the test however I get TypeError: 'tuple' object is not callable.

我如何测试我的方法以确保实际上使用模拟程序调用了 subprocess ?

How can I test my method to ensure that subprocess is actually being called using mocks?

@mock.patch('subprocess.Popen')
def run_script(file_path):
  process = subprocess.Popen(['myscript', -M, file_path], stdout=subprocess.PIPE)
  output,err = process.communicate()
  return process.returncode

def test_run_script(self, mock_subproc_popen):
  mock_subproc_popen.return_value = mock.Mock(communicate=('ouput','error'), returncode=0)
  am.account_manager("path")
  self.assertTrue(mock_subproc_popen.called)

推荐答案

在我看来,您在run_script函数上使用补丁装饰器是不寻常的,因为您没有在其中传递模拟参数.

It seems unusual to me that you use the patch decorator over the run_script function, since you don't pass a mock argument there.

如何?

def run_script(file_path):
  process = subprocess.Popen(['myscript', -M, file_path], stdout=subprocess.PIPE)
  output,err = process.communicate()
  return process.returncode

@mock.patch('subprocess.Popen')
def test_run_script(self, mock_subproc_popen):
  process_mock = mock.Mock()
  attrs = {'communicate.return_value': ('output', 'error')}
  process_mock.configure_mock(**attrs)
  mock_subproc_popen.return_value = process_mock 
  am.account_manager("path") # this calls run_script somewhere, is that right?
  self.assertTrue(mock_subproc_popen.called)

现在,模拟的子进程.Popen似乎返回一个元组,从而导致process.communicate()提高TypeError: 'tuple' object is not callable..因此,最重要的一点是要正确地对ock_subproc_popen的return_value赋值.

Right now, your mocked subprocess.Popen seems to return a tuple, causeing process.communicate() to raise TypeError: 'tuple' object is not callable.. Therefore it's most important to get the return_value on mock_subproc_popen just right.

这篇关于在Python中模拟子流程调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆