Debian Codegraph @

tests/_util.py

raw
1 import os
2 import sys
3 from io import BytesIO
4 from functools import wraps
5
6 try:
7 import termios
8 except ImportError:
9 # Not available on Windows
10 termios = None
11 from contextlib import contextmanager
12
13 from unittest.mock import patch, Mock
14 from pytest import skip
15 from pytest_relaxed import trap
16
17 from invoke import Program, Runner
18 from invoke.terminals import WINDOWS
19
20
21 support = os.path.join(os.path.dirname(__file__), "_support")
22 ROOT = os.path.abspath(os.path.sep)
23
24
25 def skip_if_windows(fn):
26 @wraps(fn)
27 def wrapper(*args, **kwargs):
28 if WINDOWS:
29 skip()
30 return fn(*args, **kwargs)
31
32 return wrapper
33
34
35 @contextmanager
36 def support_path():
37 sys.path.insert(0, support)
38 try:
39 yield
40 finally:
41 sys.path.pop(0)
42
43
44 def load(name):
45 with support_path():
46 imported = __import__(name)
47 return imported
48
49
50 def support_file(subpath):
51 with open(os.path.join(support, subpath)) as fd:
52 return fd.read()
53
54
55 @trap
56 def run(invocation, program=None, invoke=True):
57 """
58 Run ``invocation`` via ``program``, returning output stream captures.
59
60 ``program`` defaults to ``Program()``.
61
62 To skip automatically assuming the argv under test starts with ``"invoke
63 "``, say ``invoke=False``.
64
65 :returns: Two-tuple of ``stdout, stderr`` strings.
66 """
67 if program is None:
68 program = Program()
69 if invoke:
70 invocation = "invoke {}".format(invocation)
71 program.run(invocation, exit=False)
72 return sys.stdout.getvalue(), sys.stderr.getvalue()
73
74
75 def expect(
76 invocation, out=None, err=None, program=None, invoke=True, test=None
77 ):
78 """
79 Run ``invocation`` via ``program`` and expect resulting output to match.
80
81 May give one or both of ``out``/``err`` (but not neither).
82
83 ``program`` defaults to ``Program()``.
84
85 To skip automatically assuming the argv under test starts with ``"invoke
86 "``, say ``invoke=False``.
87
88 To customize the operator used for testing (default: equality), use
89 ``test`` (which should be an assertion wrapper of some kind).
90 """
91 stdout, stderr = run(invocation, program, invoke)
92 # Perform tests
93 if out is not None:
94 if test:
95 test(stdout, out)
96 else:
97 assert out == stdout
98 if err is not None:
99 if test:
100 test(stderr, err)
101 else:
102 assert err == stderr
103 # Guard against silent failures; since we say exit=False this is the only
104 # real way to tell if stuff died in a manner we didn't expect.
105 elif stderr:
106 assert False, "Unexpected stderr: {}".format(stderr)
107 return stdout, stderr
108
109
110 class MockSubprocess:
111 def __init__(self, out="", err="", exit=0, isatty=None, autostart=True):
112 self.out_file = BytesIO(out.encode())
113 self.err_file = BytesIO(err.encode())
114 self.exit = exit
115 self.isatty = isatty
116 if autostart:
117 self.start()
118
119 def start(self):
120 # Start patchin'
121 self.popen = patch("invoke.runners.Popen")
122 Popen = self.popen.start()
123 self.read = patch("os.read")
124 read = self.read.start()
125 self.sys_stdin = patch("sys.stdin", new_callable=BytesIO)
126 sys_stdin = self.sys_stdin.start()
127 # Setup mocks
128 process = Popen.return_value
129 process.returncode = self.exit
130 process.stdout.fileno.return_value = 1
131 process.stderr.fileno.return_value = 2
132 # If requested, mock isatty to fake out pty detection
133 if self.isatty is not None:
134 sys_stdin.isatty = Mock(return_value=self.isatty)
135
136 def fakeread(fileno, count):
137 fd = {1: self.out_file, 2: self.err_file}[fileno]
138 return fd.read(count)
139
140 read.side_effect = fakeread
141 # Return the Popen mock as it's sometimes wanted inside tests
142 return Popen
143
144 def stop(self):
145 self.popen.stop()
146 self.read.stop()
147 self.sys_stdin.stop()
148
149
150 def mock_subprocess(out="", err="", exit=0, isatty=None, insert_Popen=False):
151 def decorator(f):
152 @wraps(f)
153 # We have to include a @patch here to trick pytest into ignoring
154 # the wrapped test's sometimes-there, sometimes-not mock_Popen arg. (It
155 # explicitly "skips ahead" past what it perceives as patch args, even
156 # though in our case those are not applying to the test function!)
157 # Doesn't matter what we patch as long as it doesn't
158 # actually get in our way.
159 @patch("invoke.runners.pty")
160 def wrapper(*args, **kwargs):
161 proc = MockSubprocess(
162 out=out, err=err, exit=exit, isatty=isatty, autostart=False
163 )
164 Popen = proc.start()
165 args = list(args)
166 args.pop() # Pop the dummy patch
167 if insert_Popen:
168 args.append(Popen)
169 try:
170 f(*args, **kwargs)
171 finally:
172 proc.stop()
173
174 return wrapper
175
176 return decorator
177
178
179 def mock_pty(
180 out="",
181 err="",
182 exit=0,
183 isatty=None,
184 trailing_error=None,
185 skip_asserts=False,
186 insert_os=False,
187 be_childish=False,
188 os_close_error=False,
189 ):
190 # Windows doesn't have ptys, so all the pty tests should be
191 # skipped anyway...
192 if WINDOWS:
193 return skip_if_windows
194
195 def decorator(f):
196 import fcntl
197
198 ioctl_patch = patch("invoke.runners.fcntl.ioctl", wraps=fcntl.ioctl)
199
200 @wraps(f)
201 @patch("invoke.runners.pty")
202 @patch("invoke.runners.os")
203 @ioctl_patch
204 def wrapper(*args, **kwargs):
205 args = list(args)
206 pty, os, ioctl = args.pop(), args.pop(), args.pop()
207 # Don't actually fork, but pretend we did (with "our" pid differing
208 # depending on be_childish) & give 'parent fd' of 3 (typically,
209 # first allocated non-stdin/out/err FD)
210 pty.fork.return_value = (12345 if be_childish else 0), 3
211 # We don't really need to care about waiting since not truly
212 # forking/etc, so here we just return a nonzero "pid" + sentinel
213 # wait-status value (used in some tests about WIFEXITED etc)
214 os.waitpid.return_value = None, Mock(name="exitstatus")
215 # Either or both of these may get called, depending...
216 os.WEXITSTATUS.return_value = exit
217 os.WTERMSIG.return_value = exit
218 # If requested, mock isatty to fake out pty detection
219 if isatty is not None:
220 os.isatty.return_value = isatty
221 out_file = BytesIO(out.encode())
222 err_file = BytesIO(err.encode())
223
224 def fakeread(fileno, count):
225 fd = {3: out_file, 2: err_file}[fileno]
226 ret = fd.read(count)
227 # If asked, fake a Linux-platform trailing I/O error.
228 if not ret and trailing_error:
229 raise trailing_error
230 return ret
231
232 os.read.side_effect = fakeread
233 if os_close_error:
234 os.close.side_effect = IOError
235 if insert_os:
236 args.append(os)
237
238 # Do the thing!!!
239 f(*args, **kwargs)
240
241 # Short-circuit if we raised an error in fakeread()
242 if trailing_error:
243 return
244 # Sanity checks to make sure the stuff we mocked, actually got ran!
245 pty.fork.assert_called_with()
246 # Skip rest of asserts if we pretended to be the child
247 if be_childish:
248 return
249 # Expect a get, and then later set, of terminal window size
250 assert ioctl.call_args_list[0][0][1] == termios.TIOCGWINSZ
251 assert ioctl.call_args_list[1][0][1] == termios.TIOCSWINSZ
252 if not skip_asserts:
253 for name in ("execvpe", "waitpid"):
254 assert getattr(os, name).called
255 # Ensure at least one of the exit status getters was called
256 assert os.WEXITSTATUS.called or os.WTERMSIG.called
257 # Ensure something closed the pty FD
258 os.close.assert_called_once_with(3)
259
260 return wrapper
261
262 return decorator
263
264
265 class _Dummy(Runner):
266 """
267 Dummy runner subclass that does minimum work required to execute run().
268
269 It also serves as a convenient basic API checker; failure to update it to
270 match the current Runner API will cause TypeErrors, NotImplementedErrors,
271 and similar.
272 """
273
274 # Neuter the input loop sleep, so tests aren't slow (at the expense of CPU,
275 # which isn't a problem for testing).
276 input_sleep = 0
277
278 def start(self, command, shell, env, timeout=None):
279 pass
280
281 def read_proc_stdout(self, num_bytes):
282 return ""
283
284 def read_proc_stderr(self, num_bytes):
285 return ""
286
287 def _write_proc_stdin(self, data):
288 pass
289
290 def close_proc_stdin(self):
291 pass
292
293 @property
294 def process_is_finished(self):
295 return True
296
297 def returncode(self):
298 return 0
299
300 @property
301 def timed_out(self):
302 return False
303
304
305 # Dummy command that will blow up if it ever truly hits a real shell.
306 _ = "nope"
307
308
309 # Runner that fakes ^C during subprocess exec
310 class _KeyboardInterruptingRunner(_Dummy):
311 def __init__(self, *args, **kwargs):
312 super().__init__(*args, **kwargs)
313 self._interrupted = False
314
315 # Trigger KeyboardInterrupt during wait()
316 def wait(self):
317 if not self._interrupted:
318 self._interrupted = True
319 raise KeyboardInterrupt
320
321 # But also, after that has been done, pretend subprocess shutdown happened
322 # (or we will loop forever).
323 def process_is_finished(self):
324 return self._interrupted
325
326
327 class OhNoz(Exception):
328 pass