我正在编写一个创建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
答案 0 :(得分:0)
由于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