-
Notifications
You must be signed in to change notification settings - Fork 0
/
pytest_stubprocess.py
70 lines (54 loc) · 1.48 KB
/
pytest_stubprocess.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# -*- coding: utf-8 -*-
import multiprocessing
import os
import sys
import attr
import pytest
@pytest.fixture
def stubprocess(mocker):
return Registry(mocker.patch('_posixsubprocess.fork_exec'))
@attr.s
class Registry:
_mock_fork_exec = attr.ib()
_executables = attr.ib(default=attr.Factory(dict))
_processes = attr.ib(default=attr.Factory(dict))
def __attrs_post_init__(self):
self._mock_fork_exec.side_effect = self._fork_exec
def register(self, name, executable):
self._executables[name] = executable
def _fork_exec(
self,
args,
executable_list,
close_fds,
fds_to_keep,
cwd,
env,
p2cread,
p2cwrite,
c2pread,
c2pwrite,
errread,
errwrite,
errpipe_read,
errpipe_write,
restore_signals,
call_setsid,
preexec_fn,
):
name = args[0]
try:
executable = self._executables[name]
except KeyError:
# TODO(): pass correct args
raise FileNotFoundError
def run():
if c2pwrite >= 0:
sys.stdout = os.fdopen(c2pwrite, mode='w', closefd=False)
if errwrite >= 0:
sys.stderr = os.fdopen(errwrite, mode='w', closefd=False)
executable(args)
process = multiprocessing.Process(target=run)
process.start()
self._processes[process.pid] = process
return process.pid