Debian Codegraph @

Lib/test/test_asyncio/test_subprocess.py

raw
1 import os
2 import signal
3 import sys
4 import textwrap
5 import unittest
6 import warnings
7 from unittest import mock
8
9 import asyncio
10 from asyncio import base_subprocess
11 from asyncio import subprocess
12 from test.test_asyncio import utils as test_utils
13 from test import support
14 from test.support import os_helper, warnings_helper, gc_collect
15
16 if not support.has_subprocess_support:
17 raise unittest.SkipTest("test module requires subprocess")
18
19 if support.MS_WINDOWS:
20 import msvcrt
21 else:
22 from asyncio import unix_events
23
24
25 if support.check_sanitizer(address=True):
26 raise unittest.SkipTest("Exposes ASAN flakiness in GitHub CI")
27
28 # Program blocking
29 PROGRAM_BLOCKED = [sys.executable, '-c', 'import time; time.sleep(3600)']
30
31 # Program copying input to output
32 PROGRAM_CAT = [
33 sys.executable, '-c',
34 ';'.join(('import sys',
35 'data = sys.stdin.buffer.read()',
36 'sys.stdout.buffer.write(data)'))]
37
38
39 def tearDownModule():
40 asyncio.set_event_loop_policy(None)
41
42
43 class TestSubprocessTransport(base_subprocess.BaseSubprocessTransport):
44 def _start(self, *args, **kwargs):
45 self._proc = mock.Mock()
46 self._proc.stdin = None
47 self._proc.stdout = None
48 self._proc.stderr = None
49 self._proc.pid = -1
50
51
52 class SubprocessTransportTests(test_utils.TestCase):
53 def setUp(self):
54 super().setUp()
55 self.loop = self.new_test_loop()
56 self.set_event_loop(self.loop)
57
58 def create_transport(self, waiter=None):
59 protocol = mock.Mock()
60 transport = TestSubprocessTransport(
61 self.loop, protocol, ['test'], False,
62 None, None, None, 0, waiter=waiter)
63 return (transport, protocol)
64
65 def test_proc_exited(self):
66 waiter = self.loop.create_future()
67 transport, protocol = self.create_transport(waiter)
68 transport._process_exited(6)
69 self.loop.run_until_complete(waiter)
70
71 self.assertEqual(transport.get_returncode(), 6)
72
73 self.assertTrue(protocol.connection_made.called)
74 self.assertTrue(protocol.process_exited.called)
75 self.assertTrue(protocol.connection_lost.called)
76 self.assertEqual(protocol.connection_lost.call_args[0], (None,))
77
78 self.assertFalse(transport.is_closing())
79 self.assertIsNone(transport._loop)
80 self.assertIsNone(transport._proc)
81 self.assertIsNone(transport._protocol)
82
83 # methods must raise ProcessLookupError if the process exited
84 self.assertRaises(ProcessLookupError,
85 transport.send_signal, signal.SIGTERM)
86 self.assertRaises(ProcessLookupError, transport.terminate)
87 self.assertRaises(ProcessLookupError, transport.kill)
88
89 transport.close()
90
91 def test_subprocess_repr(self):
92 waiter = self.loop.create_future()
93 transport, protocol = self.create_transport(waiter)
94 transport._process_exited(6)
95 self.loop.run_until_complete(waiter)
96
97 self.assertEqual(
98 repr(transport),
99 "<TestSubprocessTransport pid=-1 returncode=6>"
100 )
101 transport._returncode = None
102 self.assertEqual(
103 repr(transport),
104 "<TestSubprocessTransport pid=-1 running>"
105 )
106 transport._pid = None
107 transport._returncode = None
108 self.assertEqual(
109 repr(transport),
110 "<TestSubprocessTransport not started>"
111 )
112 transport.close()
113
114
115 class SubprocessMixin:
116
117 def test_stdin_stdout(self):
118 args = PROGRAM_CAT
119
120 async def run(data):
121 proc = await asyncio.create_subprocess_exec(
122 *args,
123 stdin=subprocess.PIPE,
124 stdout=subprocess.PIPE,
125 )
126
127 # feed data
128 proc.stdin.write(data)
129 await proc.stdin.drain()
130 proc.stdin.close()
131
132 # get output and exitcode
133 data = await proc.stdout.read()
134 exitcode = await proc.wait()
135 return (exitcode, data)
136
137 task = run(b'some data')
138 task = asyncio.wait_for(task, 60.0)
139 exitcode, stdout = self.loop.run_until_complete(task)
140 self.assertEqual(exitcode, 0)
141 self.assertEqual(stdout, b'some data')
142
143 def test_communicate(self):
144 args = PROGRAM_CAT
145
146 async def run(data):
147 proc = await asyncio.create_subprocess_exec(
148 *args,
149 stdin=subprocess.PIPE,
150 stdout=subprocess.PIPE,
151 )
152 stdout, stderr = await proc.communicate(data)
153 return proc.returncode, stdout
154
155 task = run(b'some data')
156 task = asyncio.wait_for(task, support.LONG_TIMEOUT)
157 exitcode, stdout = self.loop.run_until_complete(task)
158 self.assertEqual(exitcode, 0)
159 self.assertEqual(stdout, b'some data')
160
161 def test_communicate_none_input(self):
162 args = PROGRAM_CAT
163
164 async def run():
165 proc = await asyncio.create_subprocess_exec(
166 *args,
167 stdin=subprocess.PIPE,
168 stdout=subprocess.PIPE,
169 )
170 stdout, stderr = await proc.communicate()
171 return proc.returncode, stdout
172
173 task = run()
174 task = asyncio.wait_for(task, support.LONG_TIMEOUT)
175 exitcode, stdout = self.loop.run_until_complete(task)
176 self.assertEqual(exitcode, 0)
177 self.assertEqual(stdout, b'')
178
179 def test_shell(self):
180 proc = self.loop.run_until_complete(
181 asyncio.create_subprocess_shell('exit 7')
182 )
183 exitcode = self.loop.run_until_complete(proc.wait())
184 self.assertEqual(exitcode, 7)
185
186 def test_start_new_session(self):
187 # start the new process in a new session
188 proc = self.loop.run_until_complete(
189 asyncio.create_subprocess_shell(
190 'exit 8',
191 start_new_session=True,
192 )
193 )
194 exitcode = self.loop.run_until_complete(proc.wait())
195 self.assertEqual(exitcode, 8)
196
197 def test_kill(self):
198 args = PROGRAM_BLOCKED
199 proc = self.loop.run_until_complete(
200 asyncio.create_subprocess_exec(*args)
201 )
202 proc.kill()
203 returncode = self.loop.run_until_complete(proc.wait())
204 if sys.platform == 'win32':
205 self.assertIsInstance(returncode, int)
206 # expect 1 but sometimes get 0
207 else:
208 self.assertEqual(-signal.SIGKILL, returncode)
209
210 def test_kill_issue43884(self):
211 if sys.platform == 'win32':
212 blocking_shell_command = f'"{sys.executable}" -c "import time; time.sleep(2)"'
213 else:
214 blocking_shell_command = 'sleep 1; sleep 1'
215 creationflags = 0
216 if sys.platform == 'win32':
217 from subprocess import CREATE_NEW_PROCESS_GROUP
218 # On windows create a new process group so that killing process
219 # kills the process and all its children.
220 creationflags = CREATE_NEW_PROCESS_GROUP
221 proc = self.loop.run_until_complete(
222 asyncio.create_subprocess_shell(blocking_shell_command,
223 creationflags=creationflags)
224 )
225 self.loop.run_until_complete(asyncio.sleep(1))
226 if sys.platform == 'win32':
227 proc.send_signal(signal.CTRL_BREAK_EVENT)
228 # On windows it is an alias of terminate which sets the return code
229 proc.kill()
230 returncode = self.loop.run_until_complete(proc.wait())
231 if sys.platform == 'win32':
232 self.assertIsInstance(returncode, int)
233 # expect 1 but sometimes get 0
234 else:
235 self.assertEqual(-signal.SIGKILL, returncode)
236
237 def test_terminate(self):
238 args = PROGRAM_BLOCKED
239 proc = self.loop.run_until_complete(
240 asyncio.create_subprocess_exec(*args)
241 )
242 proc.terminate()
243 returncode = self.loop.run_until_complete(proc.wait())
244 if sys.platform == 'win32':
245 self.assertIsInstance(returncode, int)
246 # expect 1 but sometimes get 0
247 else:
248 self.assertEqual(-signal.SIGTERM, returncode)
249
250 @unittest.skipIf(sys.platform == 'win32', "Don't have SIGHUP")
251 def test_send_signal(self):
252 # bpo-31034: Make sure that we get the default signal handler (killing
253 # the process). The parent process may have decided to ignore SIGHUP,
254 # and signal handlers are inherited.
255 old_handler = signal.signal(signal.SIGHUP, signal.SIG_DFL)
256 try:
257 code = 'import time; print("sleeping", flush=True); time.sleep(3600)'
258 args = [sys.executable, '-c', code]
259 proc = self.loop.run_until_complete(
260 asyncio.create_subprocess_exec(
261 *args,
262 stdout=subprocess.PIPE,
263 )
264 )
265
266 async def send_signal(proc):
267 # basic synchronization to wait until the program is sleeping
268 line = await proc.stdout.readline()
269 self.assertEqual(line, b'sleeping\n')
270
271 proc.send_signal(signal.SIGHUP)
272 returncode = await proc.wait()
273 return returncode
274
275 returncode = self.loop.run_until_complete(send_signal(proc))
276 self.assertEqual(-signal.SIGHUP, returncode)
277 finally:
278 signal.signal(signal.SIGHUP, old_handler)
279
280 def test_stdin_broken_pipe(self):
281 # buffer large enough to feed the whole pipe buffer
282 large_data = b'x' * support.PIPE_MAX_SIZE
283
284 rfd, wfd = os.pipe()
285 self.addCleanup(os.close, rfd)
286 self.addCleanup(os.close, wfd)
287 if support.MS_WINDOWS:
288 handle = msvcrt.get_osfhandle(rfd)
289 os.set_handle_inheritable(handle, True)
290 code = textwrap.dedent(f'''
291 import os, msvcrt
292 handle = {handle}
293 fd = msvcrt.open_osfhandle(handle, os.O_RDONLY)
294 os.read(fd, 1)
295 ''')
296 from subprocess import STARTUPINFO
297 startupinfo = STARTUPINFO()
298 startupinfo.lpAttributeList = {"handle_list": [handle]}
299 kwargs = dict(startupinfo=startupinfo)
300 else:
301 code = f'import os; fd = {rfd}; os.read(fd, 1)'
302 kwargs = dict(pass_fds=(rfd,))
303
304 # the program ends before the stdin can be fed
305 proc = self.loop.run_until_complete(
306 asyncio.create_subprocess_exec(
307 sys.executable, '-c', code,
308 stdin=subprocess.PIPE,
309 **kwargs
310 )
311 )
312
313 async def write_stdin(proc, data):
314 proc.stdin.write(data)
315 # Only exit the child process once the write buffer is filled
316 os.write(wfd, b'go')
317 await proc.stdin.drain()
318
319 coro = write_stdin(proc, large_data)
320 # drain() must raise BrokenPipeError or ConnectionResetError
321 with test_utils.disable_logger():
322 self.assertRaises((BrokenPipeError, ConnectionResetError),
323 self.loop.run_until_complete, coro)
324 self.loop.run_until_complete(proc.wait())
325
326 def test_communicate_ignore_broken_pipe(self):
327 # buffer large enough to feed the whole pipe buffer
328 large_data = b'x' * support.PIPE_MAX_SIZE
329
330 # the program ends before the stdin can be fed
331 proc = self.loop.run_until_complete(
332 asyncio.create_subprocess_exec(
333 sys.executable, '-c', 'pass',
334 stdin=subprocess.PIPE,
335 )
336 )
337
338 # communicate() must ignore BrokenPipeError when feeding stdin
339 self.loop.set_exception_handler(lambda loop, msg: None)
340 self.loop.run_until_complete(proc.communicate(large_data))
341 self.loop.run_until_complete(proc.wait())
342
343 def test_pause_reading(self):
344 limit = 10
345 size = (limit * 2 + 1)
346
347 async def test_pause_reading():
348 code = '\n'.join((
349 'import sys',
350 'sys.stdout.write("x" * %s)' % size,
351 'sys.stdout.flush()',
352 ))
353
354 connect_read_pipe = self.loop.connect_read_pipe
355
356 async def connect_read_pipe_mock(*args, **kw):
357 transport, protocol = await connect_read_pipe(*args, **kw)
358 transport.pause_reading = mock.Mock()
359 transport.resume_reading = mock.Mock()
360 return (transport, protocol)
361
362 self.loop.connect_read_pipe = connect_read_pipe_mock
363
364 proc = await asyncio.create_subprocess_exec(
365 sys.executable, '-c', code,
366 stdin=asyncio.subprocess.PIPE,
367 stdout=asyncio.subprocess.PIPE,
368 limit=limit,
369 )
370 stdout_transport = proc._transport.get_pipe_transport(1)
371
372 stdout, stderr = await proc.communicate()
373
374 # The child process produced more than limit bytes of output,
375 # the stream reader transport should pause the protocol to not
376 # allocate too much memory.
377 return (stdout, stdout_transport)
378
379 # Issue #22685: Ensure that the stream reader pauses the protocol
380 # when the child process produces too much data
381 stdout, transport = self.loop.run_until_complete(test_pause_reading())
382
383 self.assertEqual(stdout, b'x' * size)
384 self.assertTrue(transport.pause_reading.called)
385 self.assertTrue(transport.resume_reading.called)
386
387 def test_stdin_not_inheritable(self):
388 # asyncio issue #209: stdin must not be inheritable, otherwise
389 # the Process.communicate() hangs
390 async def len_message(message):
391 code = 'import sys; data = sys.stdin.read(); print(len(data))'
392 proc = await asyncio.create_subprocess_exec(
393 sys.executable, '-c', code,
394 stdin=asyncio.subprocess.PIPE,
395 stdout=asyncio.subprocess.PIPE,
396 stderr=asyncio.subprocess.PIPE,
397 close_fds=False,
398 )
399 stdout, stderr = await proc.communicate(message)
400 exitcode = await proc.wait()
401 return (stdout, exitcode)
402
403 output, exitcode = self.loop.run_until_complete(len_message(b'abc'))
404 self.assertEqual(output.rstrip(), b'3')
405 self.assertEqual(exitcode, 0)
406
407 def test_wait_even_if_pipe_is_open(self):
408 # gh-119710: Process.wait() must return once the process exits even
409 # if its stdout pipe is inherited by a grandchild that keeps it open,
410 # so the pipe never reaches EOF. Otherwise wait() hangs forever
411 # despite the returncode being known.
412
413 async def run():
414 # The grandchild inherits the child's stdin and stdout pipes and
415 # keeps both open after the child is killed. It writes "ready"
416 # so we know it has started, and exits once its stdin hits EOF.
417 code = textwrap.dedent("""\
418 import subprocess, sys
419 subprocess.run([sys.executable, "-c",
420 "import sys; sys.stdout.write('ready');"
421 " sys.stdout.flush(); sys.stdin.read()"])
422 """)
423
424 proc = await asyncio.create_subprocess_exec(
425 sys.executable, "-c", code,
426 stdin=subprocess.PIPE,
427 stdout=subprocess.PIPE,
428 )
429 try:
430 wait_proc = asyncio.create_task(proc.wait())
431 # Wait until the grandchild holds the inherited pipes; this
432 # also lets the wait() task register its waiter.
433 await proc.stdout.readexactly(5)
434 proc.kill()
435 returncode = await asyncio.wait_for(
436 wait_proc, timeout=support.SHORT_TIMEOUT)
437 if sys.platform == 'win32':
438 self.assertIsInstance(returncode, int)
439 else:
440 self.assertEqual(-signal.SIGKILL, returncode)
441 finally:
442 proc.stdin.close() # let the grandchild exit
443 await proc.stdout.read()
444
445 self.loop.run_until_complete(run())
446
447 def test_empty_input(self):
448
449 async def empty_input():
450 code = 'import sys; data = sys.stdin.read(); print(len(data))'
451 proc = await asyncio.create_subprocess_exec(
452 sys.executable, '-c', code,
453 stdin=asyncio.subprocess.PIPE,
454 stdout=asyncio.subprocess.PIPE,
455 stderr=asyncio.subprocess.PIPE,
456 close_fds=False,
457 )
458 stdout, stderr = await proc.communicate(b'')
459 exitcode = await proc.wait()
460 return (stdout, exitcode)
461
462 output, exitcode = self.loop.run_until_complete(empty_input())
463 self.assertEqual(output.rstrip(), b'0')
464 self.assertEqual(exitcode, 0)
465
466 def test_devnull_input(self):
467
468 async def empty_input():
469 code = 'import sys; data = sys.stdin.read(); print(len(data))'
470 proc = await asyncio.create_subprocess_exec(
471 sys.executable, '-c', code,
472 stdin=asyncio.subprocess.DEVNULL,
473 stdout=asyncio.subprocess.PIPE,
474 stderr=asyncio.subprocess.PIPE,
475 close_fds=False,
476 )
477 stdout, stderr = await proc.communicate()
478 exitcode = await proc.wait()
479 return (stdout, exitcode)
480
481 output, exitcode = self.loop.run_until_complete(empty_input())
482 self.assertEqual(output.rstrip(), b'0')
483 self.assertEqual(exitcode, 0)
484
485 def test_devnull_output(self):
486
487 async def empty_output():
488 code = 'import sys; data = sys.stdin.read(); print(len(data))'
489 proc = await asyncio.create_subprocess_exec(
490 sys.executable, '-c', code,
491 stdin=asyncio.subprocess.PIPE,
492 stdout=asyncio.subprocess.DEVNULL,
493 stderr=asyncio.subprocess.PIPE,
494 close_fds=False,
495 )
496 stdout, stderr = await proc.communicate(b"abc")
497 exitcode = await proc.wait()
498 return (stdout, exitcode)
499
500 output, exitcode = self.loop.run_until_complete(empty_output())
501 self.assertEqual(output, None)
502 self.assertEqual(exitcode, 0)
503
504 def test_devnull_error(self):
505
506 async def empty_error():
507 code = 'import sys; data = sys.stdin.read(); print(len(data))'
508 proc = await asyncio.create_subprocess_exec(
509 sys.executable, '-c', code,
510 stdin=asyncio.subprocess.PIPE,
511 stdout=asyncio.subprocess.PIPE,
512 stderr=asyncio.subprocess.DEVNULL,
513 close_fds=False,
514 )
515 stdout, stderr = await proc.communicate(b"abc")
516 exitcode = await proc.wait()
517 return (stderr, exitcode)
518
519 output, exitcode = self.loop.run_until_complete(empty_error())
520 self.assertEqual(output, None)
521 self.assertEqual(exitcode, 0)
522
523 @unittest.skipIf(sys.platform not in ('linux', 'android'),
524 "Don't have /dev/stdin")
525 def test_devstdin_input(self):
526
527 async def devstdin_input(message):
528 code = 'file = open("/dev/stdin"); data = file.read(); print(len(data))'
529 proc = await asyncio.create_subprocess_exec(
530 sys.executable, '-c', code,
531 stdin=asyncio.subprocess.PIPE,
532 stdout=asyncio.subprocess.PIPE,
533 stderr=asyncio.subprocess.PIPE,
534 close_fds=False,
535 )
536 stdout, stderr = await proc.communicate(message)
537 exitcode = await proc.wait()
538 return (stdout, exitcode)
539
540 output, exitcode = self.loop.run_until_complete(devstdin_input(b'abc'))
541 self.assertEqual(output.rstrip(), b'3')
542 self.assertEqual(exitcode, 0)
543
544 def test_cancel_process_wait(self):
545 # Issue #23140: cancel Process.wait()
546
547 async def cancel_wait():
548 proc = await asyncio.create_subprocess_exec(*PROGRAM_BLOCKED)
549
550 # Create an internal future waiting on the process exit
551 task = self.loop.create_task(proc.wait())
552 self.loop.call_soon(task.cancel)
553 try:
554 await task
555 except asyncio.CancelledError:
556 pass
557
558 # Cancel the future
559 task.cancel()
560
561 # Kill the process and wait until it is done
562 proc.kill()
563 await proc.wait()
564
565 self.loop.run_until_complete(cancel_wait())
566
567 def test_cancel_make_subprocess_transport_exec(self):
568
569 async def cancel_make_transport():
570 coro = asyncio.create_subprocess_exec(*PROGRAM_BLOCKED)
571 task = self.loop.create_task(coro)
572
573 self.loop.call_soon(task.cancel)
574 try:
575 await task
576 except asyncio.CancelledError:
577 pass
578
579 # ignore the log:
580 # "Exception during subprocess creation, kill the subprocess"
581 with test_utils.disable_logger():
582 self.loop.run_until_complete(cancel_make_transport())
583
584 def test_cancel_post_init(self):
585
586 async def cancel_make_transport():
587 coro = self.loop.subprocess_exec(asyncio.SubprocessProtocol,
588 *PROGRAM_BLOCKED)
589 task = self.loop.create_task(coro)
590
591 self.loop.call_soon(task.cancel)
592 try:
593 await task
594 except asyncio.CancelledError:
595 pass
596
597 # ignore the log:
598 # "Exception during subprocess creation, kill the subprocess"
599 with test_utils.disable_logger():
600 self.loop.run_until_complete(cancel_make_transport())
601 test_utils.run_briefly(self.loop)
602
603 def test_close_kill_running(self):
604
605 async def kill_running():
606 create = self.loop.subprocess_exec(asyncio.SubprocessProtocol,
607 *PROGRAM_BLOCKED)
608 transport, protocol = await create
609
610 kill_called = False
611 def kill():
612 nonlocal kill_called
613 kill_called = True
614 orig_kill()
615
616 proc = transport.get_extra_info('subprocess')
617 orig_kill = proc.kill
618 proc.kill = kill
619 returncode = transport.get_returncode()
620 transport.close()
621 await asyncio.wait_for(transport._wait(), 5)
622 return (returncode, kill_called)
623
624 # Ignore "Close running child process: kill ..." log
625 with test_utils.disable_logger():
626 try:
627 returncode, killed = self.loop.run_until_complete(
628 kill_running()
629 )
630 except asyncio.TimeoutError:
631 self.skipTest(
632 "Timeout failure on waiting for subprocess stopping"
633 )
634 self.assertIsNone(returncode)
635
636 # transport.close() must kill the process if it is still running
637 self.assertTrue(killed)
638 test_utils.run_briefly(self.loop)
639
640 def test_close_dont_kill_finished(self):
641
642 async def kill_running():
643 create = self.loop.subprocess_exec(asyncio.SubprocessProtocol,
644 *PROGRAM_BLOCKED)
645 transport, protocol = await create
646 proc = transport.get_extra_info('subprocess')
647
648 # kill the process (but asyncio is not notified immediately)
649 proc.kill()
650 proc.wait()
651
652 proc.kill = mock.Mock()
653 proc_returncode = proc.poll()
654 transport_returncode = transport.get_returncode()
655 transport.close()
656 return (proc_returncode, transport_returncode, proc.kill.called)
657
658 # Ignore "Unknown child process pid ..." log of SafeChildWatcher,
659 # emitted because the test already consumes the exit status:
660 # proc.wait()
661 with test_utils.disable_logger():
662 result = self.loop.run_until_complete(kill_running())
663 test_utils.run_briefly(self.loop)
664
665 proc_returncode, transport_return_code, killed = result
666
667 self.assertIsNotNone(proc_returncode)
668 self.assertIsNone(transport_return_code)
669
670 # transport.close() must not kill the process if it finished, even if
671 # the transport was not notified yet
672 self.assertFalse(killed)
673
674 # Unlike SafeChildWatcher, FastChildWatcher does not pop the
675 # callbacks if waitpid() is called elsewhere. Let's clear them
676 # manually to avoid a warning when the watcher is detached.
677 if (sys.platform != 'win32' and
678 isinstance(self, SubprocessFastWatcherTests)):
679 with warnings.catch_warnings():
680 warnings.simplefilter('ignore', DeprecationWarning)
681 asyncio.get_child_watcher()._callbacks.clear()
682
683 async def _test_popen_error(self, stdin):
684 if sys.platform == 'win32':
685 target = 'asyncio.windows_utils.Popen'
686 else:
687 target = 'subprocess.Popen'
688 with mock.patch(target) as popen:
689 exc = ZeroDivisionError
690 popen.side_effect = exc
691
692 with warnings.catch_warnings(record=True) as warns:
693 with self.assertRaises(exc):
694 await asyncio.create_subprocess_exec(
695 sys.executable,
696 '-c',
697 'pass',
698 stdin=stdin
699 )
700 self.assertEqual(warns, [])
701
702 def test_popen_error(self):
703 # Issue #24763: check that the subprocess transport is closed
704 # when BaseSubprocessTransport fails
705 self.loop.run_until_complete(self._test_popen_error(stdin=None))
706
707 def test_popen_error_with_stdin_pipe(self):
708 # Issue #35721: check that newly created socket pair is closed when
709 # Popen fails
710 self.loop.run_until_complete(
711 self._test_popen_error(stdin=subprocess.PIPE))
712
713 def test_read_stdout_after_process_exit(self):
714
715 async def execute():
716 code = '\n'.join(['import sys',
717 'for _ in range(64):',
718 ' sys.stdout.write("x" * 4096)',
719 'sys.stdout.flush()',
720 'sys.exit(1)'])
721
722 process = await asyncio.create_subprocess_exec(
723 sys.executable, '-c', code,
724 stdout=asyncio.subprocess.PIPE,
725 )
726
727 while True:
728 data = await process.stdout.read(65536)
729 if data:
730 await asyncio.sleep(0.3)
731 else:
732 break
733
734 self.loop.run_until_complete(execute())
735
736 def test_create_subprocess_exec_text_mode_fails(self):
737 async def execute():
738 with self.assertRaises(ValueError):
739 await subprocess.create_subprocess_exec(sys.executable,
740 text=True)
741
742 with self.assertRaises(ValueError):
743 await subprocess.create_subprocess_exec(sys.executable,
744 encoding="utf-8")
745
746 with self.assertRaises(ValueError):
747 await subprocess.create_subprocess_exec(sys.executable,
748 errors="strict")
749
750 self.loop.run_until_complete(execute())
751
752 def test_create_subprocess_shell_text_mode_fails(self):
753
754 async def execute():
755 with self.assertRaises(ValueError):
756 await subprocess.create_subprocess_shell(sys.executable,
757 text=True)
758
759 with self.assertRaises(ValueError):
760 await subprocess.create_subprocess_shell(sys.executable,
761 encoding="utf-8")
762
763 with self.assertRaises(ValueError):
764 await subprocess.create_subprocess_shell(sys.executable,
765 errors="strict")
766
767 self.loop.run_until_complete(execute())
768
769 def test_create_subprocess_exec_with_path(self):
770 async def execute():
771 p = await subprocess.create_subprocess_exec(
772 os_helper.FakePath(sys.executable), '-c', 'pass')
773 await p.wait()
774 p = await subprocess.create_subprocess_exec(
775 sys.executable, '-c', 'pass', os_helper.FakePath('.'))
776 await p.wait()
777
778 self.assertIsNone(self.loop.run_until_complete(execute()))
779
780 async def check_stdout_output(self, coro, output):
781 proc = await coro
782 stdout, _ = await proc.communicate()
783 self.assertEqual(stdout, output)
784 self.assertEqual(proc.returncode, 0)
785 task = asyncio.create_task(proc.wait())
786 await asyncio.sleep(0)
787 self.assertEqual(task.result(), proc.returncode)
788
789 def test_create_subprocess_env_shell(self) -> None:
790 async def main() -> None:
791 executable = sys.executable
792 if sys.platform == "win32":
793 executable = f'"{executable}"'
794 cmd = f'''{executable} -c "import os, sys; sys.stdout.write(os.getenv('FOO'))"'''
795 env = os.environ.copy()
796 env["FOO"] = "bar"
797 proc = await asyncio.create_subprocess_shell(
798 cmd, env=env, stdout=subprocess.PIPE
799 )
800 return proc
801
802 self.loop.run_until_complete(self.check_stdout_output(main(), b'bar'))
803
804 def test_create_subprocess_env_exec(self) -> None:
805 async def main() -> None:
806 cmd = [sys.executable, "-c",
807 "import os, sys; sys.stdout.write(os.getenv('FOO'))"]
808 env = os.environ.copy()
809 env["FOO"] = "baz"
810 proc = await asyncio.create_subprocess_exec(
811 *cmd, env=env, stdout=subprocess.PIPE
812 )
813 return proc
814
815 self.loop.run_until_complete(self.check_stdout_output(main(), b'baz'))
816
817
818 def test_subprocess_concurrent_wait(self) -> None:
819 async def main() -> None:
820 proc = await asyncio.create_subprocess_exec(
821 *PROGRAM_CAT,
822 stdin=subprocess.PIPE,
823 stdout=subprocess.PIPE,
824 )
825 stdout, _ = await proc.communicate(b'some data')
826 self.assertEqual(stdout, b"some data")
827 self.assertEqual(proc.returncode, 0)
828 self.assertEqual(await asyncio.gather(*[proc.wait() for _ in range(10)]),
829 [proc.returncode] * 10)
830
831 self.loop.run_until_complete(main())
832
833 def test_subprocess_protocol_events(self):
834 # gh-108973: Test that all subprocess protocol methods are called.
835 # The protocol methods are not called in a determistic order.
836 # The order depends on the event loop and the operating system.
837 events = []
838 fds = [1, 2]
839 expected = [
840 ('pipe_data_received', 1, b'stdout'),
841 ('pipe_data_received', 2, b'stderr'),
842 ('pipe_connection_lost', 1),
843 ('pipe_connection_lost', 2),
844 'process_exited',
845 ]
846 per_fd_expected = [
847 'pipe_data_received',
848 'pipe_connection_lost',
849 ]
850
851 class MyProtocol(asyncio.SubprocessProtocol):
852 def __init__(self, exit_future: asyncio.Future) -> None:
853 self.exit_future = exit_future
854
855 def pipe_data_received(self, fd, data) -> None:
856 events.append(('pipe_data_received', fd, data))
857 self.exit_maybe()
858
859 def pipe_connection_lost(self, fd, exc) -> None:
860 events.append(('pipe_connection_lost', fd))
861 self.exit_maybe()
862
863 def process_exited(self) -> None:
864 events.append('process_exited')
865 self.exit_maybe()
866
867 def exit_maybe(self):
868 # Only exit when we got all expected events
869 if len(events) >= len(expected):
870 self.exit_future.set_result(True)
871
872 async def main() -> None:
873 loop = asyncio.get_running_loop()
874 exit_future = asyncio.Future()
875 code = 'import sys; sys.stdout.write("stdout"); sys.stderr.write("stderr")'
876 transport, _ = await loop.subprocess_exec(lambda: MyProtocol(exit_future),
877 sys.executable, '-c', code, stdin=None)
878 await exit_future
879 transport.close()
880
881 return events
882
883 events = self.loop.run_until_complete(main())
884
885 # First, make sure that we received all events
886 self.assertSetEqual(set(events), set(expected))
887
888 # Second, check order of pipe events per file descriptor
889 per_fd_events = {fd: [] for fd in fds}
890 for event in events:
891 if event == 'process_exited':
892 continue
893 name, fd = event[:2]
894 per_fd_events[fd].append(name)
895
896 for fd in fds:
897 self.assertEqual(per_fd_events[fd], per_fd_expected, (fd, events))
898
899 def test_subprocess_communicate_stdout(self):
900 # See https://github.com/python/cpython/issues/100133
901 async def get_command_stdout(cmd, *args):
902 proc = await asyncio.create_subprocess_exec(
903 cmd, *args, stdout=asyncio.subprocess.PIPE,
904 )
905 stdout, _ = await proc.communicate()
906 return stdout.decode().strip()
907
908 async def main():
909 outputs = [f'foo{i}' for i in range(10)]
910 res = await asyncio.gather(*[get_command_stdout(sys.executable, '-c',
911 f'print({out!r})') for out in outputs])
912 self.assertEqual(res, outputs)
913
914 self.loop.run_until_complete(main())
915
916 @unittest.skipIf(sys.platform != 'linux', "Linux only")
917 def test_subprocess_send_signal_race(self):
918 # See https://github.com/python/cpython/issues/87744
919 async def main():
920 for _ in range(10):
921 proc = await asyncio.create_subprocess_exec('sleep', '0.1')
922 await asyncio.sleep(0.1)
923 try:
924 proc.send_signal(signal.SIGUSR1)
925 except ProcessLookupError:
926 pass
927 self.assertNotEqual(await proc.wait(), 255)
928
929 self.loop.run_until_complete(main())
930
931 @warnings_helper.ignore_warnings(category=ResourceWarning)
932 def test_subprocess_read_pipe_cancelled(self):
933 async def main():
934 loop = asyncio.get_running_loop()
935 loop.connect_read_pipe = mock.AsyncMock(side_effect=asyncio.CancelledError)
936 with self.assertRaises(asyncio.CancelledError):
937 await asyncio.create_subprocess_exec(*PROGRAM_BLOCKED, stderr=asyncio.subprocess.PIPE)
938
939 asyncio.run(main())
940 gc_collect()
941
942 @warnings_helper.ignore_warnings(category=ResourceWarning)
943 def test_subprocess_write_pipe_cancelled(self):
944 async def main():
945 loop = asyncio.get_running_loop()
946 loop.connect_write_pipe = mock.AsyncMock(side_effect=asyncio.CancelledError)
947 with self.assertRaises(asyncio.CancelledError):
948 await asyncio.create_subprocess_exec(*PROGRAM_BLOCKED, stdin=asyncio.subprocess.PIPE)
949
950 asyncio.run(main())
951 gc_collect()
952
953 @warnings_helper.ignore_warnings(category=ResourceWarning)
954 def test_subprocess_read_write_pipe_cancelled(self):
955 async def main():
956 loop = asyncio.get_running_loop()
957 loop.connect_read_pipe = mock.AsyncMock(side_effect=asyncio.CancelledError)
958 loop.connect_write_pipe = mock.AsyncMock(side_effect=asyncio.CancelledError)
959 with self.assertRaises(asyncio.CancelledError):
960 await asyncio.create_subprocess_exec(
961 *PROGRAM_BLOCKED,
962 stdin=asyncio.subprocess.PIPE,
963 stdout=asyncio.subprocess.PIPE,
964 stderr=asyncio.subprocess.PIPE,
965 )
966
967 asyncio.run(main())
968 gc_collect()
969
970 if sys.platform != 'win32':
971 # Unix
972 class SubprocessWatcherMixin(SubprocessMixin):
973
974 Watcher = None
975
976 def setUp(self):
977 super().setUp()
978 policy = asyncio.get_event_loop_policy()
979 self.loop = policy.new_event_loop()
980 self.set_event_loop(self.loop)
981
982 watcher = self._get_watcher()
983 watcher.attach_loop(self.loop)
984 with warnings.catch_warnings():
985 warnings.simplefilter('ignore', DeprecationWarning)
986 policy.set_child_watcher(watcher)
987
988 def tearDown(self):
989 super().tearDown()
990 policy = asyncio.get_event_loop_policy()
991 with warnings.catch_warnings():
992 warnings.simplefilter('ignore', DeprecationWarning)
993 watcher = policy.get_child_watcher()
994 policy.set_child_watcher(None)
995 watcher.attach_loop(None)
996 watcher.close()
997
998 class SubprocessThreadedWatcherTests(SubprocessWatcherMixin,
999 test_utils.TestCase):
1000
1001 def _get_watcher(self):
1002 return unix_events.ThreadedChildWatcher()
1003
1004 class SubprocessSafeWatcherTests(SubprocessWatcherMixin,
1005 test_utils.TestCase):
1006
1007 def _get_watcher(self):
1008 with self.assertWarns(DeprecationWarning):
1009 return unix_events.SafeChildWatcher()
1010
1011 class MultiLoopChildWatcherTests(test_utils.TestCase):
1012
1013 def test_warns(self):
1014 with self.assertWarns(DeprecationWarning):
1015 unix_events.MultiLoopChildWatcher()
1016
1017 class SubprocessFastWatcherTests(SubprocessWatcherMixin,
1018 test_utils.TestCase):
1019
1020 def _get_watcher(self):
1021 with self.assertWarns(DeprecationWarning):
1022 return unix_events.FastChildWatcher()
1023
1024 @unittest.skipUnless(
1025 unix_events.can_use_pidfd(),
1026 "operating system does not support pidfds",
1027 )
1028 class SubprocessPidfdWatcherTests(SubprocessWatcherMixin,
1029 test_utils.TestCase):
1030
1031 def _get_watcher(self):
1032 return unix_events.PidfdChildWatcher()
1033
1034
1035 class GenericWatcherTests(test_utils.TestCase):
1036
1037 def test_create_subprocess_fails_with_inactive_watcher(self):
1038 watcher = mock.create_autospec(asyncio.AbstractChildWatcher)
1039 watcher.is_active.return_value = False
1040
1041 async def execute():
1042 asyncio.set_child_watcher(watcher)
1043
1044 with self.assertRaises(RuntimeError):
1045 await subprocess.create_subprocess_exec(
1046 os_helper.FakePath(sys.executable), '-c', 'pass')
1047
1048 watcher.add_child_handler.assert_not_called()
1049
1050 with asyncio.Runner(loop_factory=asyncio.new_event_loop) as runner:
1051 with warnings.catch_warnings():
1052 warnings.simplefilter('ignore', DeprecationWarning)
1053 self.assertIsNone(runner.run(execute()))
1054 self.assertListEqual(watcher.mock_calls, [
1055 mock.call.__enter__(),
1056 mock.call.is_active(),
1057 mock.call.__exit__(RuntimeError, mock.ANY, mock.ANY),
1058 ], watcher.mock_calls)
1059
1060
1061 @unittest.skipUnless(
1062 unix_events.can_use_pidfd(),
1063 "operating system does not support pidfds",
1064 )
1065 def test_create_subprocess_with_pidfd(self):
1066 async def in_thread():
1067 proc = await asyncio.create_subprocess_exec(
1068 *PROGRAM_CAT,
1069 stdin=subprocess.PIPE,
1070 stdout=subprocess.PIPE,
1071 )
1072 stdout, stderr = await proc.communicate(b"some data")
1073 return proc.returncode, stdout
1074
1075 async def main():
1076 # asyncio.Runner did not call asyncio.set_event_loop()
1077 with warnings.catch_warnings():
1078 warnings.simplefilter('error', DeprecationWarning)
1079 # get_event_loop() raises DeprecationWarning if
1080 # set_event_loop() was never called and RuntimeError if
1081 # it was called at least once.
1082 with self.assertRaises((RuntimeError, DeprecationWarning)):
1083 asyncio.get_event_loop_policy().get_event_loop()
1084 return await asyncio.to_thread(asyncio.run, in_thread())
1085 with self.assertWarns(DeprecationWarning):
1086 asyncio.set_child_watcher(asyncio.PidfdChildWatcher())
1087 try:
1088 with asyncio.Runner(loop_factory=asyncio.new_event_loop) as runner:
1089 returncode, stdout = runner.run(main())
1090 self.assertEqual(returncode, 0)
1091 self.assertEqual(stdout, b'some data')
1092 finally:
1093 with self.assertWarns(DeprecationWarning):
1094 asyncio.set_child_watcher(None)
1095 else:
1096 # Windows
1097 class SubprocessProactorTests(SubprocessMixin, test_utils.TestCase):
1098
1099 def setUp(self):
1100 super().setUp()
1101 self.loop = asyncio.ProactorEventLoop()
1102 self.set_event_loop(self.loop)
1103
1104
1105 if __name__ == '__main__':
1106 unittest.main()