Debian Codegraph @

tests/test-stdio.py

raw ◀ ▶
1 Debian patch touch this file
1 #!/usr/bin/env python3
2 """
3 Tests the buffering behavior of stdio streams in `mercurial.utils.procutil`.
4 """
5
6 import contextlib
7 import errno
8 import os
9 import pickle
10 import signal
11 import subprocess
12 import sys
13 import tempfile
14 import unittest
15
16 from mercurial import pycompat, util
17
18
19 TEST_BUFFERING_CHILD_SCRIPT = r'''
20 import os
21
22 from mercurial import dispatch
23 from mercurial.utils import procutil
24
25 dispatch.initstdio()
26 procutil.{stream}.write(b'aaa')
27 os.write(procutil.{stream}.fileno(), b'[written aaa]')
28 procutil.{stream}.write(b'bbb\n')
29 os.write(procutil.{stream}.fileno(), b'[written bbb\\n]')
30 '''
31 UNBUFFERED = b'aaa[written aaa]bbb\n[written bbb\\n]'
32 LINE_BUFFERED = b'[written aaa]aaabbb\n[written bbb\\n]'
33 FULLY_BUFFERED = b'[written aaa][written bbb\\n]aaabbb\n'
34
35
36 TEST_LARGE_WRITE_CHILD_SCRIPT = r'''
37 import os
38 import signal
39 import sys
40
41 from mercurial import dispatch
42 from mercurial.utils import procutil
43
44 signal.signal(signal.SIGINT, lambda *x: None)
45 dispatch.initstdio()
46 write_result = procutil.{stream}.write(b'x' * (2 * 1048576))
47 with os.fdopen(
48 os.open({write_result_fn!r}, os.O_WRONLY | getattr(os, 'O_TEMPORARY', 0)),
49 'w',
50 ) as write_result_f:
51 write_result_f.write(str(write_result))
52 # If the signal is coming late,
53 # we ignore the signal to avoid a test flake (return code -2).
54 # This can happen for example if the kernel accepts the whole
55 # large write without blocking.
56 signal.signal(signal.SIGINT, signal.SIG_IGN)
57 '''
58
59
60 TEST_BROKEN_PIPE_CHILD_SCRIPT = r'''
61 import os
62 import pickle
63
64 from mercurial import dispatch
65 from mercurial.utils import procutil
66
67 dispatch.initstdio()
68 procutil.stdin.read(1) # wait until parent process closed pipe
69 try:
70 procutil.{stream}.write(b'test')
71 procutil.{stream}.flush()
72 except EnvironmentError as e:
73 with os.fdopen(
74 os.open(
75 {err_fn!r},
76 os.O_WRONLY
77 | getattr(os, 'O_BINARY', 0)
78 | getattr(os, 'O_TEMPORARY', 0),
79 ),
80 'wb',
81 ) as err_f:
82 pickle.dump(e, err_f)
83 # Exit early to suppress further broken pipe errors at interpreter shutdown.
84 os._exit(0)
85 '''
86
87
88 @contextlib.contextmanager
89 def _closing(fds):
90 try:
91 yield
92 finally:
93 for fd in fds:
94 try:
95 os.close(fd)
96 except OSError:
97 pass
98
99
100 # In the following, we set the FDs non-inheritable mainly to make it possible
101 # for tests to close the receiving end of the pipe / PTYs.
102
103
104 @contextlib.contextmanager
105 def _devnull():
106 devnull = os.open(os.devnull, os.O_WRONLY)
107 # We don't have a receiving end, so it's not worth the effort on Python 2
108 # on Windows to make the FD non-inheritable.
109 with _closing([devnull]):
110 yield (None, devnull)
111
112
113 @contextlib.contextmanager
114 def _pipes():
115 rwpair = os.pipe()
116 with _closing(rwpair):
117 yield rwpair
118
119
120 @contextlib.contextmanager
121 def _ptys():
122 if pycompat.iswindows:
123 raise unittest.SkipTest("PTYs are not supported on Windows")
124 import pty
125 import tty
126
127 rwpair = pty.openpty()
128 with _closing(rwpair):
129 tty.setraw(rwpair[0])
130 yield rwpair
131
132
133 def _readall(fd, buffer_size, initial_buf=None):
134 buf = initial_buf or []
135 while True:
136 try:
137 s = os.read(fd, buffer_size)
138 except OSError as e:
139 if e.errno == errno.EIO:
140 # If the child-facing PTY got closed, reading from the
141 # parent-facing PTY raises EIO.
142 break
143 raise
144 if not s:
145 break
146 buf.append(s)
147 return b''.join(buf)
148
149
150 class TestStdio(unittest.TestCase):
151 def _test(
152 self,
153 child_script,
154 stream,
155 rwpair_generator,
156 check_output,
157 python_args=[],
158 post_child_check=None,
159 stdin_generator=None,
160 ):
161 assert stream in ('stdout', 'stderr')
162 if stdin_generator is None:
163 stdin_generator = open(os.devnull, 'rb')
164 with rwpair_generator() as (
165 stream_receiver,
166 child_stream,
167 ), stdin_generator as child_stdin:
168 proc = subprocess.Popen(
169 [sys.executable] + python_args + ['-c', child_script],
170 stdin=child_stdin,
171 stdout=child_stream if stream == 'stdout' else None,
172 stderr=child_stream if stream == 'stderr' else None,
173 )
174 try:
175 os.close(child_stream)
176 if stream_receiver is not None:
177 check_output(stream_receiver, proc)
178 except: # re-raises
179 proc.terminate()
180 raise
181 finally:
182 retcode = proc.wait()
•183 self.assertIn(retcode, [0, -2])
184 if post_child_check is not None:
185 post_child_check()
186
187 def _test_buffering(
188 self, stream, rwpair_generator, expected_output, python_args=[]
189 ):
190 def check_output(stream_receiver, proc):
191 self.assertEqual(_readall(stream_receiver, 1024), expected_output)
192
193 self._test(
194 TEST_BUFFERING_CHILD_SCRIPT.format(stream=stream),
195 stream,
196 rwpair_generator,
197 check_output,
198 python_args,
199 )
200
201 def test_buffering_stdout_devnull(self):
202 self._test_buffering('stdout', _devnull, None)
203
204 def test_buffering_stdout_pipes(self):
205 self._test_buffering('stdout', _pipes, FULLY_BUFFERED)
206
207 def test_buffering_stdout_ptys(self):
208 self._test_buffering('stdout', _ptys, LINE_BUFFERED)
209
210 def test_buffering_stdout_devnull_unbuffered(self):
211 self._test_buffering('stdout', _devnull, None, python_args=['-u'])
212
213 def test_buffering_stdout_pipes_unbuffered(self):
214 self._test_buffering('stdout', _pipes, UNBUFFERED, python_args=['-u'])
215
216 def test_buffering_stdout_ptys_unbuffered(self):
217 self._test_buffering('stdout', _ptys, UNBUFFERED, python_args=['-u'])
218
219 def _test_large_write(self, stream, rwpair_generator, python_args=[]):
220 def check_output(stream_receiver, proc):
221 if not pycompat.iswindows:
222 # On Unix, we can provoke a partial write() by interrupting it
223 # by a signal handler as soon as a bit of data was written.
224 # We test that write() is called until all data is written.
225 buf = [os.read(stream_receiver, 1)]
226 proc.send_signal(signal.SIGINT)
227 else:
228 # On Windows, there doesn't seem to be a way to cause partial
229 # writes.
230 buf = []
231 self.assertEqual(
232 _readall(stream_receiver, 131072, buf), b'x' * (2 * 1048576)
233 )
234
235 def post_child_check():
236 self.assertEqual(write_result_f.read(), str(2 * 1048576))
237
238 with tempfile.NamedTemporaryFile('r') as write_result_f:
239 self._test(
240 TEST_LARGE_WRITE_CHILD_SCRIPT.format(
241 stream=stream, write_result_fn=write_result_f.name
242 ),
243 stream,
244 rwpair_generator,
245 check_output,
246 python_args,
247 post_child_check=post_child_check,
248 )
249
250 def test_large_write_stdout_devnull(self):
251 self._test_large_write('stdout', _devnull)
252
253 def test_large_write_stdout_pipes(self):
254 self._test_large_write('stdout', _pipes)
255
256 def test_large_write_stdout_ptys(self):
257 self._test_large_write('stdout', _ptys)
258
259 def test_large_write_stdout_devnull_unbuffered(self):
260 self._test_large_write('stdout', _devnull, python_args=['-u'])
261
262 def test_large_write_stdout_pipes_unbuffered(self):
263 self._test_large_write('stdout', _pipes, python_args=['-u'])
264
265 def test_large_write_stdout_ptys_unbuffered(self):
266 self._test_large_write('stdout', _ptys, python_args=['-u'])
267
268 def test_large_write_stderr_devnull(self):
269 self._test_large_write('stderr', _devnull)
270
271 def test_large_write_stderr_pipes(self):
272 self._test_large_write('stderr', _pipes)
273
274 def test_large_write_stderr_ptys(self):
275 self._test_large_write('stderr', _ptys)
276
277 def test_large_write_stderr_devnull_unbuffered(self):
278 self._test_large_write('stderr', _devnull, python_args=['-u'])
279
280 def test_large_write_stderr_pipes_unbuffered(self):
281 self._test_large_write('stderr', _pipes, python_args=['-u'])
282
283 def test_large_write_stderr_ptys_unbuffered(self):
284 self._test_large_write('stderr', _ptys, python_args=['-u'])
285
286 def _test_broken_pipe(self, stream):
287 assert stream in ('stdout', 'stderr')
288
289 def check_output(stream_receiver, proc):
290 os.close(stream_receiver)
291 proc.stdin.write(b'x')
292 proc.stdin.close()
293
294 def post_child_check():
295 err = pickle.load(err_f)
296 self.assertEqual(err.errno, errno.EPIPE)
297 self.assertEqual(err.strerror, "Broken pipe")
298
299 with tempfile.NamedTemporaryFile('rb') as err_f:
300 self._test(
301 TEST_BROKEN_PIPE_CHILD_SCRIPT.format(
302 stream=stream, err_fn=err_f.name
303 ),
304 stream,
305 _pipes,
306 check_output,
307 post_child_check=post_child_check,
308 stdin_generator=util.nullcontextmanager(subprocess.PIPE),
309 )
310
311 def test_broken_pipe_stdout(self):
312 self._test_broken_pipe('stdout')
313
314 def test_broken_pipe_stderr(self):
315 self._test_broken_pipe('stderr')
316
317
318 if __name__ == '__main__':
319 import silenttestrunner
320
321 silenttestrunner.main(__name__)