python 流程模拟,在Python中模拟子流程调用

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.

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)

解决方案

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.

How about this:

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)

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值