【发布时间】:2019-05-15 23:47:07
【问题描述】:
我正在尝试编写一个执行子进程调用的 python unittest,所以我想模拟该调用。
我已经解决了这些 SO 问题(无济于事):
- Mocking a subprocess call in Python
- mocking subprocess.Popen
- mocking subprocess.Popen dependant on import style
- Mocking two functions with patch for a unit test
benchmark.py
from subprocess import Popen, PIPE, STDOUT
def some_func():
with Popen(some_list, stdout=PIPE, stderr=STDOUT) as process:
stdout, stderr = process.communicate(timeout=timeout)
test.py
import mock
@mock.patch('benchmark.Popen.communicate')
@mock.patch('benchmark.Popen')
def test_some_func(self, mock_popen, mock_comm):
mock_popen.return_value = 0
mock_comm.return_value = ('output', 'error')
foo = benchmark.some_func()
运行单元测试时,我得到:
stdout, stderr = process.communicate(timeout=timeout)
ValueError: not enough values to unpack (expected 2, got 0)
看起来我没有正确地模拟communicate 的返回值;我做错了什么?
解决方案
我拿了 cmets 并提出了解决此类问题的建议答案:
test.py
import mock
@mock.patch('benchmark.Popen')
def test_some_func(self, mock_popen):
process = mock_popen.return_value.__enter__.return_value
process.returncode = 0
process.communicate.return_value = (b'some output', b'some error')
foo = benchmark.some_func()
【问题讨论】:
-
您需要模拟 上下文管理器,
process将是mock_popen.return_value.__enter__.return_value。 -
我尝试做同样的事情,但出现以下错误:AssertionError:
!= 0
标签: python unit-testing mocking