我想测试一个函数,它调用subprocess.Popen
并捕获stdout
.特别是,我需要测试stdout
个物理捕获在磁盘上的文件中的内容,而无需调用实际的进程.
示例函数:
import subprocess
def func():
with open('stdout.txt', 'wt') as out:
subprocess.Popen(_cmdline(), stdout=out)
def _cmdline() -> list[str]:
# Or whatever process we want to run
return ['ls']
测试功能:
from unittest import mock
def test_captures_stdout():
with mock.patch('subprocess.Popen') as mock_popen:
func()
# Try to intercept stdout and write to it
[(_, kwargs)] = mock_popen.call_args_list
with kwargs['stdout']:
buf.write('some standard output')
with open('stdout.txt') as buf:
assert buf.read() == 'some standard output'
在这里,我模拟subprocess.Popen
,然后拦截传递给它的构造函数的stdout
,并try 写入缓冲区.然后,我打算对stdout.txt
文件的内容运行断言.
显然,当我try 写入stdout
缓冲区时,它已经关闭,并且我收到IO错误.
================================== FAILURES ===================================
____________________________ test_captures_stdout _____________________________
def test_captures_stdout():
with mock.patch('subprocess.Popen') as mock_popen:
func()
# Try to intercept stdout and write to it
[(_, kwargs)] = mock_popen.call_args_list
> with kwargs['stdout']:
E ValueError: I/O operation on closed file.
test_subprocess.py:22: ValueError
=========================== short test summary info ===========================
我想知道是否有一种方便的方法来模拟Popen
并以某种方式模拟写入到文件中的stdout
.