我正在编写一个创建subprocess.Popen
管道的程序。我试图模拟subprocess.Popen
以便每个调用返回一个不同的MagicMock
这样我就可以确保在管道中的特定(或所有(进程上调用方法。
我也希望这个模拟是基于subprocess.Popen
自动规范的,但不断收到一个错误,我无法基于模拟自动规范。
目前我的代码如下:
@pytest.fixture
def Popen(mocker: 'pytest_mock.MockFixture'):
def popen_factory(*args, **kwargs):
popen = mocker.MagicMock() # mocker.create_autospec(subprocess.Popen)
popen.stdin = open(os.devnull, "wb")
popen.stdout = open(os.devnull, "rb")
popen.wait.return_value = 0
return popen
Popen = mocker.patch.object(subprocess, 'Popen', autospec=True)
Popen.side_effect = popen_factory
yield Popen
由于mocker.patch.object(subprocess, 'Popen', autospec=True)
覆盖了subprocess.Popen
,我必须将现有值分配给局部变量,并改用它。
@pytest.fixture
def Popen(mocker: 'pytest_mock.MockFixture'):
real_Popen = subprocess.Popen
def popen_factory(*args, **kwargs):
popen = mocker.create_autospec(real_Popen)
popen.stdin = open(os.devnull, "wb")
popen.stdout = open(os.devnull, "rb")
popen.wait.return_value = 0
return popen
Popen = mocker.patch.object(subprocess, 'Popen', autospec=True)
Popen.side_effect = popen_factory
yield Popen