blob: 4fe74bf504b4f114fb7209e78810ee64ddca4542 [file] [log] [blame]
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001import unittest
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)1ef8c7e2016-06-04 00:22:17 +00002from unittest import mock
Benjamin Petersonee8712c2008-05-20 21:35:26 +00003from test import support
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00004import subprocess
5import sys
6import signal
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04007import io
Alexey Izbyshev0e7144b2018-03-26 22:49:35 +03008import itertools
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00009import os
Gregory P. Smitha59c59f2010-03-01 00:17:40 +000010import errno
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000011import tempfile
12import time
Charles-François Natali3a4586a2013-11-08 19:56:59 +010013import selectors
Ezio Melotti184bdfb2010-02-18 09:37:05 +000014import sysconfig
Gregory P. Smith51ee2702010-12-13 07:59:39 +000015import select
Gregory P. Smith81ce6852011-03-15 02:04:11 -040016import shutil
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020017import threading
Benjamin Petersonb870aa12011-12-10 12:44:25 -050018import gc
Andrew Svetlov47ec25d2012-08-19 16:25:37 +030019import textwrap
Serhiy Storchakab21d1552018-03-02 11:53:51 +020020from test.support import FakePath
Benjamin Peterson964561b2011-12-10 12:31:42 -050021
22try:
Victor Stinner7b7c6dc2017-08-10 12:37:39 +020023 import _testcapi
24except ImportError:
25 _testcapi = None
26
Victor Stinner8f4ef3b2019-07-01 18:28:25 +020027
Steve Dower22d06982016-09-06 19:38:15 -070028if support.PGO:
29 raise unittest.SkipTest("test is not helpful for PGO")
30
Victor Stinner937ee9e2018-06-26 02:11:06 +020031mswindows = (sys.platform == "win32")
32
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000033#
34# Depends on the following external programs: Python
35#
36
Victor Stinner937ee9e2018-06-26 02:11:06 +020037if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000038 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
39 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000040else:
41 SETBINARY = ''
42
Victor Stinner9a83f652017-08-21 23:51:31 +020043NONEXISTING_CMD = ('nonexisting_i_hope',)
Victor Stinnerb31206a2018-01-25 19:06:05 +010044# Ignore errors that indicate the command was not found
45NONEXISTING_ERRORS = (FileNotFoundError, NotADirectoryError, PermissionError)
Victor Stinner9a83f652017-08-21 23:51:31 +020046
Florent Xiclunab1e94e82010-02-27 22:12:37 +000047
Florent Xiclunac049d872010-03-27 22:47:23 +000048class BaseTestCase(unittest.TestCase):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000049 def setUp(self):
50 # Try to minimize the number of children we have so this test
51 # doesn't crash on some buildbots (Alphas in particular).
Florent Xiclunab1e94e82010-02-27 22:12:37 +000052 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000053
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000054 def tearDown(self):
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +030055 if not mswindows:
56 # subprocess._active is not used on Windows and is set to None.
57 for inst in subprocess._active:
58 inst.wait()
59 subprocess._cleanup()
60 self.assertFalse(
61 subprocess._active, "subprocess._active not empty"
62 )
Victor Stinnercc42c122017-07-28 18:00:22 +020063 self.doCleanups()
64 support.reap_children()
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000065
Florent Xiclunab1e94e82010-02-27 22:12:37 +000066 def assertStderrEqual(self, stderr, expected, msg=None):
67 # In a debug build, stuff like "[6580 refs]" is printed to stderr at
68 # shutdown time. That frustrates tests trying to check stderr produced
69 # from a spawned Python process.
Antoine Pitrou62f68ed2010-08-04 11:48:56 +000070 actual = support.strip_python_stderr(stderr)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -040071 # strip_python_stderr also strips whitespace, so we do too.
72 expected = expected.strip()
Florent Xiclunab1e94e82010-02-27 22:12:37 +000073 self.assertEqual(actual, expected, msg)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000074
Florent Xiclunac049d872010-03-27 22:47:23 +000075
Gregory P. Smith3d8e7762012-11-10 22:32:22 -080076class PopenTestException(Exception):
77 pass
78
79
80class PopenExecuteChildRaises(subprocess.Popen):
81 """Popen subclass for testing cleanup of subprocess.PIPE filehandles when
82 _execute_child fails.
83 """
84 def _execute_child(self, *args, **kwargs):
85 raise PopenTestException("Forced Exception for Test")
86
87
Florent Xiclunac049d872010-03-27 22:47:23 +000088class ProcessTestCase(BaseTestCase):
89
Gregory P. Smitha1ed5392013-03-23 11:44:25 -070090 def test_io_buffered_by_default(self):
91 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
92 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
93 stderr=subprocess.PIPE)
94 try:
95 self.assertIsInstance(p.stdin, io.BufferedIOBase)
96 self.assertIsInstance(p.stdout, io.BufferedIOBase)
97 self.assertIsInstance(p.stderr, io.BufferedIOBase)
98 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -070099 p.stdin.close()
100 p.stdout.close()
101 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700102 p.wait()
103
104 def test_io_unbuffered_works(self):
105 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
106 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
107 stderr=subprocess.PIPE, bufsize=0)
108 try:
109 self.assertIsInstance(p.stdin, io.RawIOBase)
110 self.assertIsInstance(p.stdout, io.RawIOBase)
111 self.assertIsInstance(p.stderr, io.RawIOBase)
112 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -0700113 p.stdin.close()
114 p.stdout.close()
115 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700116 p.wait()
117
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000118 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000119 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +0000120 rc = subprocess.call([sys.executable, "-c",
121 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000122 self.assertEqual(rc, 47)
123
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400124 def test_call_timeout(self):
125 # call() function with timeout argument; we want to test that the child
126 # process gets killed when the timeout expires. If the child isn't
127 # killed, this call will deadlock since subprocess.call waits for the
128 # child.
129 self.assertRaises(subprocess.TimeoutExpired, subprocess.call,
130 [sys.executable, "-c", "while True: pass"],
131 timeout=0.1)
132
Peter Astrand454f7672005-01-01 09:36:35 +0000133 def test_check_call_zero(self):
134 # check_call() function with zero return code
135 rc = subprocess.check_call([sys.executable, "-c",
136 "import sys; sys.exit(0)"])
137 self.assertEqual(rc, 0)
138
139 def test_check_call_nonzero(self):
140 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000141 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +0000142 subprocess.check_call([sys.executable, "-c",
143 "import sys; sys.exit(47)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000144 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +0000145
Georg Brandlf9734072008-12-07 15:30:06 +0000146 def test_check_output(self):
147 # check_output() function with zero return code
148 output = subprocess.check_output(
149 [sys.executable, "-c", "print('BDFL')"])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000150 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000151
152 def test_check_output_nonzero(self):
153 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000154 with self.assertRaises(subprocess.CalledProcessError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000155 subprocess.check_output(
156 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000157 self.assertEqual(c.exception.returncode, 5)
Georg Brandlf9734072008-12-07 15:30:06 +0000158
159 def test_check_output_stderr(self):
160 # check_output() function stderr redirected to stdout
161 output = subprocess.check_output(
162 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
163 stderr=subprocess.STDOUT)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000164 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000165
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300166 def test_check_output_stdin_arg(self):
167 # check_output() can be called with stdin set to a file
168 tf = tempfile.TemporaryFile()
169 self.addCleanup(tf.close)
170 tf.write(b'pear')
171 tf.seek(0)
172 output = subprocess.check_output(
173 [sys.executable, "-c",
174 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
175 stdin=tf)
176 self.assertIn(b'PEAR', output)
177
178 def test_check_output_input_arg(self):
179 # check_output() can be called with input set to a string
180 output = subprocess.check_output(
181 [sys.executable, "-c",
182 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
183 input=b'pear')
184 self.assertIn(b'PEAR', output)
185
Georg Brandlf9734072008-12-07 15:30:06 +0000186 def test_check_output_stdout_arg(self):
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300187 # check_output() refuses to accept 'stdout' argument
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000188 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000189 output = subprocess.check_output(
190 [sys.executable, "-c", "print('will not be run')"],
191 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +0000192 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000193 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +0000194
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300195 def test_check_output_stdin_with_input_arg(self):
196 # check_output() refuses to accept 'stdin' with 'input'
197 tf = tempfile.TemporaryFile()
198 self.addCleanup(tf.close)
199 tf.write(b'pear')
200 tf.seek(0)
201 with self.assertRaises(ValueError) as c:
202 output = subprocess.check_output(
203 [sys.executable, "-c", "print('will not be run')"],
204 stdin=tf, input=b'hare')
205 self.fail("Expected ValueError when stdin and input args supplied.")
206 self.assertIn('stdin', c.exception.args[0])
207 self.assertIn('input', c.exception.args[0])
208
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400209 def test_check_output_timeout(self):
210 # check_output() function with timeout arg
211 with self.assertRaises(subprocess.TimeoutExpired) as c:
212 output = subprocess.check_output(
213 [sys.executable, "-c",
Victor Stinner149b1c72011-06-06 23:43:02 +0200214 "import sys, time\n"
215 "sys.stdout.write('BDFL')\n"
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400216 "sys.stdout.flush()\n"
Victor Stinner149b1c72011-06-06 23:43:02 +0200217 "time.sleep(3600)"],
Reid Klecknerda9ac722011-03-16 17:08:21 -0400218 # Some heavily loaded buildbots (sparc Debian 3.x) require
219 # this much time to start and print.
220 timeout=3)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400221 self.fail("Expected TimeoutExpired.")
222 self.assertEqual(c.exception.output, b'BDFL')
223
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000224 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000225 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000226 newenv = os.environ.copy()
227 newenv["FRUIT"] = "banana"
228 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000229 'import sys, os;'
230 'sys.exit(os.getenv("FRUIT")=="banana")'],
231 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000232 self.assertEqual(rc, 1)
233
Victor Stinner87b9bc32011-06-01 00:57:47 +0200234 def test_invalid_args(self):
235 # Popen() called with invalid arguments should raise TypeError
236 # but Popen.__del__ should not complain (issue #12085)
237 with support.captured_stderr() as s:
238 self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1)
239 argcount = subprocess.Popen.__init__.__code__.co_argcount
240 too_many_args = [0] * (argcount + 1)
241 self.assertRaises(TypeError, subprocess.Popen, *too_many_args)
242 self.assertEqual(s.getvalue(), '')
243
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000244 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000245 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000246 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000247 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000248 self.addCleanup(p.stdout.close)
249 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000250 p.wait()
251 self.assertEqual(p.stdin, None)
252
253 def test_stdout_none(self):
Ezio Melotti42a541b2013-03-11 05:53:34 +0200254 # .stdout is None when not redirected, and the child's stdout will
255 # be inherited from the parent. In order to test this we run a
256 # subprocess in a subprocess:
257 # this_test
258 # \-- subprocess created by this test (parent)
259 # \-- subprocess created by the parent subprocess (child)
260 # The parent doesn't specify stdout, so the child will use the
261 # parent's stdout. This test checks that the message printed by the
262 # child goes to the parent stdout. The parent also checks that the
263 # child's stdout is None. See #11963.
264 code = ('import sys; from subprocess import Popen, PIPE;'
265 'p = Popen([sys.executable, "-c", "print(\'test_stdout_none\')"],'
266 ' stdin=PIPE, stderr=PIPE);'
267 'p.wait(); assert p.stdout is None;')
268 p = subprocess.Popen([sys.executable, "-c", code],
269 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
270 self.addCleanup(p.stdout.close)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000271 self.addCleanup(p.stderr.close)
Ezio Melotti42a541b2013-03-11 05:53:34 +0200272 out, err = p.communicate()
273 self.assertEqual(p.returncode, 0, err)
274 self.assertEqual(out.rstrip(), b'test_stdout_none')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000275
276 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000277 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000278 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000279 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000280 self.addCleanup(p.stdout.close)
281 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000282 p.wait()
283 self.assertEqual(p.stderr, None)
284
Chris Jerdonek776cb192012-10-08 15:56:43 -0700285 def _assert_python(self, pre_args, **kwargs):
286 # We include sys.exit() to prevent the test runner from hanging
287 # whenever python is found.
288 args = pre_args + ["import sys; sys.exit(47)"]
289 p = subprocess.Popen(args, **kwargs)
290 p.wait()
291 self.assertEqual(47, p.returncode)
292
293 def test_executable(self):
294 # Check that the executable argument works.
Chris Jerdonek86b0fb22012-10-09 13:17:49 -0700295 #
296 # On Unix (non-Mac and non-Windows), Python looks at args[0] to
297 # determine where its standard library is, so we need the directory
298 # of args[0] to be valid for the Popen() call to Python to succeed.
299 # See also issue #16170 and issue #7774.
300 doesnotexist = os.path.join(os.path.dirname(sys.executable),
301 "doesnotexist")
302 self._assert_python([doesnotexist, "-c"], executable=sys.executable)
Chris Jerdonek776cb192012-10-08 15:56:43 -0700303
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +0300304 def test_bytes_executable(self):
305 doesnotexist = os.path.join(os.path.dirname(sys.executable),
306 "doesnotexist")
307 self._assert_python([doesnotexist, "-c"],
308 executable=os.fsencode(sys.executable))
309
310 def test_pathlike_executable(self):
311 doesnotexist = os.path.join(os.path.dirname(sys.executable),
312 "doesnotexist")
313 self._assert_python([doesnotexist, "-c"],
314 executable=FakePath(sys.executable))
315
Chris Jerdonek776cb192012-10-08 15:56:43 -0700316 def test_executable_takes_precedence(self):
317 # Check that the executable argument takes precedence over args[0].
318 #
319 # Verify first that the call succeeds without the executable arg.
320 pre_args = [sys.executable, "-c"]
321 self._assert_python(pre_args)
Victor Stinnerb31206a2018-01-25 19:06:05 +0100322 self.assertRaises(NONEXISTING_ERRORS,
Xavier de Gaye38c8b7d2016-11-14 17:14:42 +0100323 self._assert_python, pre_args,
Victor Stinnerb31206a2018-01-25 19:06:05 +0100324 executable=NONEXISTING_CMD[0])
Chris Jerdonek776cb192012-10-08 15:56:43 -0700325
Victor Stinner937ee9e2018-06-26 02:11:06 +0200326 @unittest.skipIf(mswindows, "executable argument replaces shell")
Chris Jerdonek776cb192012-10-08 15:56:43 -0700327 def test_executable_replaces_shell(self):
328 # Check that the executable argument replaces the default shell
329 # when shell=True.
330 self._assert_python([], executable=sys.executable, shell=True)
331
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +0300332 @unittest.skipIf(mswindows, "executable argument replaces shell")
333 def test_bytes_executable_replaces_shell(self):
334 self._assert_python([], executable=os.fsencode(sys.executable),
335 shell=True)
336
337 @unittest.skipIf(mswindows, "executable argument replaces shell")
338 def test_pathlike_executable_replaces_shell(self):
339 self._assert_python([], executable=FakePath(sys.executable),
340 shell=True)
341
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700342 # For use in the test_cwd* tests below.
343 def _normalize_cwd(self, cwd):
344 # Normalize an expected cwd (for Tru64 support).
345 # We can't use os.path.realpath since it doesn't expand Tru64 {memb}
346 # strings. See bug #1063571.
Serhiy Storchaka2a23adf2015-09-06 14:13:25 +0300347 with support.change_cwd(cwd):
348 return os.getcwd()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700349
350 # For use in the test_cwd* tests below.
351 def _split_python_path(self):
352 # Return normalized (python_dir, python_base).
353 python_path = os.path.realpath(sys.executable)
354 return os.path.split(python_path)
355
356 # For use in the test_cwd* tests below.
357 def _assert_cwd(self, expected_cwd, python_arg, **kwargs):
358 # Invoke Python via Popen, and assert that (1) the call succeeds,
359 # and that (2) the current working directory of the child process
360 # matches *expected_cwd*.
361 p = subprocess.Popen([python_arg, "-c",
362 "import os, sys; "
363 "sys.stdout.write(os.getcwd()); "
364 "sys.exit(47)"],
365 stdout=subprocess.PIPE,
366 **kwargs)
367 self.addCleanup(p.stdout.close)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000368 p.wait()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700369 self.assertEqual(47, p.returncode)
370 normcase = os.path.normcase
371 self.assertEqual(normcase(expected_cwd),
372 normcase(p.stdout.read().decode("utf-8")))
373
374 def test_cwd(self):
375 # Check that cwd changes the cwd for the child process.
376 temp_dir = tempfile.gettempdir()
377 temp_dir = self._normalize_cwd(temp_dir)
378 self._assert_cwd(temp_dir, sys.executable, cwd=temp_dir)
379
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +0300380 def test_cwd_with_bytes(self):
381 temp_dir = tempfile.gettempdir()
382 temp_dir = self._normalize_cwd(temp_dir)
383 self._assert_cwd(temp_dir, sys.executable, cwd=os.fsencode(temp_dir))
384
Sayan Chowdhuryd5c11f72017-02-26 22:36:10 +0530385 def test_cwd_with_pathlike(self):
386 temp_dir = tempfile.gettempdir()
387 temp_dir = self._normalize_cwd(temp_dir)
Serhiy Storchakab21d1552018-03-02 11:53:51 +0200388 self._assert_cwd(temp_dir, sys.executable, cwd=FakePath(temp_dir))
Sayan Chowdhuryd5c11f72017-02-26 22:36:10 +0530389
Victor Stinner937ee9e2018-06-26 02:11:06 +0200390 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700391 def test_cwd_with_relative_arg(self):
392 # Check that Popen looks for args[0] relative to cwd if args[0]
393 # is relative.
394 python_dir, python_base = self._split_python_path()
395 rel_python = os.path.join(os.curdir, python_base)
396 with support.temp_cwd() as wrong_dir:
397 # Before calling with the correct cwd, confirm that the call fails
398 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700399 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700400 [rel_python])
Chris Jerdonek28714c82012-09-30 02:15:37 -0700401 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700402 [rel_python], cwd=wrong_dir)
403 python_dir = self._normalize_cwd(python_dir)
404 self._assert_cwd(python_dir, rel_python, cwd=python_dir)
405
Victor Stinner937ee9e2018-06-26 02:11:06 +0200406 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700407 def test_cwd_with_relative_executable(self):
408 # Check that Popen looks for executable relative to cwd if executable
409 # is relative (and that executable takes precedence over args[0]).
410 python_dir, python_base = self._split_python_path()
411 rel_python = os.path.join(os.curdir, python_base)
412 doesntexist = "somethingyoudonthave"
413 with support.temp_cwd() as wrong_dir:
414 # Before calling with the correct cwd, confirm that the call fails
415 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700416 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700417 [doesntexist], executable=rel_python)
Chris Jerdonek28714c82012-09-30 02:15:37 -0700418 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700419 [doesntexist], executable=rel_python,
420 cwd=wrong_dir)
421 python_dir = self._normalize_cwd(python_dir)
422 self._assert_cwd(python_dir, doesntexist, executable=rel_python,
423 cwd=python_dir)
424
425 def test_cwd_with_absolute_arg(self):
426 # Check that Popen can find the executable when the cwd is wrong
427 # if args[0] is an absolute path.
428 python_dir, python_base = self._split_python_path()
429 abs_python = os.path.join(python_dir, python_base)
430 rel_python = os.path.join(os.curdir, python_base)
Berker Peksagce643912015-05-06 06:33:17 +0300431 with support.temp_dir() as wrong_dir:
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700432 # Before calling with an absolute path, confirm that using a
433 # relative path fails.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700434 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700435 [rel_python], cwd=wrong_dir)
436 wrong_dir = self._normalize_cwd(wrong_dir)
437 self._assert_cwd(wrong_dir, abs_python, cwd=wrong_dir)
438
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100439 @unittest.skipIf(sys.base_prefix != sys.prefix,
440 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000441 def test_executable_with_cwd(self):
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700442 python_dir, python_base = self._split_python_path()
443 python_dir = self._normalize_cwd(python_dir)
444 self._assert_cwd(python_dir, "somethingyoudonthave",
445 executable=sys.executable, cwd=python_dir)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000446
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100447 @unittest.skipIf(sys.base_prefix != sys.prefix,
448 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000449 @unittest.skipIf(sysconfig.is_python_build(),
450 "need an installed Python. See #7774")
451 def test_executable_without_cwd(self):
452 # For a normal installation, it should work without 'cwd'
453 # argument. For test runs in the build directory, see #7774.
Ned Deilye92dfbf2013-08-02 18:02:21 -0700454 self._assert_cwd(os.getcwd(), "somethingyoudonthave",
455 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000456
457 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000458 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000459 p = subprocess.Popen([sys.executable, "-c",
460 'import sys; sys.exit(sys.stdin.read() == "pear")'],
461 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000462 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000463 p.stdin.close()
464 p.wait()
465 self.assertEqual(p.returncode, 1)
466
467 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000468 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000469 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000470 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000471 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000472 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000473 os.lseek(d, 0, 0)
474 p = subprocess.Popen([sys.executable, "-c",
475 'import sys; sys.exit(sys.stdin.read() == "pear")'],
476 stdin=d)
477 p.wait()
478 self.assertEqual(p.returncode, 1)
479
480 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000481 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000482 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000483 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000484 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000485 tf.seek(0)
486 p = subprocess.Popen([sys.executable, "-c",
487 'import sys; sys.exit(sys.stdin.read() == "pear")'],
488 stdin=tf)
489 p.wait()
490 self.assertEqual(p.returncode, 1)
491
492 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000493 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000494 p = subprocess.Popen([sys.executable, "-c",
495 'import sys; sys.stdout.write("orange")'],
496 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +0200497 with p:
498 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000499
500 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000501 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000502 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000503 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000504 d = tf.fileno()
505 p = subprocess.Popen([sys.executable, "-c",
506 'import sys; sys.stdout.write("orange")'],
507 stdout=d)
508 p.wait()
509 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000510 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000511
512 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000513 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000514 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000515 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000516 p = subprocess.Popen([sys.executable, "-c",
517 'import sys; sys.stdout.write("orange")'],
518 stdout=tf)
519 p.wait()
520 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000521 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000522
523 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000524 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000525 p = subprocess.Popen([sys.executable, "-c",
526 'import sys; sys.stderr.write("strawberry")'],
527 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +0200528 with p:
529 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000530
531 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000532 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000533 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000534 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000535 d = tf.fileno()
536 p = subprocess.Popen([sys.executable, "-c",
537 'import sys; sys.stderr.write("strawberry")'],
538 stderr=d)
539 p.wait()
540 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000541 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000542
543 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000544 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000545 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000546 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000547 p = subprocess.Popen([sys.executable, "-c",
548 'import sys; sys.stderr.write("strawberry")'],
549 stderr=tf)
550 p.wait()
551 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000552 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000553
Martin Panterc7635892016-05-13 01:54:44 +0000554 def test_stderr_redirect_with_no_stdout_redirect(self):
555 # test stderr=STDOUT while stdout=None (not set)
556
557 # - grandchild prints to stderr
558 # - child redirects grandchild's stderr to its stdout
559 # - the parent should get grandchild's stderr in child's stdout
560 p = subprocess.Popen([sys.executable, "-c",
561 'import sys, subprocess;'
562 'rc = subprocess.call([sys.executable, "-c",'
563 ' "import sys;"'
564 ' "sys.stderr.write(\'42\')"],'
565 ' stderr=subprocess.STDOUT);'
566 'sys.exit(rc)'],
567 stdout=subprocess.PIPE,
568 stderr=subprocess.PIPE)
569 stdout, stderr = p.communicate()
570 #NOTE: stdout should get stderr from grandchild
571 self.assertStderrEqual(stdout, b'42')
572 self.assertStderrEqual(stderr, b'') # should be empty
573 self.assertEqual(p.returncode, 0)
574
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000575 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000576 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000577 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000578 'import sys;'
579 'sys.stdout.write("apple");'
580 'sys.stdout.flush();'
581 'sys.stderr.write("orange")'],
582 stdout=subprocess.PIPE,
583 stderr=subprocess.STDOUT)
Victor Stinner7438c612016-05-20 12:43:15 +0200584 with p:
585 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000586
587 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000588 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000589 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000590 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000591 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000592 'import sys;'
593 'sys.stdout.write("apple");'
594 'sys.stdout.flush();'
595 'sys.stderr.write("orange")'],
596 stdout=tf,
597 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000598 p.wait()
599 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000600 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000601
Thomas Wouters89f507f2006-12-13 04:49:30 +0000602 def test_stdout_filedes_of_stdout(self):
603 # stdout is set to 1 (#1531862).
Ezio Melotti42a541b2013-03-11 05:53:34 +0200604 # To avoid printing the text on stdout, we do something similar to
605 # test_stdout_none (see above). The parent subprocess calls the child
606 # subprocess passing stdout=1, and this test uses stdout=PIPE in
607 # order to capture and check the output of the parent. See #11963.
608 code = ('import sys, subprocess; '
609 'rc = subprocess.call([sys.executable, "-c", '
610 ' "import os, sys; sys.exit(os.write(sys.stdout.fileno(), '
611 'b\'test with stdout=1\'))"], stdout=1); '
612 'assert rc == 18')
613 p = subprocess.Popen([sys.executable, "-c", code],
614 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
615 self.addCleanup(p.stdout.close)
616 self.addCleanup(p.stderr.close)
617 out, err = p.communicate()
618 self.assertEqual(p.returncode, 0, err)
619 self.assertEqual(out.rstrip(), b'test with stdout=1')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000620
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200621 def test_stdout_devnull(self):
622 p = subprocess.Popen([sys.executable, "-c",
623 'for i in range(10240):'
624 'print("x" * 1024)'],
625 stdout=subprocess.DEVNULL)
626 p.wait()
627 self.assertEqual(p.stdout, None)
628
629 def test_stderr_devnull(self):
630 p = subprocess.Popen([sys.executable, "-c",
631 'import sys\n'
632 'for i in range(10240):'
633 'sys.stderr.write("x" * 1024)'],
634 stderr=subprocess.DEVNULL)
635 p.wait()
636 self.assertEqual(p.stderr, None)
637
638 def test_stdin_devnull(self):
639 p = subprocess.Popen([sys.executable, "-c",
640 'import sys;'
641 'sys.stdin.read(1)'],
642 stdin=subprocess.DEVNULL)
643 p.wait()
644 self.assertEqual(p.stdin, None)
645
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000646 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000647 newenv = os.environ.copy()
648 newenv["FRUIT"] = "orange"
Victor Stinnerf1512a22011-06-21 17:18:38 +0200649 with subprocess.Popen([sys.executable, "-c",
650 'import sys,os;'
651 'sys.stdout.write(os.getenv("FRUIT"))'],
652 stdout=subprocess.PIPE,
653 env=newenv) as p:
654 stdout, stderr = p.communicate()
655 self.assertEqual(stdout, b"orange")
656
Victor Stinner62d51182011-06-23 01:02:25 +0200657 # Windows requires at least the SYSTEMROOT environment variable to start
658 # Python
659 @unittest.skipIf(sys.platform == 'win32',
660 'cannot test an empty env on Windows')
Gregory P. Smithb3512482017-05-30 14:40:37 -0700661 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') == 1,
662 'The Python shared library cannot be loaded '
663 'with an empty environment.')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200664 def test_empty_env(self):
Gregory P. Smithb3512482017-05-30 14:40:37 -0700665 """Verify that env={} is as empty as possible."""
666
Gregory P. Smith85aba232017-05-30 16:21:47 -0700667 def is_env_var_to_ignore(n):
Gregory P. Smithb3512482017-05-30 14:40:37 -0700668 """Determine if an environment variable is under our control."""
669 # This excludes some __CF_* and VERSIONER_* keys MacOS insists
670 # on adding even when the environment in exec is empty.
671 # Gentoo sandboxes also force LD_PRELOAD and SANDBOX_* to exist.
Gregory P. Smith85aba232017-05-30 16:21:47 -0700672 return ('VERSIONER' in n or '__CF' in n or # MacOS
Ned Deily918edc02017-09-04 00:00:21 -0400673 '__PYVENV_LAUNCHER__' in n or # MacOS framework build
Nick Coghlan6ea41862017-06-11 13:16:15 +1000674 n == 'LD_PRELOAD' or n.startswith('SANDBOX') or # Gentoo
675 n == 'LC_CTYPE') # Locale coercion triggered
Gregory P. Smithb3512482017-05-30 14:40:37 -0700676
Victor Stinnerf1512a22011-06-21 17:18:38 +0200677 with subprocess.Popen([sys.executable, "-c",
Gregory P. Smithb3512482017-05-30 14:40:37 -0700678 'import os; print(list(os.environ.keys()))'],
679 stdout=subprocess.PIPE, env={}) as p:
Victor Stinnerf1512a22011-06-21 17:18:38 +0200680 stdout, stderr = p.communicate()
Gregory P. Smithb3512482017-05-30 14:40:37 -0700681 child_env_names = eval(stdout.strip())
682 self.assertIsInstance(child_env_names, list)
683 child_env_names = [k for k in child_env_names
684 if not is_env_var_to_ignore(k)]
685 self.assertEqual(child_env_names, [])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000686
Serhiy Storchakad174d242017-06-23 19:39:27 +0300687 def test_invalid_cmd(self):
688 # null character in the command name
689 cmd = sys.executable + '\0'
690 with self.assertRaises(ValueError):
691 subprocess.Popen([cmd, "-c", "pass"])
692
693 # null character in the command argument
694 with self.assertRaises(ValueError):
695 subprocess.Popen([sys.executable, "-c", "pass#\0"])
696
697 def test_invalid_env(self):
Ville Skyttä49b27342017-08-03 09:00:59 +0300698 # null character in the environment variable name
Serhiy Storchakad174d242017-06-23 19:39:27 +0300699 newenv = os.environ.copy()
700 newenv["FRUIT\0VEGETABLE"] = "cabbage"
701 with self.assertRaises(ValueError):
702 subprocess.Popen([sys.executable, "-c", "pass"], env=newenv)
703
Ville Skyttä49b27342017-08-03 09:00:59 +0300704 # null character in the environment variable value
Serhiy Storchakad174d242017-06-23 19:39:27 +0300705 newenv = os.environ.copy()
706 newenv["FRUIT"] = "orange\0VEGETABLE=cabbage"
707 with self.assertRaises(ValueError):
708 subprocess.Popen([sys.executable, "-c", "pass"], env=newenv)
709
Ville Skyttä49b27342017-08-03 09:00:59 +0300710 # equal character in the environment variable name
Serhiy Storchakad174d242017-06-23 19:39:27 +0300711 newenv = os.environ.copy()
712 newenv["FRUIT=ORANGE"] = "lemon"
713 with self.assertRaises(ValueError):
714 subprocess.Popen([sys.executable, "-c", "pass"], env=newenv)
715
Ville Skyttä49b27342017-08-03 09:00:59 +0300716 # equal character in the environment variable value
Serhiy Storchakad174d242017-06-23 19:39:27 +0300717 newenv = os.environ.copy()
718 newenv["FRUIT"] = "orange=lemon"
719 with subprocess.Popen([sys.executable, "-c",
720 'import sys, os;'
721 'sys.stdout.write(os.getenv("FRUIT"))'],
722 stdout=subprocess.PIPE,
723 env=newenv) as p:
724 stdout, stderr = p.communicate()
725 self.assertEqual(stdout, b"orange=lemon")
726
Peter Astrandcbac93c2005-03-03 20:24:28 +0000727 def test_communicate_stdin(self):
728 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000729 'import sys;'
730 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000731 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000732 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000733 self.assertEqual(p.returncode, 1)
734
735 def test_communicate_stdout(self):
736 p = subprocess.Popen([sys.executable, "-c",
737 'import sys; sys.stdout.write("pineapple")'],
738 stdout=subprocess.PIPE)
739 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000740 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000741 self.assertEqual(stderr, None)
742
743 def test_communicate_stderr(self):
744 p = subprocess.Popen([sys.executable, "-c",
745 'import sys; sys.stderr.write("pineapple")'],
746 stderr=subprocess.PIPE)
747 (stdout, stderr) = p.communicate()
748 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000749 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000750
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000751 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000752 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000753 'import sys,os;'
754 'sys.stderr.write("pineapple");'
755 'sys.stdout.write(sys.stdin.read())'],
756 stdin=subprocess.PIPE,
757 stdout=subprocess.PIPE,
758 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000759 self.addCleanup(p.stdout.close)
760 self.addCleanup(p.stderr.close)
761 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000762 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000763 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000764 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000765
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400766 def test_communicate_timeout(self):
767 p = subprocess.Popen([sys.executable, "-c",
768 'import sys,os,time;'
769 'sys.stderr.write("pineapple\\n");'
770 'time.sleep(1);'
771 'sys.stderr.write("pear\\n");'
772 'sys.stdout.write(sys.stdin.read())'],
773 universal_newlines=True,
774 stdin=subprocess.PIPE,
775 stdout=subprocess.PIPE,
776 stderr=subprocess.PIPE)
777 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
778 timeout=0.3)
779 # Make sure we can keep waiting for it, and that we get the whole output
780 # after it completes.
781 (stdout, stderr) = p.communicate()
782 self.assertEqual(stdout, "banana")
783 self.assertStderrEqual(stderr.encode(), b"pineapple\npear\n")
784
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700785 def test_communicate_timeout_large_output(self):
Ross Lagerwall003c7a32012-02-12 09:02:01 +0200786 # Test an expiring timeout while the child is outputting lots of data.
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400787 p = subprocess.Popen([sys.executable, "-c",
788 'import sys,os,time;'
789 'sys.stdout.write("a" * (64 * 1024));'
790 'time.sleep(0.2);'
791 'sys.stdout.write("a" * (64 * 1024));'
792 'time.sleep(0.2);'
793 'sys.stdout.write("a" * (64 * 1024));'
794 'time.sleep(0.2);'
795 'sys.stdout.write("a" * (64 * 1024));'],
796 stdout=subprocess.PIPE)
797 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
798 (stdout, _) = p.communicate()
799 self.assertEqual(len(stdout), 4 * 64 * 1024)
800
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000801 # Test for the fd leak reported in http://bugs.python.org/issue2791.
802 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000803 for stdin_pipe in (False, True):
804 for stdout_pipe in (False, True):
805 for stderr_pipe in (False, True):
806 options = {}
807 if stdin_pipe:
808 options['stdin'] = subprocess.PIPE
809 if stdout_pipe:
810 options['stdout'] = subprocess.PIPE
811 if stderr_pipe:
812 options['stderr'] = subprocess.PIPE
813 if not options:
814 continue
815 p = subprocess.Popen((sys.executable, "-c", "pass"), **options)
816 p.communicate()
817 if p.stdin is not None:
818 self.assertTrue(p.stdin.closed)
819 if p.stdout is not None:
820 self.assertTrue(p.stdout.closed)
821 if p.stderr is not None:
822 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000823
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000824 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000825 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000826 p = subprocess.Popen([sys.executable, "-c",
827 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000828 (stdout, stderr) = p.communicate()
829 self.assertEqual(stdout, None)
830 self.assertEqual(stderr, None)
831
832 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000833 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000834 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000835 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000836 x, y = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000837 os.close(x)
838 os.close(y)
839 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000840 'import sys,os;'
841 'sys.stdout.write(sys.stdin.read(47));'
Charles-François Natali2d517212011-05-29 16:36:44 +0200842 'sys.stderr.write("x" * %d);'
843 'sys.stdout.write(sys.stdin.read())' %
844 support.PIPE_MAX_SIZE],
Guido van Rossum98297ee2007-11-06 21:34:58 +0000845 stdin=subprocess.PIPE,
846 stdout=subprocess.PIPE,
847 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000848 self.addCleanup(p.stdout.close)
849 self.addCleanup(p.stderr.close)
850 self.addCleanup(p.stdin.close)
Charles-François Natali2d517212011-05-29 16:36:44 +0200851 string_to_write = b"a" * support.PIPE_MAX_SIZE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000852 (stdout, stderr) = p.communicate(string_to_write)
853 self.assertEqual(stdout, string_to_write)
854
855 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000856 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000857 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000858 'import sys,os;'
859 'sys.stdout.write(sys.stdin.read())'],
860 stdin=subprocess.PIPE,
861 stdout=subprocess.PIPE,
862 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000863 self.addCleanup(p.stdout.close)
864 self.addCleanup(p.stderr.close)
865 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000866 p.stdin.write(b"banana")
867 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000868 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000869 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000870
andyclegg7fed7bd2017-10-23 03:01:19 +0100871 def test_universal_newlines_and_text(self):
872 args = [
873 sys.executable, "-c",
874 'import sys,os;' + SETBINARY +
875 'buf = sys.stdout.buffer;'
876 'buf.write(sys.stdin.readline().encode());'
877 'buf.flush();'
878 'buf.write(b"line2\\n");'
879 'buf.flush();'
880 'buf.write(sys.stdin.read().encode());'
881 'buf.flush();'
882 'buf.write(b"line4\\n");'
883 'buf.flush();'
884 'buf.write(b"line5\\r\\n");'
885 'buf.flush();'
886 'buf.write(b"line6\\r");'
887 'buf.flush();'
888 'buf.write(b"\\nline7");'
889 'buf.flush();'
890 'buf.write(b"\\nline8");']
891
892 for extra_kwarg in ('universal_newlines', 'text'):
893 p = subprocess.Popen(args, **{'stdin': subprocess.PIPE,
894 'stdout': subprocess.PIPE,
895 extra_kwarg: True})
896 with p:
897 p.stdin.write("line1\n")
898 p.stdin.flush()
899 self.assertEqual(p.stdout.readline(), "line1\n")
900 p.stdin.write("line3\n")
901 p.stdin.close()
902 self.addCleanup(p.stdout.close)
903 self.assertEqual(p.stdout.readline(),
904 "line2\n")
905 self.assertEqual(p.stdout.read(6),
906 "line3\n")
907 self.assertEqual(p.stdout.read(),
908 "line4\nline5\nline6\nline7\nline8")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000909
910 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000911 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000912 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000913 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200914 'buf = sys.stdout.buffer;'
915 'buf.write(b"line2\\n");'
916 'buf.flush();'
917 'buf.write(b"line4\\n");'
918 'buf.flush();'
919 'buf.write(b"line5\\r\\n");'
920 'buf.flush();'
921 'buf.write(b"line6\\r");'
922 'buf.flush();'
923 'buf.write(b"\\nline7");'
924 'buf.flush();'
925 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200926 stderr=subprocess.PIPE,
927 stdout=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000928 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000929 self.addCleanup(p.stdout.close)
930 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000931 (stdout, stderr) = p.communicate()
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200932 self.assertEqual(stdout,
933 "line2\nline4\nline5\nline6\nline7\nline8")
934
935 def test_universal_newlines_communicate_stdin(self):
936 # universal newlines through communicate(), with only stdin
937 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300938 'import sys,os;' + SETBINARY + textwrap.dedent('''
939 s = sys.stdin.readline()
940 assert s == "line1\\n", repr(s)
941 s = sys.stdin.read()
942 assert s == "line3\\n", repr(s)
943 ''')],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200944 stdin=subprocess.PIPE,
945 universal_newlines=1)
946 (stdout, stderr) = p.communicate("line1\nline3\n")
947 self.assertEqual(p.returncode, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000948
Andrew Svetlovf3765072012-08-14 18:35:17 +0300949 def test_universal_newlines_communicate_input_none(self):
950 # Test communicate(input=None) with universal newlines.
951 #
952 # We set stdout to PIPE because, as of this writing, a different
953 # code path is tested when the number of pipes is zero or one.
954 p = subprocess.Popen([sys.executable, "-c", "pass"],
955 stdin=subprocess.PIPE,
956 stdout=subprocess.PIPE,
957 universal_newlines=True)
958 p.communicate()
959 self.assertEqual(p.returncode, 0)
960
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300961 def test_universal_newlines_communicate_stdin_stdout_stderr(self):
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300962 # universal newlines through communicate(), with stdin, stdout, stderr
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300963 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300964 'import sys,os;' + SETBINARY + textwrap.dedent('''
965 s = sys.stdin.buffer.readline()
966 sys.stdout.buffer.write(s)
967 sys.stdout.buffer.write(b"line2\\r")
968 sys.stderr.buffer.write(b"eline2\\n")
969 s = sys.stdin.buffer.read()
970 sys.stdout.buffer.write(s)
971 sys.stdout.buffer.write(b"line4\\n")
972 sys.stdout.buffer.write(b"line5\\r\\n")
973 sys.stderr.buffer.write(b"eline6\\r")
974 sys.stderr.buffer.write(b"eline7\\r\\nz")
975 ''')],
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300976 stdin=subprocess.PIPE,
977 stderr=subprocess.PIPE,
978 stdout=subprocess.PIPE,
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300979 universal_newlines=True)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300980 self.addCleanup(p.stdout.close)
981 self.addCleanup(p.stderr.close)
982 (stdout, stderr) = p.communicate("line1\nline3\n")
983 self.assertEqual(p.returncode, 0)
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300984 self.assertEqual("line1\nline2\nline3\nline4\nline5\n", stdout)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300985 # Python debug build push something like "[42442 refs]\n"
986 # to stderr at exit of subprocess.
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300987 # Don't use assertStderrEqual because it strips CR and LF from output.
988 self.assertTrue(stderr.startswith("eline2\neline6\neline7\n"))
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300989
Andrew Svetlov82860712012-08-19 22:13:41 +0300990 def test_universal_newlines_communicate_encodings(self):
991 # Check that universal newlines mode works for various encodings,
992 # in particular for encodings in the UTF-16 and UTF-32 families.
993 # See issue #15595.
994 #
995 # UTF-16 and UTF-32-BE are sufficient to check both with BOM and
996 # without, and UTF-16 and UTF-32.
997 for encoding in ['utf-16', 'utf-32-be']:
Andrew Svetlov82860712012-08-19 22:13:41 +0300998 code = ("import sys; "
999 r"sys.stdout.buffer.write('1\r\n2\r3\n4'.encode('%s'))" %
1000 encoding)
1001 args = [sys.executable, '-c', code]
Steve Dower050acae2016-09-06 20:16:17 -07001002 # We set stdin to be non-None because, as of this writing,
1003 # a different code path is used when the number of pipes is
1004 # zero or one.
1005 popen = subprocess.Popen(args,
1006 stdin=subprocess.PIPE,
1007 stdout=subprocess.PIPE,
1008 encoding=encoding)
1009 stdout, stderr = popen.communicate(input='')
Andrew Svetlov82860712012-08-19 22:13:41 +03001010 self.assertEqual(stdout, '1\n2\n3\n4')
1011
Steve Dower050acae2016-09-06 20:16:17 -07001012 def test_communicate_errors(self):
1013 for errors, expected in [
1014 ('ignore', ''),
1015 ('replace', '\ufffd\ufffd'),
1016 ('surrogateescape', '\udc80\udc80'),
1017 ('backslashreplace', '\\x80\\x80'),
1018 ]:
1019 code = ("import sys; "
1020 r"sys.stdout.buffer.write(b'[\x80\x80]')")
1021 args = [sys.executable, '-c', code]
1022 # We set stdin to be non-None because, as of this writing,
1023 # a different code path is used when the number of pipes is
1024 # zero or one.
1025 popen = subprocess.Popen(args,
1026 stdin=subprocess.PIPE,
1027 stdout=subprocess.PIPE,
1028 encoding='utf-8',
1029 errors=errors)
1030 stdout, stderr = popen.communicate(input='')
1031 self.assertEqual(stdout, '[{}]'.format(expected))
1032
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001033 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +00001034 # Make sure we leak no resources
Victor Stinner937ee9e2018-06-26 02:11:06 +02001035 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +00001036 max_handles = 1026 # too much for most UNIX systems
1037 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +00001038 max_handles = 2050 # too much for (at least some) Windows setups
1039 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001040 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +00001041 try:
1042 for i in range(max_handles):
1043 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001044 tmpfile = os.path.join(tmpdir, support.TESTFN)
1045 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +00001046 except OSError as e:
1047 if e.errno != errno.EMFILE:
1048 raise
1049 break
1050 else:
1051 self.skipTest("failed to reach the file descriptor limit "
1052 "(tried %d)" % max_handles)
1053 # Close a couple of them (should be enough for a subprocess)
1054 for i in range(10):
1055 os.close(handles.pop())
1056 # Loop creating some subprocesses. If one of them leaks some fds,
1057 # the next loop iteration will fail by reaching the max fd limit.
1058 for i in range(15):
1059 p = subprocess.Popen([sys.executable, "-c",
1060 "import sys;"
1061 "sys.stdout.write(sys.stdin.read())"],
1062 stdin=subprocess.PIPE,
1063 stdout=subprocess.PIPE,
1064 stderr=subprocess.PIPE)
1065 data = p.communicate(b"lime")[0]
1066 self.assertEqual(data, b"lime")
1067 finally:
1068 for h in handles:
1069 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001070 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001071
1072 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001073 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
1074 '"a b c" d e')
1075 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
1076 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +00001077 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
1078 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001079 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
1080 'a\\\\\\b "de fg" h')
1081 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
1082 'a\\\\\\"b c d')
1083 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
1084 '"a\\\\b c" d e')
1085 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
1086 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001087 self.assertEqual(subprocess.list2cmdline(['ab', '']),
1088 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001089
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001090 def test_poll(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001091 p = subprocess.Popen([sys.executable, "-c",
Ross Lagerwalle7ad4192012-02-22 06:02:07 +02001092 "import os; os.read(0, 1)"],
1093 stdin=subprocess.PIPE)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001094 self.addCleanup(p.stdin.close)
1095 self.assertIsNone(p.poll())
1096 os.write(p.stdin.fileno(), b'A')
1097 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001098 # Subsequent invocations should just return the returncode
1099 self.assertEqual(p.poll(), 0)
1100
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001101 def test_wait(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001102 p = subprocess.Popen([sys.executable, "-c", "pass"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001103 self.assertEqual(p.wait(), 0)
1104 # Subsequent invocations should just return the returncode
1105 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +00001106
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001107 def test_wait_timeout(self):
1108 p = subprocess.Popen([sys.executable,
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001109 "-c", "import time; time.sleep(0.3)"])
Reid Kleckner2b228f02011-03-16 16:57:54 -04001110 with self.assertRaises(subprocess.TimeoutExpired) as c:
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001111 p.wait(timeout=0.0001)
1112 self.assertIn("0.0001", str(c.exception)) # For coverage of __str__.
Reid Klecknerda9ac722011-03-16 17:08:21 -04001113 # Some heavily loaded buildbots (sparc Debian 3.x) require this much
1114 # time to start.
1115 self.assertEqual(p.wait(timeout=3), 0)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001116
Peter Astrand738131d2004-11-30 21:04:45 +00001117 def test_invalid_bufsize(self):
1118 # an invalid type of the bufsize argument should raise
1119 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001120 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +00001121 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +00001122
Guido van Rossum46a05a72007-06-07 21:56:45 +00001123 def test_bufsize_is_none(self):
1124 # bufsize=None should be the same as bufsize=0.
1125 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
1126 self.assertEqual(p.wait(), 0)
1127 # Again with keyword arg
1128 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
1129 self.assertEqual(p.wait(), 0)
1130
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001131 def _test_bufsize_equal_one(self, line, expected, universal_newlines):
1132 # subprocess may deadlock with bufsize=1, see issue #21332
1133 with subprocess.Popen([sys.executable, "-c", "import sys;"
1134 "sys.stdout.write(sys.stdin.readline());"
1135 "sys.stdout.flush()"],
1136 stdin=subprocess.PIPE,
1137 stdout=subprocess.PIPE,
1138 stderr=subprocess.DEVNULL,
1139 bufsize=1,
1140 universal_newlines=universal_newlines) as p:
1141 p.stdin.write(line) # expect that it flushes the line in text mode
1142 os.close(p.stdin.fileno()) # close it without flushing the buffer
1143 read_line = p.stdout.readline()
Segev Finer4d385172017-08-18 16:18:13 +03001144 with support.SuppressCrashReport():
1145 try:
1146 p.stdin.close()
1147 except OSError:
1148 pass
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001149 p.stdin = None
1150 self.assertEqual(p.returncode, 0)
1151 self.assertEqual(read_line, expected)
1152
1153 def test_bufsize_equal_one_text_mode(self):
1154 # line is flushed in text mode with bufsize=1.
1155 # we should get the full line in return
1156 line = "line\n"
1157 self._test_bufsize_equal_one(line, line, universal_newlines=True)
1158
1159 def test_bufsize_equal_one_binary_mode(self):
1160 # line is not flushed in binary mode with bufsize=1.
1161 # we should get empty response
1162 line = b'line' + os.linesep.encode() # assume ascii-based locale
Alexey Izbysheva2670562018-10-20 03:22:31 +03001163 with self.assertWarnsRegex(RuntimeWarning, 'line buffering'):
1164 self._test_bufsize_equal_one(line, b'', universal_newlines=False)
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001165
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001166 def test_leaking_fds_on_error(self):
1167 # see bug #5179: Popen leaks file descriptors to PIPEs if
1168 # the child fails to execute; this will eventually exhaust
1169 # the maximum number of open fds. 1024 seems a very common
1170 # value for that limit, but Windows has 2048, so we loop
1171 # 1024 times (each call leaked two fds).
1172 for i in range(1024):
Victor Stinnerb31206a2018-01-25 19:06:05 +01001173 with self.assertRaises(NONEXISTING_ERRORS):
Victor Stinner9a83f652017-08-21 23:51:31 +02001174 subprocess.Popen(NONEXISTING_CMD,
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001175 stdout=subprocess.PIPE,
1176 stderr=subprocess.PIPE)
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001177
Victor Stinner9a83f652017-08-21 23:51:31 +02001178 def test_nonexisting_with_pipes(self):
1179 # bpo-30121: Popen with pipes must close properly pipes on error.
1180 # Previously, os.close() was called with a Windows handle which is not
1181 # a valid file descriptor.
1182 #
1183 # Run the test in a subprocess to control how the CRT reports errors
1184 # and to get stderr content.
1185 try:
1186 import msvcrt
1187 msvcrt.CrtSetReportMode
1188 except (AttributeError, ImportError):
1189 self.skipTest("need msvcrt.CrtSetReportMode")
1190
1191 code = textwrap.dedent(f"""
1192 import msvcrt
1193 import subprocess
1194
1195 cmd = {NONEXISTING_CMD!r}
1196
1197 for report_type in [msvcrt.CRT_WARN,
1198 msvcrt.CRT_ERROR,
1199 msvcrt.CRT_ASSERT]:
1200 msvcrt.CrtSetReportMode(report_type, msvcrt.CRTDBG_MODE_FILE)
1201 msvcrt.CrtSetReportFile(report_type, msvcrt.CRTDBG_FILE_STDERR)
1202
1203 try:
Zachary Ware55376462018-02-19 14:02:38 -06001204 subprocess.Popen(cmd,
Victor Stinner9a83f652017-08-21 23:51:31 +02001205 stdout=subprocess.PIPE,
1206 stderr=subprocess.PIPE)
1207 except OSError:
1208 pass
1209 """)
1210 cmd = [sys.executable, "-c", code]
1211 proc = subprocess.Popen(cmd,
1212 stderr=subprocess.PIPE,
1213 universal_newlines=True)
1214 with proc:
1215 stderr = proc.communicate()[1]
1216 self.assertEqual(stderr, "")
1217 self.assertEqual(proc.returncode, 0)
1218
Antoine Pitroua8392712013-08-30 23:38:13 +02001219 def test_double_close_on_error(self):
1220 # Issue #18851
1221 fds = []
1222 def open_fds():
1223 for i in range(20):
1224 fds.extend(os.pipe())
1225 time.sleep(0.001)
1226 t = threading.Thread(target=open_fds)
1227 t.start()
1228 try:
1229 with self.assertRaises(EnvironmentError):
Victor Stinner9a83f652017-08-21 23:51:31 +02001230 subprocess.Popen(NONEXISTING_CMD,
Antoine Pitroua8392712013-08-30 23:38:13 +02001231 stdin=subprocess.PIPE,
1232 stdout=subprocess.PIPE,
1233 stderr=subprocess.PIPE)
1234 finally:
1235 t.join()
1236 exc = None
1237 for fd in fds:
1238 # If a double close occurred, some of those fds will
1239 # already have been closed by mistake, and os.close()
1240 # here will raise.
1241 try:
1242 os.close(fd)
1243 except OSError as e:
1244 exc = e
1245 if exc is not None:
1246 raise exc
1247
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001248 def test_threadsafe_wait(self):
1249 """Issue21291: Popen.wait() needs to be threadsafe for returncode."""
1250 proc = subprocess.Popen([sys.executable, '-c',
1251 'import time; time.sleep(12)'])
1252 self.assertEqual(proc.returncode, None)
1253 results = []
1254
1255 def kill_proc_timer_thread():
1256 results.append(('thread-start-poll-result', proc.poll()))
1257 # terminate it from the thread and wait for the result.
1258 proc.kill()
1259 proc.wait()
1260 results.append(('thread-after-kill-and-wait', proc.returncode))
1261 # this wait should be a no-op given the above.
1262 proc.wait()
1263 results.append(('thread-after-second-wait', proc.returncode))
1264
1265 # This is a timing sensitive test, the failure mode is
1266 # triggered when both the main thread and this thread are in
1267 # the wait() call at once. The delay here is to allow the
1268 # main thread to most likely be blocked in its wait() call.
1269 t = threading.Timer(0.2, kill_proc_timer_thread)
1270 t.start()
1271
Victor Stinner937ee9e2018-06-26 02:11:06 +02001272 if mswindows:
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001273 expected_errorcode = 1
1274 else:
1275 # Should be -9 because of the proc.kill() from the thread.
1276 expected_errorcode = -9
1277
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001278 # Wait for the process to finish; the thread should kill it
1279 # long before it finishes on its own. Supplying a timeout
1280 # triggers a different code path for better coverage.
1281 proc.wait(timeout=20)
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001282 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001283 msg="unexpected result in wait from main thread")
1284
1285 # This should be a no-op with no change in returncode.
1286 proc.wait()
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001287 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001288 msg="unexpected result in second main wait.")
1289
1290 t.join()
1291 # Ensure that all of the thread results are as expected.
1292 # When a race condition occurs in wait(), the returncode could
1293 # be set by the wrong thread that doesn't actually have it
1294 # leading to an incorrect value.
1295 self.assertEqual([('thread-start-poll-result', None),
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001296 ('thread-after-kill-and-wait', expected_errorcode),
1297 ('thread-after-second-wait', expected_errorcode)],
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001298 results)
1299
Victor Stinnerb3693582010-05-21 20:13:12 +00001300 def test_issue8780(self):
1301 # Ensure that stdout is inherited from the parent
1302 # if stdout=PIPE is not used
1303 code = ';'.join((
1304 'import subprocess, sys',
1305 'retcode = subprocess.call('
1306 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
1307 'assert retcode == 0'))
1308 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001309 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +00001310
Tim Goldenaf5ac392010-08-06 13:03:56 +00001311 def test_handles_closed_on_exception(self):
1312 # If CreateProcess exits with an error, ensure the
1313 # duplicate output handles are released
Berker Peksag16a1f282015-09-28 13:33:14 +03001314 ifhandle, ifname = tempfile.mkstemp()
1315 ofhandle, ofname = tempfile.mkstemp()
1316 efhandle, efname = tempfile.mkstemp()
Tim Goldenaf5ac392010-08-06 13:03:56 +00001317 try:
1318 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
1319 stderr=efhandle)
1320 except OSError:
1321 os.close(ifhandle)
1322 os.remove(ifname)
1323 os.close(ofhandle)
1324 os.remove(ofname)
1325 os.close(efhandle)
1326 os.remove(efname)
1327 self.assertFalse(os.path.exists(ifname))
1328 self.assertFalse(os.path.exists(ofname))
1329 self.assertFalse(os.path.exists(efname))
1330
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001331 def test_communicate_epipe(self):
1332 # Issue 10963: communicate() should hide EPIPE
1333 p = subprocess.Popen([sys.executable, "-c", 'pass'],
1334 stdin=subprocess.PIPE,
1335 stdout=subprocess.PIPE,
1336 stderr=subprocess.PIPE)
1337 self.addCleanup(p.stdout.close)
1338 self.addCleanup(p.stderr.close)
1339 self.addCleanup(p.stdin.close)
1340 p.communicate(b"x" * 2**20)
1341
1342 def test_communicate_epipe_only_stdin(self):
1343 # Issue 10963: communicate() should hide EPIPE
1344 p = subprocess.Popen([sys.executable, "-c", 'pass'],
1345 stdin=subprocess.PIPE)
1346 self.addCleanup(p.stdin.close)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001347 p.wait()
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001348 p.communicate(b"x" * 2**20)
1349
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001350 @unittest.skipUnless(hasattr(signal, 'SIGUSR1'),
1351 "Requires signal.SIGUSR1")
1352 @unittest.skipUnless(hasattr(os, 'kill'),
1353 "Requires os.kill")
1354 @unittest.skipUnless(hasattr(os, 'getppid'),
1355 "Requires os.getppid")
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001356 def test_communicate_eintr(self):
1357 # Issue #12493: communicate() should handle EINTR
1358 def handler(signum, frame):
1359 pass
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001360 old_handler = signal.signal(signal.SIGUSR1, handler)
1361 self.addCleanup(signal.signal, signal.SIGUSR1, old_handler)
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001362
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001363 args = [sys.executable, "-c",
1364 'import os, signal;'
1365 'os.kill(os.getppid(), signal.SIGUSR1)']
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001366 for stream in ('stdout', 'stderr'):
1367 kw = {stream: subprocess.PIPE}
1368 with subprocess.Popen(args, **kw) as process:
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001369 # communicate() will be interrupted by SIGUSR1
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001370 process.communicate()
1371
Tim Peterse718f612004-10-12 21:51:32 +00001372
Gregory P. Smith3d8e7762012-11-10 22:32:22 -08001373 # This test is Linux-ish specific for simplicity to at least have
1374 # some coverage. It is not a platform specific bug.
1375 @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
1376 "Linux specific")
1377 def test_failed_child_execute_fd_leak(self):
1378 """Test for the fork() failure fd leak reported in issue16327."""
1379 fd_directory = '/proc/%d/fd' % os.getpid()
1380 fds_before_popen = os.listdir(fd_directory)
1381 with self.assertRaises(PopenTestException):
1382 PopenExecuteChildRaises(
1383 [sys.executable, '-c', 'pass'], stdin=subprocess.PIPE,
1384 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1385
1386 # NOTE: This test doesn't verify that the real _execute_child
1387 # does not close the file descriptors itself on the way out
1388 # during an exception. Code inspection has confirmed that.
1389
1390 fds_after_exception = os.listdir(fd_directory)
1391 self.assertEqual(fds_before_popen, fds_after_exception)
1392
Victor Stinner937ee9e2018-06-26 02:11:06 +02001393 @unittest.skipIf(mswindows, "behavior currently not supported on Windows")
Gregory P. Smith8621bb52017-08-24 14:58:25 -07001394 def test_file_not_found_includes_filename(self):
1395 with self.assertRaises(FileNotFoundError) as c:
1396 subprocess.call(['/opt/nonexistent_binary', 'with', 'some', 'args'])
1397 self.assertEqual(c.exception.filename, '/opt/nonexistent_binary')
1398
Victor Stinner937ee9e2018-06-26 02:11:06 +02001399 @unittest.skipIf(mswindows, "behavior currently not supported on Windows")
Gregory P. Smith8621bb52017-08-24 14:58:25 -07001400 def test_file_not_found_with_bad_cwd(self):
1401 with self.assertRaises(FileNotFoundError) as c:
1402 subprocess.Popen(['exit', '0'], cwd='/some/nonexistent/directory')
1403 self.assertEqual(c.exception.filename, '/some/nonexistent/directory')
1404
Gregory P. Smith6e730002015-04-14 16:14:25 -07001405
1406class RunFuncTestCase(BaseTestCase):
1407 def run_python(self, code, **kwargs):
1408 """Run Python code in a subprocess using subprocess.run"""
1409 argv = [sys.executable, "-c", code]
1410 return subprocess.run(argv, **kwargs)
1411
1412 def test_returncode(self):
1413 # call() function with sequence argument
1414 cp = self.run_python("import sys; sys.exit(47)")
1415 self.assertEqual(cp.returncode, 47)
1416 with self.assertRaises(subprocess.CalledProcessError):
1417 cp.check_returncode()
1418
1419 def test_check(self):
1420 with self.assertRaises(subprocess.CalledProcessError) as c:
1421 self.run_python("import sys; sys.exit(47)", check=True)
1422 self.assertEqual(c.exception.returncode, 47)
1423
1424 def test_check_zero(self):
1425 # check_returncode shouldn't raise when returncode is zero
1426 cp = self.run_python("import sys; sys.exit(0)", check=True)
1427 self.assertEqual(cp.returncode, 0)
1428
1429 def test_timeout(self):
1430 # run() function with timeout argument; we want to test that the child
1431 # process gets killed when the timeout expires. If the child isn't
1432 # killed, this call will deadlock since subprocess.run waits for the
1433 # child.
1434 with self.assertRaises(subprocess.TimeoutExpired):
1435 self.run_python("while True: pass", timeout=0.0001)
1436
1437 def test_capture_stdout(self):
1438 # capture stdout with zero return code
1439 cp = self.run_python("print('BDFL')", stdout=subprocess.PIPE)
1440 self.assertIn(b'BDFL', cp.stdout)
1441
1442 def test_capture_stderr(self):
1443 cp = self.run_python("import sys; sys.stderr.write('BDFL')",
1444 stderr=subprocess.PIPE)
1445 self.assertIn(b'BDFL', cp.stderr)
1446
1447 def test_check_output_stdin_arg(self):
1448 # run() can be called with stdin set to a file
1449 tf = tempfile.TemporaryFile()
1450 self.addCleanup(tf.close)
1451 tf.write(b'pear')
1452 tf.seek(0)
1453 cp = self.run_python(
1454 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1455 stdin=tf, stdout=subprocess.PIPE)
1456 self.assertIn(b'PEAR', cp.stdout)
1457
1458 def test_check_output_input_arg(self):
1459 # check_output() can be called with input set to a string
1460 cp = self.run_python(
1461 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1462 input=b'pear', stdout=subprocess.PIPE)
1463 self.assertIn(b'PEAR', cp.stdout)
1464
1465 def test_check_output_stdin_with_input_arg(self):
1466 # run() refuses to accept 'stdin' with 'input'
1467 tf = tempfile.TemporaryFile()
1468 self.addCleanup(tf.close)
1469 tf.write(b'pear')
1470 tf.seek(0)
1471 with self.assertRaises(ValueError,
1472 msg="Expected ValueError when stdin and input args supplied.") as c:
1473 output = self.run_python("print('will not be run')",
1474 stdin=tf, input=b'hare')
1475 self.assertIn('stdin', c.exception.args[0])
1476 self.assertIn('input', c.exception.args[0])
1477
1478 def test_check_output_timeout(self):
1479 with self.assertRaises(subprocess.TimeoutExpired) as c:
1480 cp = self.run_python((
1481 "import sys, time\n"
1482 "sys.stdout.write('BDFL')\n"
1483 "sys.stdout.flush()\n"
1484 "time.sleep(3600)"),
1485 # Some heavily loaded buildbots (sparc Debian 3.x) require
1486 # this much time to start and print.
1487 timeout=3, stdout=subprocess.PIPE)
1488 self.assertEqual(c.exception.output, b'BDFL')
1489 # output is aliased to stdout
1490 self.assertEqual(c.exception.stdout, b'BDFL')
1491
1492 def test_run_kwargs(self):
1493 newenv = os.environ.copy()
1494 newenv["FRUIT"] = "banana"
1495 cp = self.run_python(('import sys, os;'
1496 'sys.exit(33 if os.getenv("FRUIT")=="banana" else 31)'),
1497 env=newenv)
1498 self.assertEqual(cp.returncode, 33)
1499
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +03001500 def test_run_with_pathlike_path(self):
1501 # bpo-31961: test run(pathlike_object)
1502 # the name of a command that can be run without
Min ho Kimc4cacc82019-07-31 08:16:13 +10001503 # any arguments that exit fast
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +03001504 prog = 'tree.com' if mswindows else 'ls'
1505 path = shutil.which(prog)
1506 if path is None:
1507 self.skipTest(f'{prog} required for this test')
1508 path = FakePath(path)
1509 res = subprocess.run(path, stdout=subprocess.DEVNULL)
1510 self.assertEqual(res.returncode, 0)
1511 with self.assertRaises(TypeError):
1512 subprocess.run(path, stdout=subprocess.DEVNULL, shell=True)
1513
1514 def test_run_with_bytes_path_and_arguments(self):
1515 # bpo-31961: test run([bytes_object, b'additional arguments'])
1516 path = os.fsencode(sys.executable)
1517 args = [path, '-c', b'import sys; sys.exit(57)']
1518 res = subprocess.run(args)
1519 self.assertEqual(res.returncode, 57)
1520
1521 def test_run_with_pathlike_path_and_arguments(self):
1522 # bpo-31961: test run([pathlike_object, 'additional arguments'])
1523 path = FakePath(sys.executable)
1524 args = [path, '-c', 'import sys; sys.exit(57)']
1525 res = subprocess.run(args)
1526 self.assertEqual(res.returncode, 57)
1527
Bo Baylesce0f33d2018-01-30 00:40:39 -06001528 def test_capture_output(self):
1529 cp = self.run_python(("import sys;"
1530 "sys.stdout.write('BDFL'); "
1531 "sys.stderr.write('FLUFL')"),
1532 capture_output=True)
1533 self.assertIn(b'BDFL', cp.stdout)
1534 self.assertIn(b'FLUFL', cp.stderr)
1535
1536 def test_stdout_with_capture_output_arg(self):
1537 # run() refuses to accept 'stdout' with 'capture_output'
1538 tf = tempfile.TemporaryFile()
1539 self.addCleanup(tf.close)
1540 with self.assertRaises(ValueError,
1541 msg=("Expected ValueError when stdout and capture_output "
1542 "args supplied.")) as c:
1543 output = self.run_python("print('will not be run')",
1544 capture_output=True, stdout=tf)
1545 self.assertIn('stdout', c.exception.args[0])
1546 self.assertIn('capture_output', c.exception.args[0])
1547
1548 def test_stderr_with_capture_output_arg(self):
1549 # run() refuses to accept 'stderr' with 'capture_output'
1550 tf = tempfile.TemporaryFile()
1551 self.addCleanup(tf.close)
1552 with self.assertRaises(ValueError,
1553 msg=("Expected ValueError when stderr and capture_output "
1554 "args supplied.")) as c:
1555 output = self.run_python("print('will not be run')",
1556 capture_output=True, stderr=tf)
1557 self.assertIn('stderr', c.exception.args[0])
1558 self.assertIn('capture_output', c.exception.args[0])
1559
Gregory P. Smith6e730002015-04-14 16:14:25 -07001560
Victor Stinner937ee9e2018-06-26 02:11:06 +02001561@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001562class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001563
Gregory P. Smith5591b022012-10-10 03:34:47 -07001564 def setUp(self):
1565 super().setUp()
1566 self._nonexistent_dir = "/_this/pa.th/does/not/exist"
1567
1568 def _get_chdir_exception(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001569 try:
Gregory P. Smith5591b022012-10-10 03:34:47 -07001570 os.chdir(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001571 except OSError as e:
1572 # This avoids hard coding the errno value or the OS perror()
1573 # string and instead capture the exception that we want to see
1574 # below for comparison.
1575 desired_exception = e
1576 else:
Martin Pantereb995702016-07-28 01:11:04 +00001577 self.fail("chdir to nonexistent directory %s succeeded." %
Gregory P. Smith5591b022012-10-10 03:34:47 -07001578 self._nonexistent_dir)
1579 return desired_exception
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001580
Gregory P. Smith5591b022012-10-10 03:34:47 -07001581 def test_exception_cwd(self):
1582 """Test error in the child raised in the parent for a bad cwd."""
1583 desired_exception = self._get_chdir_exception()
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001584 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001585 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smith5591b022012-10-10 03:34:47 -07001586 cwd=self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001587 except OSError as e:
1588 # Test that the child process chdir failure actually makes
1589 # it up to the parent process as the correct exception.
1590 self.assertEqual(desired_exception.errno, e.errno)
1591 self.assertEqual(desired_exception.strerror, e.strerror)
Zackery Spytz73870bf2018-09-11 09:54:07 -06001592 self.assertEqual(desired_exception.filename, e.filename)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001593 else:
1594 self.fail("Expected OSError: %s" % desired_exception)
1595
Gregory P. Smith5591b022012-10-10 03:34:47 -07001596 def test_exception_bad_executable(self):
1597 """Test error in the child raised in the parent for a bad executable."""
1598 desired_exception = self._get_chdir_exception()
1599 try:
1600 p = subprocess.Popen([sys.executable, "-c", ""],
1601 executable=self._nonexistent_dir)
1602 except OSError as e:
1603 # Test that the child process exec failure actually makes
1604 # it up to the parent process as the correct exception.
1605 self.assertEqual(desired_exception.errno, e.errno)
1606 self.assertEqual(desired_exception.strerror, e.strerror)
Zackery Spytz73870bf2018-09-11 09:54:07 -06001607 self.assertEqual(desired_exception.filename, e.filename)
Gregory P. Smith5591b022012-10-10 03:34:47 -07001608 else:
1609 self.fail("Expected OSError: %s" % desired_exception)
1610
1611 def test_exception_bad_args_0(self):
1612 """Test error in the child raised in the parent for a bad args[0]."""
1613 desired_exception = self._get_chdir_exception()
1614 try:
1615 p = subprocess.Popen([self._nonexistent_dir, "-c", ""])
1616 except OSError as e:
1617 # Test that the child process exec failure actually makes
1618 # it up to the parent process as the correct exception.
1619 self.assertEqual(desired_exception.errno, e.errno)
1620 self.assertEqual(desired_exception.strerror, e.strerror)
Zackery Spytz73870bf2018-09-11 09:54:07 -06001621 self.assertEqual(desired_exception.filename, e.filename)
Gregory P. Smith5591b022012-10-10 03:34:47 -07001622 else:
1623 self.fail("Expected OSError: %s" % desired_exception)
1624
Ammar Askar3fc499b2017-09-06 02:41:30 -04001625 # We mock the __del__ method for Popen in the next two tests
1626 # because it does cleanup based on the pid returned by fork_exec
1627 # along with issuing a resource warning if it still exists. Since
1628 # we don't actually spawn a process in these tests we can forego
1629 # the destructor. An alternative would be to set _child_created to
1630 # False before the destructor is called but there is no easy way
1631 # to do that
1632 class PopenNoDestructor(subprocess.Popen):
1633 def __del__(self):
1634 pass
1635
1636 @mock.patch("subprocess._posixsubprocess.fork_exec")
1637 def test_exception_errpipe_normal(self, fork_exec):
1638 """Test error passing done through errpipe_write in the good case"""
1639 def proper_error(*args):
1640 errpipe_write = args[13]
1641 # Write the hex for the error code EISDIR: 'is a directory'
1642 err_code = '{:x}'.format(errno.EISDIR).encode()
1643 os.write(errpipe_write, b"OSError:" + err_code + b":")
1644 return 0
1645
1646 fork_exec.side_effect = proper_error
1647
Victor Stinner11045c92017-10-05 06:32:53 -07001648 with mock.patch("subprocess.os.waitpid",
1649 side_effect=ChildProcessError):
1650 with self.assertRaises(IsADirectoryError):
1651 self.PopenNoDestructor(["non_existent_command"])
Ammar Askar3fc499b2017-09-06 02:41:30 -04001652
1653 @mock.patch("subprocess._posixsubprocess.fork_exec")
1654 def test_exception_errpipe_bad_data(self, fork_exec):
1655 """Test error passing done through errpipe_write where its not
1656 in the expected format"""
1657 error_data = b"\xFF\x00\xDE\xAD"
1658 def bad_error(*args):
1659 errpipe_write = args[13]
1660 # Anything can be in the pipe, no assumptions should
1661 # be made about its encoding, so we'll write some
1662 # arbitrary hex bytes to test it out
1663 os.write(errpipe_write, error_data)
1664 return 0
1665
1666 fork_exec.side_effect = bad_error
1667
Victor Stinner11045c92017-10-05 06:32:53 -07001668 with mock.patch("subprocess.os.waitpid",
1669 side_effect=ChildProcessError):
1670 with self.assertRaises(subprocess.SubprocessError) as e:
1671 self.PopenNoDestructor(["non_existent_command"])
Ammar Askar3fc499b2017-09-06 02:41:30 -04001672
1673 self.assertIn(repr(error_data), str(e.exception))
1674
Gregory P. Smith5f3d04f2018-06-05 12:00:57 -07001675 @unittest.skipIf(not os.path.exists('/proc/self/status'),
1676 "need /proc/self/status")
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001677 def test_restore_signals(self):
Gregory P. Smith5f3d04f2018-06-05 12:00:57 -07001678 # Blindly assume that cat exists on systems with /proc/self/status...
1679 default_proc_status = subprocess.check_output(
1680 ['cat', '/proc/self/status'],
1681 restore_signals=False)
1682 for line in default_proc_status.splitlines():
1683 if line.startswith(b'SigIgn'):
1684 default_sig_ign_mask = line
1685 break
1686 else:
1687 self.skipTest("SigIgn not found in /proc/self/status.")
1688 restored_proc_status = subprocess.check_output(
1689 ['cat', '/proc/self/status'],
1690 restore_signals=True)
1691 for line in restored_proc_status.splitlines():
1692 if line.startswith(b'SigIgn'):
1693 restored_sig_ign_mask = line
1694 break
1695 self.assertNotEqual(default_sig_ign_mask, restored_sig_ign_mask,
1696 msg="restore_signals=True should've unblocked "
1697 "SIGPIPE and friends.")
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001698
1699 def test_start_new_session(self):
1700 # For code coverage of calling setsid(). We don't care if we get an
1701 # EPERM error from it depending on the test execution environment, that
1702 # still indicates that it was called.
1703 try:
1704 output = subprocess.check_output(
Victor Stinner58840432019-06-14 19:31:43 +02001705 [sys.executable, "-c", "import os; print(os.getsid(0))"],
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001706 start_new_session=True)
1707 except OSError as e:
1708 if e.errno != errno.EPERM:
1709 raise
1710 else:
Victor Stinner58840432019-06-14 19:31:43 +02001711 parent_sid = os.getsid(0)
1712 child_sid = int(output)
1713 self.assertNotEqual(parent_sid, child_sid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001714
1715 def test_run_abort(self):
1716 # returncode handles signal termination
Antoine Pitrou77e904e2013-10-08 23:04:32 +02001717 with support.SuppressCrashReport():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001718 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001719 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001720 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001721 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001722
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00001723 def test_CalledProcessError_str_signal(self):
1724 err = subprocess.CalledProcessError(-int(signal.SIGABRT), "fake cmd")
1725 error_string = str(err)
1726 # We're relying on the repr() of the signal.Signals intenum to provide
1727 # the word signal, the signal name and the numeric value.
1728 self.assertIn("signal", error_string.lower())
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)b4149062016-06-03 06:19:35 +00001729 # We're not being specific about the signal name as some signals have
1730 # multiple names and which name is revealed can vary.
1731 self.assertIn("SIG", error_string)
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00001732 self.assertIn(str(signal.SIGABRT), error_string)
1733
1734 def test_CalledProcessError_str_unknown_signal(self):
1735 err = subprocess.CalledProcessError(-9876543, "fake cmd")
1736 error_string = str(err)
1737 self.assertIn("unknown signal 9876543.", error_string)
1738
1739 def test_CalledProcessError_str_non_zero(self):
1740 err = subprocess.CalledProcessError(2, "fake cmd")
1741 error_string = str(err)
1742 self.assertIn("non-zero exit status 2.", error_string)
1743
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001744 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001745 # DISCLAIMER: Setting environment variables is *not* a good use
1746 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001747 p = subprocess.Popen([sys.executable, "-c",
1748 'import sys,os;'
1749 'sys.stdout.write(os.getenv("FRUIT"))'],
1750 stdout=subprocess.PIPE,
1751 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Victor Stinner7438c612016-05-20 12:43:15 +02001752 with p:
1753 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001754
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001755 def test_preexec_exception(self):
1756 def raise_it():
1757 raise ValueError("What if two swallows carried a coconut?")
1758 try:
1759 p = subprocess.Popen([sys.executable, "-c", ""],
1760 preexec_fn=raise_it)
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001761 except subprocess.SubprocessError as e:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001762 self.assertTrue(
1763 subprocess._posixsubprocess,
1764 "Expected a ValueError from the preexec_fn")
1765 except ValueError as e:
1766 self.assertIn("coconut", e.args[0])
1767 else:
1768 self.fail("Exception raised by preexec_fn did not make it "
1769 "to the parent process.")
1770
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001771 class _TestExecuteChildPopen(subprocess.Popen):
1772 """Used to test behavior at the end of _execute_child."""
1773 def __init__(self, testcase, *args, **kwargs):
1774 self._testcase = testcase
1775 subprocess.Popen.__init__(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001776
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001777 def _execute_child(self, *args, **kwargs):
Gregory P. Smith12489d92012-11-11 01:37:02 -08001778 try:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001779 subprocess.Popen._execute_child(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001780 finally:
1781 # Open a bunch of file descriptors and verify that
1782 # none of them are the same as the ones the Popen
1783 # instance is using for stdin/stdout/stderr.
1784 devzero_fds = [os.open("/dev/zero", os.O_RDONLY)
1785 for _ in range(8)]
1786 try:
1787 for fd in devzero_fds:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001788 self._testcase.assertNotIn(
1789 fd, (self.stdin.fileno(), self.stdout.fileno(),
1790 self.stderr.fileno()),
Gregory P. Smith12489d92012-11-11 01:37:02 -08001791 msg="At least one fd was closed early.")
1792 finally:
Richard Oudkerk0e547b62013-06-10 16:29:19 +01001793 for fd in devzero_fds:
1794 os.close(fd)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001795
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001796 @unittest.skipIf(not os.path.exists("/dev/zero"), "/dev/zero required.")
1797 def test_preexec_errpipe_does_not_double_close_pipes(self):
1798 """Issue16140: Don't double close pipes on preexec error."""
1799
1800 def raise_it():
Gregory P. Smith65ee6ec2012-11-11 10:12:40 -08001801 raise subprocess.SubprocessError(
1802 "force the _execute_child() errpipe_data path.")
Gregory P. Smith12489d92012-11-11 01:37:02 -08001803
Gregory P. Smithc2c4cb62012-11-11 01:41:49 -08001804 with self.assertRaises(subprocess.SubprocessError):
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001805 self._TestExecuteChildPopen(
1806 self, [sys.executable, "-c", "pass"],
Gregory P. Smith12489d92012-11-11 01:37:02 -08001807 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1808 stderr=subprocess.PIPE, preexec_fn=raise_it)
1809
Gregory P. Smith32ec9da2010-03-19 16:53:08 +00001810 def test_preexec_gc_module_failure(self):
1811 # This tests the code that disables garbage collection if the child
1812 # process will execute any Python.
1813 def raise_runtime_error():
1814 raise RuntimeError("this shouldn't escape")
1815 enabled = gc.isenabled()
1816 orig_gc_disable = gc.disable
1817 orig_gc_isenabled = gc.isenabled
1818 try:
1819 gc.disable()
1820 self.assertFalse(gc.isenabled())
1821 subprocess.call([sys.executable, '-c', ''],
1822 preexec_fn=lambda: None)
1823 self.assertFalse(gc.isenabled(),
1824 "Popen enabled gc when it shouldn't.")
1825
1826 gc.enable()
1827 self.assertTrue(gc.isenabled())
1828 subprocess.call([sys.executable, '-c', ''],
1829 preexec_fn=lambda: None)
1830 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
1831
1832 gc.disable = raise_runtime_error
1833 self.assertRaises(RuntimeError, subprocess.Popen,
1834 [sys.executable, '-c', ''],
1835 preexec_fn=lambda: None)
1836
1837 del gc.isenabled # force an AttributeError
1838 self.assertRaises(AttributeError, subprocess.Popen,
1839 [sys.executable, '-c', ''],
1840 preexec_fn=lambda: None)
1841 finally:
1842 gc.disable = orig_gc_disable
1843 gc.isenabled = orig_gc_isenabled
1844 if not enabled:
1845 gc.disable()
1846
Martin Panterf7fdbda2015-12-05 09:51:52 +00001847 @unittest.skipIf(
1848 sys.platform == 'darwin', 'setrlimit() seems to fail on OS X')
Martin Panterafdd5132015-11-30 02:21:41 +00001849 def test_preexec_fork_failure(self):
1850 # The internal code did not preserve the previous exception when
1851 # re-enabling garbage collection
1852 try:
1853 from resource import getrlimit, setrlimit, RLIMIT_NPROC
1854 except ImportError as err:
1855 self.skipTest(err) # RLIMIT_NPROC is specific to Linux and BSD
1856 limits = getrlimit(RLIMIT_NPROC)
1857 [_, hard] = limits
1858 setrlimit(RLIMIT_NPROC, (0, hard))
1859 self.addCleanup(setrlimit, RLIMIT_NPROC, limits)
Martin Panter5cf791b2015-12-11 05:40:14 +00001860 try:
Martin Panterafdd5132015-11-30 02:21:41 +00001861 subprocess.call([sys.executable, '-c', ''],
1862 preexec_fn=lambda: None)
Martin Panter5cf791b2015-12-11 05:40:14 +00001863 except BlockingIOError:
1864 # Forking should raise EAGAIN, translated to BlockingIOError
1865 pass
1866 else:
1867 self.skipTest('RLIMIT_NPROC had no effect; probably superuser')
Martin Panterafdd5132015-11-30 02:21:41 +00001868
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001869 def test_args_string(self):
1870 # args is a string
Berker Peksag16a1f282015-09-28 13:33:14 +03001871 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001872 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001873 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02001874 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001875 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1876 sys.executable)
1877 os.chmod(fname, 0o700)
1878 p = subprocess.Popen(fname)
1879 p.wait()
1880 os.remove(fname)
1881 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001882
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001883 def test_invalid_args(self):
1884 # invalid arguments should raise ValueError
1885 self.assertRaises(ValueError, subprocess.call,
1886 [sys.executable, "-c",
1887 "import sys; sys.exit(47)"],
1888 startupinfo=47)
1889 self.assertRaises(ValueError, subprocess.call,
1890 [sys.executable, "-c",
1891 "import sys; sys.exit(47)"],
1892 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001893
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001894 def test_shell_sequence(self):
1895 # Run command through the shell (sequence)
1896 newenv = os.environ.copy()
1897 newenv["FRUIT"] = "apple"
1898 p = subprocess.Popen(["echo $FRUIT"], shell=1,
1899 stdout=subprocess.PIPE,
1900 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02001901 with p:
1902 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001903
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001904 def test_shell_string(self):
1905 # Run command through the shell (string)
1906 newenv = os.environ.copy()
1907 newenv["FRUIT"] = "apple"
1908 p = subprocess.Popen("echo $FRUIT", shell=1,
1909 stdout=subprocess.PIPE,
1910 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02001911 with p:
1912 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +00001913
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001914 def test_call_string(self):
1915 # call() function with string argument on UNIX
Berker Peksag16a1f282015-09-28 13:33:14 +03001916 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001917 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001918 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02001919 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001920 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1921 sys.executable)
1922 os.chmod(fname, 0o700)
1923 rc = subprocess.call(fname)
1924 os.remove(fname)
1925 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00001926
Stefan Krah9542cc62010-07-19 14:20:53 +00001927 def test_specific_shell(self):
1928 # Issue #9265: Incorrect name passed as arg[0].
1929 shells = []
1930 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
1931 for name in ['bash', 'ksh']:
1932 sh = os.path.join(prefix, name)
1933 if os.path.isfile(sh):
1934 shells.append(sh)
1935 if not shells: # Will probably work for any shell but csh.
1936 self.skipTest("bash or ksh required for this test")
1937 sh = '/bin/sh'
1938 if os.path.isfile(sh) and not os.path.islink(sh):
1939 # Test will fail if /bin/sh is a symlink to csh.
1940 shells.append(sh)
1941 for sh in shells:
1942 p = subprocess.Popen("echo $0", executable=sh, shell=True,
1943 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02001944 with p:
1945 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
Stefan Krah9542cc62010-07-19 14:20:53 +00001946
Florent Xicluna4886d242010-03-08 13:27:26 +00001947 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00001948 # Do not inherit file handles from the parent.
1949 # It should fix failures on some platforms.
Gregory P. Smithdee04342013-08-29 13:35:27 -07001950 # Also set the SIGINT handler to the default to make sure it's not
1951 # being ignored (some tests rely on that.)
1952 old_handler = signal.signal(signal.SIGINT, signal.default_int_handler)
1953 try:
1954 p = subprocess.Popen([sys.executable, "-c", """if 1:
1955 import sys, time
1956 sys.stdout.write('x\\n')
1957 sys.stdout.flush()
1958 time.sleep(30)
1959 """],
1960 close_fds=True,
1961 stdin=subprocess.PIPE,
1962 stdout=subprocess.PIPE,
1963 stderr=subprocess.PIPE)
1964 finally:
1965 signal.signal(signal.SIGINT, old_handler)
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00001966 # Wait for the interpreter to be completely initialized before
1967 # sending any signal.
1968 p.stdout.read(1)
1969 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00001970 return p
1971
Charles-François Natali53221e32013-01-12 16:52:20 +01001972 @unittest.skipIf(sys.platform.startswith(('netbsd', 'openbsd')),
1973 "Due to known OS bug (issue #16762)")
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001974 def _kill_dead_process(self, method, *args):
1975 # Do not inherit file handles from the parent.
1976 # It should fix failures on some platforms.
1977 p = subprocess.Popen([sys.executable, "-c", """if 1:
1978 import sys, time
1979 sys.stdout.write('x\\n')
1980 sys.stdout.flush()
1981 """],
1982 close_fds=True,
1983 stdin=subprocess.PIPE,
1984 stdout=subprocess.PIPE,
1985 stderr=subprocess.PIPE)
1986 # Wait for the interpreter to be completely initialized before
1987 # sending any signal.
1988 p.stdout.read(1)
1989 # The process should end after this
1990 time.sleep(1)
1991 # This shouldn't raise even though the child is now dead
1992 getattr(p, method)(*args)
1993 p.communicate()
1994
Florent Xicluna4886d242010-03-08 13:27:26 +00001995 def test_send_signal(self):
1996 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00001997 _, stderr = p.communicate()
1998 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001999 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00002000
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002001 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002002 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00002003 _, stderr = p.communicate()
2004 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002005 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00002006
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002007 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002008 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00002009 _, stderr = p.communicate()
2010 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002011 self.assertEqual(p.wait(), -signal.SIGTERM)
2012
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002013 def test_send_signal_dead(self):
2014 # Sending a signal to a dead process
2015 self._kill_dead_process('send_signal', signal.SIGINT)
2016
2017 def test_kill_dead(self):
2018 # Killing a dead process
2019 self._kill_dead_process('kill')
2020
2021 def test_terminate_dead(self):
2022 # Terminating a dead process
2023 self._kill_dead_process('terminate')
2024
Victor Stinnerdaf45552013-08-28 00:53:59 +02002025 def _save_fds(self, save_fds):
2026 fds = []
2027 for fd in save_fds:
2028 inheritable = os.get_inheritable(fd)
2029 saved = os.dup(fd)
2030 fds.append((fd, saved, inheritable))
2031 return fds
2032
2033 def _restore_fds(self, fds):
2034 for fd, saved, inheritable in fds:
2035 os.dup2(saved, fd, inheritable=inheritable)
2036 os.close(saved)
2037
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002038 def check_close_std_fds(self, fds):
2039 # Issue #9905: test that subprocess pipes still work properly with
2040 # some standard fds closed
2041 stdin = 0
Victor Stinnerdaf45552013-08-28 00:53:59 +02002042 saved_fds = self._save_fds(fds)
2043 for fd, saved, inheritable in saved_fds:
2044 if fd == 0:
2045 stdin = saved
2046 break
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002047 try:
2048 for fd in fds:
2049 os.close(fd)
2050 out, err = subprocess.Popen([sys.executable, "-c",
2051 'import sys;'
2052 'sys.stdout.write("apple");'
2053 'sys.stdout.flush();'
2054 'sys.stderr.write("orange")'],
2055 stdin=stdin,
2056 stdout=subprocess.PIPE,
2057 stderr=subprocess.PIPE).communicate()
2058 err = support.strip_python_stderr(err)
2059 self.assertEqual((out, err), (b'apple', b'orange'))
2060 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002061 self._restore_fds(saved_fds)
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002062
2063 def test_close_fd_0(self):
2064 self.check_close_std_fds([0])
2065
2066 def test_close_fd_1(self):
2067 self.check_close_std_fds([1])
2068
2069 def test_close_fd_2(self):
2070 self.check_close_std_fds([2])
2071
2072 def test_close_fds_0_1(self):
2073 self.check_close_std_fds([0, 1])
2074
2075 def test_close_fds_0_2(self):
2076 self.check_close_std_fds([0, 2])
2077
2078 def test_close_fds_1_2(self):
2079 self.check_close_std_fds([1, 2])
2080
2081 def test_close_fds_0_1_2(self):
2082 # Issue #10806: test that subprocess pipes still work properly with
2083 # all standard fds closed.
2084 self.check_close_std_fds([0, 1, 2])
2085
Gregory P. Smith53dd8162013-12-01 16:03:24 -08002086 def test_small_errpipe_write_fd(self):
2087 """Issue #15798: Popen should work when stdio fds are available."""
2088 new_stdin = os.dup(0)
2089 new_stdout = os.dup(1)
2090 try:
2091 os.close(0)
2092 os.close(1)
2093
2094 # Side test: if errpipe_write fails to have its CLOEXEC
2095 # flag set this should cause the parent to think the exec
2096 # failed. Extremely unlikely: everyone supports CLOEXEC.
2097 subprocess.Popen([
2098 sys.executable, "-c",
2099 "print('AssertionError:0:CLOEXEC failure.')"]).wait()
2100 finally:
2101 # Restore original stdin and stdout
2102 os.dup2(new_stdin, 0)
2103 os.dup2(new_stdout, 1)
2104 os.close(new_stdin)
2105 os.close(new_stdout)
2106
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002107 def test_remapping_std_fds(self):
2108 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03002109 temps = [tempfile.mkstemp() for i in range(3)]
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002110 try:
2111 temp_fds = [fd for fd, fname in temps]
2112
2113 # unlink the files -- we won't need to reopen them
2114 for fd, fname in temps:
2115 os.unlink(fname)
2116
2117 # write some data to what will become stdin, and rewind
2118 os.write(temp_fds[1], b"STDIN")
2119 os.lseek(temp_fds[1], 0, 0)
2120
2121 # move the standard file descriptors out of the way
Victor Stinnerdaf45552013-08-28 00:53:59 +02002122 saved_fds = self._save_fds(range(3))
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002123 try:
2124 # duplicate the file objects over the standard fd's
2125 for fd, temp_fd in enumerate(temp_fds):
2126 os.dup2(temp_fd, fd)
2127
2128 # now use those files in the "wrong" order, so that subprocess
2129 # has to rearrange them in the child
2130 p = subprocess.Popen([sys.executable, "-c",
2131 'import sys; got = sys.stdin.read();'
2132 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
2133 stdin=temp_fds[1],
2134 stdout=temp_fds[2],
2135 stderr=temp_fds[0])
2136 p.wait()
2137 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002138 self._restore_fds(saved_fds)
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002139
2140 for fd in temp_fds:
2141 os.lseek(fd, 0, 0)
2142
2143 out = os.read(temp_fds[2], 1024)
2144 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
2145 self.assertEqual(out, b"got STDIN")
2146 self.assertEqual(err, b"err")
2147
2148 finally:
2149 for fd in temp_fds:
2150 os.close(fd)
2151
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002152 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
2153 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03002154 temps = [tempfile.mkstemp() for i in range(3)]
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002155 temp_fds = [fd for fd, fname in temps]
2156 try:
2157 # unlink the files -- we won't need to reopen them
2158 for fd, fname in temps:
2159 os.unlink(fname)
2160
2161 # save a copy of the standard file descriptors
Victor Stinnerdaf45552013-08-28 00:53:59 +02002162 saved_fds = self._save_fds(range(3))
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002163 try:
2164 # duplicate the temp files over the standard fd's 0, 1, 2
2165 for fd, temp_fd in enumerate(temp_fds):
2166 os.dup2(temp_fd, fd)
2167
2168 # write some data to what will become stdin, and rewind
2169 os.write(stdin_no, b"STDIN")
2170 os.lseek(stdin_no, 0, 0)
2171
2172 # now use those files in the given order, so that subprocess
2173 # has to rearrange them in the child
2174 p = subprocess.Popen([sys.executable, "-c",
2175 'import sys; got = sys.stdin.read();'
2176 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
2177 stdin=stdin_no,
2178 stdout=stdout_no,
2179 stderr=stderr_no)
2180 p.wait()
2181
2182 for fd in temp_fds:
2183 os.lseek(fd, 0, 0)
2184
2185 out = os.read(stdout_no, 1024)
2186 err = support.strip_python_stderr(os.read(stderr_no, 1024))
2187 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002188 self._restore_fds(saved_fds)
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002189
2190 self.assertEqual(out, b"got STDIN")
2191 self.assertEqual(err, b"err")
2192
2193 finally:
2194 for fd in temp_fds:
2195 os.close(fd)
2196
2197 # When duping fds, if there arises a situation where one of the fds is
2198 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
2199 # This tests all combinations of this.
2200 def test_swap_fds(self):
2201 self.check_swap_fds(0, 1, 2)
2202 self.check_swap_fds(0, 2, 1)
2203 self.check_swap_fds(1, 0, 2)
2204 self.check_swap_fds(1, 2, 0)
2205 self.check_swap_fds(2, 0, 1)
2206 self.check_swap_fds(2, 1, 0)
2207
Alexey Izbyshev0e7144b2018-03-26 22:49:35 +03002208 def _check_swap_std_fds_with_one_closed(self, from_fds, to_fds):
2209 saved_fds = self._save_fds(range(3))
2210 try:
2211 for from_fd in from_fds:
2212 with tempfile.TemporaryFile() as f:
2213 os.dup2(f.fileno(), from_fd)
2214
2215 fd_to_close = (set(range(3)) - set(from_fds)).pop()
2216 os.close(fd_to_close)
2217
2218 arg_names = ['stdin', 'stdout', 'stderr']
2219 kwargs = {}
2220 for from_fd, to_fd in zip(from_fds, to_fds):
2221 kwargs[arg_names[to_fd]] = from_fd
2222
2223 code = textwrap.dedent(r'''
2224 import os, sys
2225 skipped_fd = int(sys.argv[1])
2226 for fd in range(3):
2227 if fd != skipped_fd:
2228 os.write(fd, str(fd).encode('ascii'))
2229 ''')
2230
2231 skipped_fd = (set(range(3)) - set(to_fds)).pop()
2232
2233 rc = subprocess.call([sys.executable, '-c', code, str(skipped_fd)],
2234 **kwargs)
2235 self.assertEqual(rc, 0)
2236
2237 for from_fd, to_fd in zip(from_fds, to_fds):
2238 os.lseek(from_fd, 0, os.SEEK_SET)
2239 read_bytes = os.read(from_fd, 1024)
2240 read_fds = list(map(int, read_bytes.decode('ascii')))
2241 msg = textwrap.dedent(f"""
2242 When testing {from_fds} to {to_fds} redirection,
2243 parent descriptor {from_fd} got redirected
2244 to descriptor(s) {read_fds} instead of descriptor {to_fd}.
2245 """)
2246 self.assertEqual([to_fd], read_fds, msg)
2247 finally:
2248 self._restore_fds(saved_fds)
2249
2250 # Check that subprocess can remap std fds correctly even
2251 # if one of them is closed (#32844).
2252 def test_swap_std_fds_with_one_closed(self):
2253 for from_fds in itertools.combinations(range(3), 2):
2254 for to_fds in itertools.permutations(range(3), 2):
2255 self._check_swap_std_fds_with_one_closed(from_fds, to_fds)
2256
Victor Stinner13bb71c2010-04-23 21:41:56 +00002257 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00002258 def prepare():
2259 raise ValueError("surrogate:\uDCff")
2260
2261 try:
2262 subprocess.call(
2263 [sys.executable, "-c", "pass"],
2264 preexec_fn=prepare)
2265 except ValueError as err:
2266 # Pure Python implementations keeps the message
2267 self.assertIsNone(subprocess._posixsubprocess)
2268 self.assertEqual(str(err), "surrogate:\uDCff")
Gregory P. Smith8d07c262012-11-10 23:53:47 -08002269 except subprocess.SubprocessError as err:
Victor Stinner4d078042010-04-23 19:28:32 +00002270 # _posixsubprocess uses a default message
2271 self.assertIsNotNone(subprocess._posixsubprocess)
2272 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
2273 else:
Gregory P. Smith8d07c262012-11-10 23:53:47 -08002274 self.fail("Expected ValueError or subprocess.SubprocessError")
Victor Stinner4d078042010-04-23 19:28:32 +00002275
Victor Stinner13bb71c2010-04-23 21:41:56 +00002276 def test_undecodable_env(self):
2277 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner5323fb02013-11-19 23:46:06 +01002278 encoded_value = value.encode("ascii", "surrogateescape")
2279
Victor Stinner13bb71c2010-04-23 21:41:56 +00002280 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00002281 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002282 env = os.environ.copy()
2283 env[key] = value
Victor Stinner5323fb02013-11-19 23:46:06 +01002284 # Use C locale to get ASCII for the locale encoding to force
Michael Felt89d79b12018-08-26 19:29:36 +02002285 # surrogate-escaping of \xFF in the child process
Victor Stinnerebc78d22010-10-14 10:38:17 +00002286 env['LC_ALL'] = 'C'
Michael Felt89d79b12018-08-26 19:29:36 +02002287 decoded_value = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00002288 stdout = subprocess.check_output(
2289 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002290 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00002291 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01002292 self.assertEqual(stdout.decode('ascii'), ascii(decoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00002293
2294 # test bytes
2295 key = key.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00002296 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002297 env = os.environ.copy()
Victor Stinner5323fb02013-11-19 23:46:06 +01002298 env[key] = encoded_value
Victor Stinner13bb71c2010-04-23 21:41:56 +00002299 stdout = subprocess.check_output(
2300 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002301 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00002302 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01002303 self.assertEqual(stdout.decode('ascii'), ascii(encoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00002304
Victor Stinnerb745a742010-05-18 17:17:23 +00002305 def test_bytes_program(self):
2306 abs_program = os.fsencode(sys.executable)
2307 path, program = os.path.split(sys.executable)
2308 program = os.fsencode(program)
2309
2310 # absolute bytes path
2311 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00002312 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002313
Victor Stinner7b3b20a2011-03-03 12:54:05 +00002314 # absolute bytes path as a string
2315 cmd = b"'" + abs_program + b"' -c pass"
2316 exitcode = subprocess.call(cmd, shell=True)
2317 self.assertEqual(exitcode, 0)
2318
Victor Stinnerb745a742010-05-18 17:17:23 +00002319 # bytes program, unicode PATH
2320 env = os.environ.copy()
2321 env["PATH"] = path
2322 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002323 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002324
2325 # bytes program, bytes PATH
2326 envb = os.environb.copy()
2327 envb[b"PATH"] = os.fsencode(path)
2328 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002329 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002330
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002331 def test_pipe_cloexec(self):
2332 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
2333 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2334
2335 p1 = subprocess.Popen([sys.executable, sleeper],
2336 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2337 stderr=subprocess.PIPE, close_fds=False)
2338
2339 self.addCleanup(p1.communicate, b'')
2340
2341 p2 = subprocess.Popen([sys.executable, fd_status],
2342 stdout=subprocess.PIPE, close_fds=False)
2343
2344 output, error = p2.communicate()
2345 result_fds = set(map(int, output.split(b',')))
2346 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
2347 p1.stderr.fileno()])
2348
2349 self.assertFalse(result_fds & unwanted_fds,
2350 "Expected no fds from %r to be open in child, "
2351 "found %r" %
2352 (unwanted_fds, result_fds & unwanted_fds))
2353
2354 def test_pipe_cloexec_real_tools(self):
2355 qcat = support.findfile("qcat.py", subdir="subprocessdata")
2356 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
2357
2358 subdata = b'zxcvbn'
2359 data = subdata * 4 + b'\n'
2360
2361 p1 = subprocess.Popen([sys.executable, qcat],
2362 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2363 close_fds=False)
2364
2365 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
2366 stdin=p1.stdout, stdout=subprocess.PIPE,
2367 close_fds=False)
2368
2369 self.addCleanup(p1.wait)
2370 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08002371 def kill_p1():
2372 try:
2373 p1.terminate()
2374 except ProcessLookupError:
2375 pass
2376 def kill_p2():
2377 try:
2378 p2.terminate()
2379 except ProcessLookupError:
2380 pass
2381 self.addCleanup(kill_p1)
2382 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002383
2384 p1.stdin.write(data)
2385 p1.stdin.close()
2386
2387 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
2388
2389 self.assertTrue(readfiles, "The child hung")
2390 self.assertEqual(p2.stdout.read(), data)
2391
Victor Stinnerfaa8c132011-01-03 16:36:00 +00002392 p1.stdout.close()
2393 p2.stdout.close()
2394
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002395 def test_close_fds(self):
2396 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2397
2398 fds = os.pipe()
2399 self.addCleanup(os.close, fds[0])
2400 self.addCleanup(os.close, fds[1])
2401
2402 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002403 # add a bunch more fds
2404 for _ in range(9):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002405 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002406 self.addCleanup(os.close, fd)
2407 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002408
Victor Stinnerdaf45552013-08-28 00:53:59 +02002409 for fd in open_fds:
2410 os.set_inheritable(fd, True)
2411
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002412 p = subprocess.Popen([sys.executable, fd_status],
2413 stdout=subprocess.PIPE, close_fds=False)
2414 output, ignored = p.communicate()
2415 remaining_fds = set(map(int, output.split(b',')))
2416
2417 self.assertEqual(remaining_fds & open_fds, open_fds,
2418 "Some fds were closed")
2419
2420 p = subprocess.Popen([sys.executable, fd_status],
2421 stdout=subprocess.PIPE, close_fds=True)
2422 output, ignored = p.communicate()
2423 remaining_fds = set(map(int, output.split(b',')))
2424
2425 self.assertFalse(remaining_fds & open_fds,
2426 "Some fds were left open")
2427 self.assertIn(1, remaining_fds, "Subprocess failed")
2428
Gregory P. Smith8facece2012-01-21 14:01:08 -08002429 # Keep some of the fd's we opened open in the subprocess.
2430 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
2431 fds_to_keep = set(open_fds.pop() for _ in range(8))
2432 p = subprocess.Popen([sys.executable, fd_status],
2433 stdout=subprocess.PIPE, close_fds=True,
izbyshev2d8f0632017-12-19 03:26:49 +07002434 pass_fds=fds_to_keep)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002435 output, ignored = p.communicate()
2436 remaining_fds = set(map(int, output.split(b',')))
2437
izbyshev2d8f0632017-12-19 03:26:49 +07002438 self.assertFalse((remaining_fds - fds_to_keep) & open_fds,
Gregory P. Smith8facece2012-01-21 14:01:08 -08002439 "Some fds not in pass_fds were left open")
2440 self.assertIn(1, remaining_fds, "Subprocess failed")
2441
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002442
Gregory P. Smithd04f6992014-06-01 15:27:28 -07002443 @unittest.skipIf(sys.platform.startswith("freebsd") and
2444 os.stat("/dev").st_dev == os.stat("/dev/fd").st_dev,
2445 "Requires fdescfs mounted on /dev/fd on FreeBSD.")
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002446 def test_close_fds_when_max_fd_is_lowered(self):
2447 """Confirm that issue21618 is fixed (may fail under valgrind)."""
2448 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2449
Gregory P. Smith634aa682014-06-15 17:51:04 -07002450 # This launches the meat of the test in a child process to
2451 # avoid messing with the larger unittest processes maximum
2452 # number of file descriptors.
2453 # This process launches:
2454 # +--> Process that lowers its RLIMIT_NOFILE aftr setting up
2455 # a bunch of high open fds above the new lower rlimit.
2456 # Those are reported via stdout before launching a new
2457 # process with close_fds=False to run the actual test:
2458 # +--> The TEST: This one launches a fd_status.py
2459 # subprocess with close_fds=True so we can find out if
2460 # any of the fds above the lowered rlimit are still open.
2461 p = subprocess.Popen([sys.executable, '-c', textwrap.dedent(
2462 '''
2463 import os, resource, subprocess, sys, textwrap
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002464 open_fds = set()
2465 # Add a bunch more fds to pass down.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002466 for _ in range(40):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002467 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002468 open_fds.add(fd)
2469
2470 # Leave a two pairs of low ones available for use by the
2471 # internal child error pipe and the stdout pipe.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002472 # We also leave 10 more open as some Python buildbots run into
2473 # "too many open files" errors during the test if we do not.
2474 for fd in sorted(open_fds)[:14]:
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002475 os.close(fd)
2476 open_fds.remove(fd)
2477
2478 for fd in open_fds:
Gregory P. Smith634aa682014-06-15 17:51:04 -07002479 #self.addCleanup(os.close, fd)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002480 os.set_inheritable(fd, True)
2481
2482 max_fd_open = max(open_fds)
2483
Gregory P. Smith634aa682014-06-15 17:51:04 -07002484 # Communicate the open_fds to the parent unittest.TestCase process.
2485 print(','.join(map(str, sorted(open_fds))))
2486 sys.stdout.flush()
2487
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002488 rlim_cur, rlim_max = resource.getrlimit(resource.RLIMIT_NOFILE)
2489 try:
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002490 # 29 is lower than the highest fds we are leaving open.
2491 resource.setrlimit(resource.RLIMIT_NOFILE, (29, rlim_max))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002492 # Launch a new Python interpreter with our low fd rlim_cur that
2493 # inherits open fds above that limit. It then uses subprocess
2494 # with close_fds=True to get a report of open fds in the child.
2495 # An explicit list of fds to check is passed to fd_status.py as
2496 # letting fd_status rely on its default logic would miss the
2497 # fds above rlim_cur as it normally only checks up to that limit.
Gregory P. Smith634aa682014-06-15 17:51:04 -07002498 subprocess.Popen(
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002499 [sys.executable, '-c',
2500 textwrap.dedent("""
2501 import subprocess, sys
Gregory P. Smith634aa682014-06-15 17:51:04 -07002502 subprocess.Popen([sys.executable, %r] +
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002503 [str(x) for x in range({max_fd})],
Gregory P. Smithffd529c2014-06-01 13:46:54 -07002504 close_fds=True).wait()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002505 """.format(max_fd=max_fd_open+1))],
2506 close_fds=False).wait()
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002507 finally:
2508 resource.setrlimit(resource.RLIMIT_NOFILE, (rlim_cur, rlim_max))
Gregory P. Smith634aa682014-06-15 17:51:04 -07002509 ''' % fd_status)], stdout=subprocess.PIPE)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002510
2511 output, unused_stderr = p.communicate()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002512 output_lines = output.splitlines()
2513 self.assertEqual(len(output_lines), 2,
Gregory P. Smith9204e092014-06-15 20:16:01 -07002514 msg="expected exactly two lines of output:\n%r" % output)
Gregory P. Smith634aa682014-06-15 17:51:04 -07002515 opened_fds = set(map(int, output_lines[0].strip().split(b',')))
2516 remaining_fds = set(map(int, output_lines[1].strip().split(b',')))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002517
Gregory P. Smith634aa682014-06-15 17:51:04 -07002518 self.assertFalse(remaining_fds & opened_fds,
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002519 msg="Some fds were left open.")
2520
2521
Victor Stinner88701e22011-06-01 13:13:04 +02002522 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
2523 # descriptor of a pipe closed in the parent process is valid in the
2524 # child process according to fstat(), but the mode of the file
2525 # descriptor is invalid, and read or write raise an error.
2526 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002527 def test_pass_fds(self):
2528 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2529
2530 open_fds = set()
2531
2532 for x in range(5):
2533 fds = os.pipe()
2534 self.addCleanup(os.close, fds[0])
2535 self.addCleanup(os.close, fds[1])
Victor Stinnerdaf45552013-08-28 00:53:59 +02002536 os.set_inheritable(fds[0], True)
2537 os.set_inheritable(fds[1], True)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002538 open_fds.update(fds)
2539
2540 for fd in open_fds:
2541 p = subprocess.Popen([sys.executable, fd_status],
2542 stdout=subprocess.PIPE, close_fds=True,
2543 pass_fds=(fd, ))
2544 output, ignored = p.communicate()
2545
2546 remaining_fds = set(map(int, output.split(b',')))
2547 to_be_closed = open_fds - {fd}
2548
2549 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
2550 self.assertFalse(remaining_fds & to_be_closed,
2551 "fd to be closed passed")
2552
2553 # pass_fds overrides close_fds with a warning.
2554 with self.assertWarns(RuntimeWarning) as context:
2555 self.assertFalse(subprocess.call(
2556 [sys.executable, "-c", "import sys; sys.exit(0)"],
2557 close_fds=False, pass_fds=(fd, )))
2558 self.assertIn('overriding close_fds', str(context.warning))
2559
Victor Stinnerdaf45552013-08-28 00:53:59 +02002560 def test_pass_fds_inheritable(self):
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002561 script = support.findfile("fd_status.py", subdir="subprocessdata")
Victor Stinnerdaf45552013-08-28 00:53:59 +02002562
2563 inheritable, non_inheritable = os.pipe()
2564 self.addCleanup(os.close, inheritable)
2565 self.addCleanup(os.close, non_inheritable)
2566 os.set_inheritable(inheritable, True)
2567 os.set_inheritable(non_inheritable, False)
2568 pass_fds = (inheritable, non_inheritable)
2569 args = [sys.executable, script]
2570 args += list(map(str, pass_fds))
2571
2572 p = subprocess.Popen(args,
2573 stdout=subprocess.PIPE, close_fds=True,
2574 pass_fds=pass_fds)
2575 output, ignored = p.communicate()
2576 fds = set(map(int, output.split(b',')))
2577
2578 # the inheritable file descriptor must be inherited, so its inheritable
2579 # flag must be set in the child process after fork() and before exec()
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002580 self.assertEqual(fds, set(pass_fds), "output=%a" % output)
Victor Stinnerdaf45552013-08-28 00:53:59 +02002581
2582 # inheritable flag must not be changed in the parent process
2583 self.assertEqual(os.get_inheritable(inheritable), True)
2584 self.assertEqual(os.get_inheritable(non_inheritable), False)
2585
Gregory P. Smithce344102018-09-10 17:46:22 -07002586
2587 # bpo-32270: Ensure that descriptors specified in pass_fds
2588 # are inherited even if they are used in redirections.
2589 # Contributed by @izbyshev.
2590 def test_pass_fds_redirected(self):
2591 """Regression test for https://bugs.python.org/issue32270."""
2592 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2593 pass_fds = []
2594 for _ in range(2):
2595 fd = os.open(os.devnull, os.O_RDWR)
2596 self.addCleanup(os.close, fd)
2597 pass_fds.append(fd)
2598
2599 stdout_r, stdout_w = os.pipe()
2600 self.addCleanup(os.close, stdout_r)
2601 self.addCleanup(os.close, stdout_w)
2602 pass_fds.insert(1, stdout_w)
2603
2604 with subprocess.Popen([sys.executable, fd_status],
2605 stdin=pass_fds[0],
2606 stdout=pass_fds[1],
2607 stderr=pass_fds[2],
2608 close_fds=True,
2609 pass_fds=pass_fds):
2610 output = os.read(stdout_r, 1024)
2611 fds = {int(num) for num in output.split(b',')}
2612
2613 self.assertEqual(fds, {0, 1, 2} | frozenset(pass_fds), f"output={output!a}")
2614
2615
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002616 def test_stdout_stdin_are_single_inout_fd(self):
2617 with io.open(os.devnull, "r+") as inout:
2618 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2619 stdout=inout, stdin=inout)
2620 p.wait()
2621
2622 def test_stdout_stderr_are_single_inout_fd(self):
2623 with io.open(os.devnull, "r+") as inout:
2624 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2625 stdout=inout, stderr=inout)
2626 p.wait()
2627
2628 def test_stderr_stdin_are_single_inout_fd(self):
2629 with io.open(os.devnull, "r+") as inout:
2630 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2631 stderr=inout, stdin=inout)
2632 p.wait()
2633
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002634 def test_wait_when_sigchild_ignored(self):
2635 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
2636 sigchild_ignore = support.findfile("sigchild_ignore.py",
2637 subdir="subprocessdata")
2638 p = subprocess.Popen([sys.executable, sigchild_ignore],
2639 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
2640 stdout, stderr = p.communicate()
2641 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00002642 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00002643 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002644
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002645 def test_select_unbuffered(self):
2646 # Issue #11459: bufsize=0 should really set the pipes as
2647 # unbuffered (and therefore let select() work properly).
2648 select = support.import_module("select")
2649 p = subprocess.Popen([sys.executable, "-c",
2650 'import sys;'
2651 'sys.stdout.write("apple")'],
2652 stdout=subprocess.PIPE,
2653 bufsize=0)
2654 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02002655 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002656 try:
2657 self.assertEqual(f.read(4), b"appl")
2658 self.assertIn(f, select.select([f], [], [], 0.0)[0])
2659 finally:
2660 p.wait()
2661
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002662 def test_zombie_fast_process_del(self):
2663 # Issue #12650: on Unix, if Popen.__del__() was called before the
2664 # process exited, it wouldn't be added to subprocess._active, and would
2665 # remain a zombie.
2666 # spawn a Popen, and delete its reference before it exits
2667 p = subprocess.Popen([sys.executable, "-c",
2668 'import sys, time;'
2669 'time.sleep(0.2)'],
2670 stdout=subprocess.PIPE,
2671 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002672 self.addCleanup(p.stdout.close)
2673 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002674 ident = id(p)
2675 pid = p.pid
Victor Stinner5a48e212016-05-20 12:11:15 +02002676 with support.check_warnings(('', ResourceWarning)):
2677 p = None
2678
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +03002679 if mswindows:
2680 # subprocess._active is not used on Windows and is set to None.
2681 self.assertIsNone(subprocess._active)
2682 else:
2683 # check that p is in the active processes list
2684 self.assertIn(ident, [id(o) for o in subprocess._active])
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002685
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002686 def test_leak_fast_process_del_killed(self):
2687 # Issue #12650: on Unix, if Popen.__del__() was called before the
2688 # process exited, and the process got killed by a signal, it would never
2689 # be removed from subprocess._active, which triggered a FD and memory
2690 # leak.
2691 # spawn a Popen, delete its reference and kill it
2692 p = subprocess.Popen([sys.executable, "-c",
2693 'import time;'
2694 'time.sleep(3)'],
2695 stdout=subprocess.PIPE,
2696 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002697 self.addCleanup(p.stdout.close)
2698 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002699 ident = id(p)
2700 pid = p.pid
Victor Stinner5a48e212016-05-20 12:11:15 +02002701 with support.check_warnings(('', ResourceWarning)):
2702 p = None
2703
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002704 os.kill(pid, signal.SIGKILL)
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +03002705 if mswindows:
2706 # subprocess._active is not used on Windows and is set to None.
2707 self.assertIsNone(subprocess._active)
2708 else:
2709 # check that p is in the active processes list
2710 self.assertIn(ident, [id(o) for o in subprocess._active])
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002711
2712 # let some time for the process to exit, and create a new Popen: this
2713 # should trigger the wait() of p
2714 time.sleep(0.2)
Victor Stinnerb31206a2018-01-25 19:06:05 +01002715 with self.assertRaises(OSError):
Victor Stinner9a83f652017-08-21 23:51:31 +02002716 with subprocess.Popen(NONEXISTING_CMD,
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002717 stdout=subprocess.PIPE,
2718 stderr=subprocess.PIPE) as proc:
2719 pass
2720 # p should have been wait()ed on, and removed from the _active list
2721 self.assertRaises(OSError, os.waitpid, pid, 0)
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +03002722 if mswindows:
2723 # subprocess._active is not used on Windows and is set to None.
2724 self.assertIsNone(subprocess._active)
2725 else:
2726 self.assertNotIn(ident, [id(o) for o in subprocess._active])
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002727
Charles-François Natali249cdc32013-08-25 18:24:45 +02002728 def test_close_fds_after_preexec(self):
2729 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2730
2731 # this FD is used as dup2() target by preexec_fn, and should be closed
2732 # in the child process
2733 fd = os.dup(1)
2734 self.addCleanup(os.close, fd)
2735
2736 p = subprocess.Popen([sys.executable, fd_status],
2737 stdout=subprocess.PIPE, close_fds=True,
2738 preexec_fn=lambda: os.dup2(1, fd))
2739 output, ignored = p.communicate()
2740
2741 remaining_fds = set(map(int, output.split(b',')))
2742
2743 self.assertNotIn(fd, remaining_fds)
2744
Victor Stinner8f437aa2014-10-05 17:25:19 +02002745 @support.cpython_only
2746 def test_fork_exec(self):
2747 # Issue #22290: fork_exec() must not crash on memory allocation failure
2748 # or other errors
2749 import _posixsubprocess
2750 gc_enabled = gc.isenabled()
2751 try:
2752 # Use a preexec function and enable the garbage collector
2753 # to force fork_exec() to re-enable the garbage collector
2754 # on error.
2755 func = lambda: None
2756 gc.enable()
2757
Victor Stinner8f437aa2014-10-05 17:25:19 +02002758 for args, exe_list, cwd, env_list in (
2759 (123, [b"exe"], None, [b"env"]),
2760 ([b"arg"], 123, None, [b"env"]),
2761 ([b"arg"], [b"exe"], 123, [b"env"]),
2762 ([b"arg"], [b"exe"], None, 123),
2763 ):
2764 with self.assertRaises(TypeError):
2765 _posixsubprocess.fork_exec(
2766 args, exe_list,
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03002767 True, (), cwd, env_list,
Victor Stinner8f437aa2014-10-05 17:25:19 +02002768 -1, -1, -1, -1,
2769 1, 2, 3, 4,
2770 True, True, func)
2771 finally:
2772 if not gc_enabled:
2773 gc.disable()
2774
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08002775 @support.cpython_only
2776 def test_fork_exec_sorted_fd_sanity_check(self):
2777 # Issue #23564: sanity check the fork_exec() fds_to_keep sanity check.
2778 import _posixsubprocess
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03002779 class BadInt:
2780 first = True
2781 def __init__(self, value):
2782 self.value = value
2783 def __int__(self):
2784 if self.first:
2785 self.first = False
2786 return self.value
2787 raise ValueError
2788
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08002789 gc_enabled = gc.isenabled()
2790 try:
2791 gc.enable()
2792
2793 for fds_to_keep in (
2794 (-1, 2, 3, 4, 5), # Negative number.
2795 ('str', 4), # Not an int.
2796 (18, 23, 42, 2**63), # Out of range.
2797 (5, 4), # Not sorted.
2798 (6, 7, 7, 8), # Duplicate.
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03002799 (BadInt(1), BadInt(2)),
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08002800 ):
2801 with self.assertRaises(
2802 ValueError,
2803 msg='fds_to_keep={}'.format(fds_to_keep)) as c:
2804 _posixsubprocess.fork_exec(
2805 [b"false"], [b"false"],
2806 True, fds_to_keep, None, [b"env"],
2807 -1, -1, -1, -1,
2808 1, 2, 3, 4,
2809 True, True, None)
2810 self.assertIn('fds_to_keep', str(c.exception))
2811 finally:
2812 if not gc_enabled:
2813 gc.disable()
Victor Stinner8f437aa2014-10-05 17:25:19 +02002814
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)2daf8e72016-06-05 02:57:47 +00002815 def test_communicate_BrokenPipeError_stdin_close(self):
2816 # By not setting stdout or stderr or a timeout we force the fast path
2817 # that just calls _stdin_write() internally due to our mock.
2818 proc = subprocess.Popen([sys.executable, '-c', 'pass'])
2819 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
2820 mock_proc_stdin.close.side_effect = BrokenPipeError
2821 proc.communicate() # Should swallow BrokenPipeError from close.
2822 mock_proc_stdin.close.assert_called_with()
2823
2824 def test_communicate_BrokenPipeError_stdin_write(self):
2825 # By not setting stdout or stderr or a timeout we force the fast path
2826 # that just calls _stdin_write() internally due to our mock.
2827 proc = subprocess.Popen([sys.executable, '-c', 'pass'])
2828 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
2829 mock_proc_stdin.write.side_effect = BrokenPipeError
2830 proc.communicate(b'stuff') # Should swallow the BrokenPipeError.
2831 mock_proc_stdin.write.assert_called_once_with(b'stuff')
2832 mock_proc_stdin.close.assert_called_once_with()
2833
2834 def test_communicate_BrokenPipeError_stdin_flush(self):
2835 # Setting stdin and stdout forces the ._communicate() code path.
2836 # python -h exits faster than python -c pass (but spams stdout).
2837 proc = subprocess.Popen([sys.executable, '-h'],
2838 stdin=subprocess.PIPE,
2839 stdout=subprocess.PIPE)
2840 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin, \
2841 open(os.devnull, 'wb') as dev_null:
2842 mock_proc_stdin.flush.side_effect = BrokenPipeError
2843 # because _communicate registers a selector using proc.stdin...
2844 mock_proc_stdin.fileno.return_value = dev_null.fileno()
2845 # _communicate() should swallow BrokenPipeError from flush.
2846 proc.communicate(b'stuff')
2847 mock_proc_stdin.flush.assert_called_once_with()
2848
2849 def test_communicate_BrokenPipeError_stdin_close_with_timeout(self):
2850 # Setting stdin and stdout forces the ._communicate() code path.
2851 # python -h exits faster than python -c pass (but spams stdout).
2852 proc = subprocess.Popen([sys.executable, '-h'],
2853 stdin=subprocess.PIPE,
2854 stdout=subprocess.PIPE)
2855 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
2856 mock_proc_stdin.close.side_effect = BrokenPipeError
2857 # _communicate() should swallow BrokenPipeError from close.
2858 proc.communicate(timeout=999)
2859 mock_proc_stdin.close.assert_called_once_with()
2860
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02002861 @unittest.skipUnless(_testcapi is not None
2862 and hasattr(_testcapi, 'W_STOPCODE'),
2863 'need _testcapi.W_STOPCODE')
2864 def test_stopped(self):
Gregory P. Smith50e16e32017-01-22 17:28:38 -08002865 """Test wait() behavior when waitpid returns WIFSTOPPED; issue29335."""
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02002866 args = [sys.executable, '-c', 'pass']
2867 proc = subprocess.Popen(args)
Victor Stinnercdee3f12017-06-26 17:23:03 +02002868
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02002869 # Wait until the real process completes to avoid zombie process
2870 pid = proc.pid
2871 pid, status = os.waitpid(pid, 0)
2872 self.assertEqual(status, 0)
Victor Stinnercdee3f12017-06-26 17:23:03 +02002873
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02002874 status = _testcapi.W_STOPCODE(3)
2875 with mock.patch('subprocess.os.waitpid', return_value=(pid, status)):
2876 returncode = proc.wait()
Victor Stinnercdee3f12017-06-26 17:23:03 +02002877
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02002878 self.assertEqual(returncode, -3)
Gregory P. Smith50e16e32017-01-22 17:28:38 -08002879
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002880
Victor Stinner937ee9e2018-06-26 02:11:06 +02002881@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00002882class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002883
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002884 def test_startupinfo(self):
2885 # startupinfo argument
2886 # We uses hardcoded constants, because we do not want to
2887 # depend on win32all.
2888 STARTF_USESHOWWINDOW = 1
2889 SW_MAXIMIZE = 3
2890 startupinfo = subprocess.STARTUPINFO()
2891 startupinfo.dwFlags = STARTF_USESHOWWINDOW
2892 startupinfo.wShowWindow = SW_MAXIMIZE
2893 # Since Python is a console process, it won't be affected
2894 # by wShowWindow, but the argument should be silently
2895 # ignored
2896 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002897 startupinfo=startupinfo)
2898
Subhendu Ghoshae160bb2017-02-25 20:29:05 +05302899 def test_startupinfo_keywords(self):
2900 # startupinfo argument
2901 # We use hardcoded constants, because we do not want to
2902 # depend on win32all.
2903 STARTF_USERSHOWWINDOW = 1
2904 SW_MAXIMIZE = 3
2905 startupinfo = subprocess.STARTUPINFO(
2906 dwFlags=STARTF_USERSHOWWINDOW,
2907 wShowWindow=SW_MAXIMIZE
2908 )
2909 # Since Python is a console process, it won't be affected
2910 # by wShowWindow, but the argument should be silently
2911 # ignored
2912 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
2913 startupinfo=startupinfo)
2914
Victor Stinner483422f2018-07-05 22:54:17 +02002915 def test_startupinfo_copy(self):
2916 # bpo-34044: Popen must not modify input STARTUPINFO structure
2917 startupinfo = subprocess.STARTUPINFO()
2918 startupinfo.dwFlags = subprocess.STARTF_USESHOWWINDOW
2919 startupinfo.wShowWindow = subprocess.SW_HIDE
2920
2921 # Call Popen() twice with the same startupinfo object to make sure
2922 # that it's not modified
2923 for _ in range(2):
2924 cmd = [sys.executable, "-c", "pass"]
2925 with open(os.devnull, 'w') as null:
2926 proc = subprocess.Popen(cmd,
2927 stdout=null,
2928 stderr=subprocess.STDOUT,
2929 startupinfo=startupinfo)
2930 with proc:
2931 proc.communicate()
2932 self.assertEqual(proc.returncode, 0)
2933
2934 self.assertEqual(startupinfo.dwFlags,
2935 subprocess.STARTF_USESHOWWINDOW)
2936 self.assertIsNone(startupinfo.hStdInput)
2937 self.assertIsNone(startupinfo.hStdOutput)
2938 self.assertIsNone(startupinfo.hStdError)
2939 self.assertEqual(startupinfo.wShowWindow, subprocess.SW_HIDE)
2940 self.assertEqual(startupinfo.lpAttributeList, {"handle_list": []})
2941
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002942 def test_creationflags(self):
2943 # creationflags argument
2944 CREATE_NEW_CONSOLE = 16
2945 sys.stderr.write(" a DOS box should flash briefly ...\n")
2946 subprocess.call(sys.executable +
2947 ' -c "import time; time.sleep(0.25)"',
2948 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002949
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002950 def test_invalid_args(self):
2951 # invalid arguments should raise ValueError
2952 self.assertRaises(ValueError, subprocess.call,
2953 [sys.executable, "-c",
2954 "import sys; sys.exit(47)"],
2955 preexec_fn=lambda: 1)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002956
Oren Milman0b3a87e2017-09-14 22:30:28 +03002957 @support.cpython_only
2958 def test_issue31471(self):
2959 # There shouldn't be an assertion failure in Popen() in case the env
2960 # argument has a bad keys() method.
2961 class BadEnv(dict):
2962 keys = None
2963 with self.assertRaises(TypeError):
2964 subprocess.Popen([sys.executable, "-c", "pass"], env=BadEnv())
2965
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002966 def test_close_fds(self):
2967 # close file descriptors
2968 rc = subprocess.call([sys.executable, "-c",
2969 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002970 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002971 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002972
Segev Finerb2a60832017-12-18 11:28:19 +02002973 def test_close_fds_with_stdio(self):
2974 import msvcrt
2975
2976 fds = os.pipe()
2977 self.addCleanup(os.close, fds[0])
2978 self.addCleanup(os.close, fds[1])
2979
2980 handles = []
2981 for fd in fds:
2982 os.set_inheritable(fd, True)
2983 handles.append(msvcrt.get_osfhandle(fd))
2984
2985 p = subprocess.Popen([sys.executable, "-c",
2986 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
2987 stdout=subprocess.PIPE, close_fds=False)
2988 stdout, stderr = p.communicate()
2989 self.assertEqual(p.returncode, 0)
2990 int(stdout.strip()) # Check that stdout is an integer
2991
2992 p = subprocess.Popen([sys.executable, "-c",
2993 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
2994 stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
2995 stdout, stderr = p.communicate()
2996 self.assertEqual(p.returncode, 1)
2997 self.assertIn(b"OSError", stderr)
2998
2999 # The same as the previous call, but with an empty handle_list
3000 handle_list = []
3001 startupinfo = subprocess.STARTUPINFO()
3002 startupinfo.lpAttributeList = {"handle_list": handle_list}
3003 p = subprocess.Popen([sys.executable, "-c",
3004 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3005 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
3006 startupinfo=startupinfo, close_fds=True)
3007 stdout, stderr = p.communicate()
3008 self.assertEqual(p.returncode, 1)
3009 self.assertIn(b"OSError", stderr)
3010
3011 # Check for a warning due to using handle_list and close_fds=False
3012 with support.check_warnings((".*overriding close_fds", RuntimeWarning)):
3013 startupinfo = subprocess.STARTUPINFO()
3014 startupinfo.lpAttributeList = {"handle_list": handles[:]}
3015 p = subprocess.Popen([sys.executable, "-c",
3016 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3017 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
3018 startupinfo=startupinfo, close_fds=False)
3019 stdout, stderr = p.communicate()
3020 self.assertEqual(p.returncode, 0)
3021
3022 def test_empty_attribute_list(self):
3023 startupinfo = subprocess.STARTUPINFO()
3024 startupinfo.lpAttributeList = {}
3025 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
3026 startupinfo=startupinfo)
3027
3028 def test_empty_handle_list(self):
3029 startupinfo = subprocess.STARTUPINFO()
3030 startupinfo.lpAttributeList = {"handle_list": []}
3031 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
3032 startupinfo=startupinfo)
3033
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003034 def test_shell_sequence(self):
3035 # Run command through the shell (sequence)
3036 newenv = os.environ.copy()
3037 newenv["FRUIT"] = "physalis"
3038 p = subprocess.Popen(["set"], shell=1,
3039 stdout=subprocess.PIPE,
3040 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02003041 with p:
3042 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00003043
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003044 def test_shell_string(self):
3045 # Run command through the shell (string)
3046 newenv = os.environ.copy()
3047 newenv["FRUIT"] = "physalis"
3048 p = subprocess.Popen("set", shell=1,
3049 stdout=subprocess.PIPE,
3050 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02003051 with p:
3052 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003053
Steve Dower050acae2016-09-06 20:16:17 -07003054 def test_shell_encodings(self):
3055 # Run command through the shell (string)
3056 for enc in ['ansi', 'oem']:
3057 newenv = os.environ.copy()
3058 newenv["FRUIT"] = "physalis"
3059 p = subprocess.Popen("set", shell=1,
3060 stdout=subprocess.PIPE,
3061 env=newenv,
3062 encoding=enc)
3063 with p:
3064 self.assertIn("physalis", p.stdout.read(), enc)
3065
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003066 def test_call_string(self):
3067 # call() function with string argument on Windows
3068 rc = subprocess.call(sys.executable +
3069 ' -c "import sys; sys.exit(47)"')
3070 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003071
Florent Xicluna4886d242010-03-08 13:27:26 +00003072 def _kill_process(self, method, *args):
3073 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00003074 p = subprocess.Popen([sys.executable, "-c", """if 1:
3075 import sys, time
3076 sys.stdout.write('x\\n')
3077 sys.stdout.flush()
3078 time.sleep(30)
3079 """],
3080 stdin=subprocess.PIPE,
3081 stdout=subprocess.PIPE,
3082 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02003083 with p:
3084 # Wait for the interpreter to be completely initialized before
3085 # sending any signal.
3086 p.stdout.read(1)
3087 getattr(p, method)(*args)
3088 _, stderr = p.communicate()
3089 self.assertStderrEqual(stderr, b'')
3090 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00003091 self.assertNotEqual(returncode, 0)
3092
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003093 def _kill_dead_process(self, method, *args):
3094 p = subprocess.Popen([sys.executable, "-c", """if 1:
3095 import sys, time
3096 sys.stdout.write('x\\n')
3097 sys.stdout.flush()
3098 sys.exit(42)
3099 """],
3100 stdin=subprocess.PIPE,
3101 stdout=subprocess.PIPE,
3102 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02003103 with p:
3104 # Wait for the interpreter to be completely initialized before
3105 # sending any signal.
3106 p.stdout.read(1)
3107 # The process should end after this
3108 time.sleep(1)
3109 # This shouldn't raise even though the child is now dead
3110 getattr(p, method)(*args)
3111 _, stderr = p.communicate()
3112 self.assertStderrEqual(stderr, b'')
3113 rc = p.wait()
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003114 self.assertEqual(rc, 42)
3115
Florent Xicluna4886d242010-03-08 13:27:26 +00003116 def test_send_signal(self):
3117 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00003118
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003119 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00003120 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00003121
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003122 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00003123 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00003124
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003125 def test_send_signal_dead(self):
3126 self._kill_dead_process('send_signal', signal.SIGTERM)
3127
3128 def test_kill_dead(self):
3129 self._kill_dead_process('kill')
3130
3131 def test_terminate_dead(self):
3132 self._kill_dead_process('terminate')
3133
Martin Panter23172bd2016-04-16 11:28:10 +00003134class MiscTests(unittest.TestCase):
Gregory P. Smithf4d644f2018-01-29 21:27:39 -08003135
3136 class RecordingPopen(subprocess.Popen):
3137 """A Popen that saves a reference to each instance for testing."""
3138 instances_created = []
3139
3140 def __init__(self, *args, **kwargs):
3141 super().__init__(*args, **kwargs)
3142 self.instances_created.append(self)
3143
3144 @mock.patch.object(subprocess.Popen, "_communicate")
3145 def _test_keyboardinterrupt_no_kill(self, popener, mock__communicate,
3146 **kwargs):
3147 """Fake a SIGINT happening during Popen._communicate() and ._wait().
3148
3149 This avoids the need to actually try and get test environments to send
3150 and receive signals reliably across platforms. The net effect of a ^C
3151 happening during a blocking subprocess execution which we want to clean
3152 up from is a KeyboardInterrupt coming out of communicate() or wait().
3153 """
3154
3155 mock__communicate.side_effect = KeyboardInterrupt
3156 try:
3157 with mock.patch.object(subprocess.Popen, "_wait") as mock__wait:
3158 # We patch out _wait() as no signal was involved so the
3159 # child process isn't actually going to exit rapidly.
3160 mock__wait.side_effect = KeyboardInterrupt
3161 with mock.patch.object(subprocess, "Popen",
3162 self.RecordingPopen):
3163 with self.assertRaises(KeyboardInterrupt):
3164 popener([sys.executable, "-c",
3165 "import time\ntime.sleep(9)\nimport sys\n"
3166 "sys.stderr.write('\\n!runaway child!\\n')"],
3167 stdout=subprocess.DEVNULL, **kwargs)
3168 for call in mock__wait.call_args_list[1:]:
3169 self.assertNotEqual(
3170 call, mock.call(timeout=None),
3171 "no open-ended wait() after the first allowed: "
3172 f"{mock__wait.call_args_list}")
3173 sigint_calls = []
3174 for call in mock__wait.call_args_list:
3175 if call == mock.call(timeout=0.25): # from Popen.__init__
3176 sigint_calls.append(call)
3177 self.assertLessEqual(mock__wait.call_count, 2,
3178 msg=mock__wait.call_args_list)
3179 self.assertEqual(len(sigint_calls), 1,
3180 msg=mock__wait.call_args_list)
3181 finally:
3182 # cleanup the forgotten (due to our mocks) child process
3183 process = self.RecordingPopen.instances_created.pop()
3184 process.kill()
3185 process.wait()
3186 self.assertEqual([], self.RecordingPopen.instances_created)
3187
3188 def test_call_keyboardinterrupt_no_kill(self):
3189 self._test_keyboardinterrupt_no_kill(subprocess.call, timeout=6.282)
3190
3191 def test_run_keyboardinterrupt_no_kill(self):
3192 self._test_keyboardinterrupt_no_kill(subprocess.run, timeout=6.282)
3193
3194 def test_context_manager_keyboardinterrupt_no_kill(self):
3195 def popen_via_context_manager(*args, **kwargs):
3196 with subprocess.Popen(*args, **kwargs) as unused_process:
3197 raise KeyboardInterrupt # Test how __exit__ handles ^C.
3198 self._test_keyboardinterrupt_no_kill(popen_via_context_manager)
3199
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003200 def test_getoutput(self):
3201 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
3202 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
3203 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00003204
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003205 # we use mkdtemp in the next line to create an empty directory
3206 # under our exclusive control; from that, we can invent a pathname
3207 # that we _know_ won't exist. This is guaranteed to fail.
3208 dir = None
3209 try:
3210 dir = tempfile.mkdtemp()
3211 name = os.path.join(dir, "foo")
Tim Goldene0041752013-11-03 12:53:17 +00003212 status, output = subprocess.getstatusoutput(
Victor Stinner937ee9e2018-06-26 02:11:06 +02003213 ("type " if mswindows else "cat ") + name)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003214 self.assertNotEqual(status, 0)
3215 finally:
3216 if dir is not None:
3217 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00003218
Gregory P. Smithace55862015-04-07 15:57:54 -07003219 def test__all__(self):
3220 """Ensure that __all__ is populated properly."""
Martin Panter528619b2016-04-16 23:42:37 +00003221 intentionally_excluded = {"list2cmdline", "Handle"}
Gregory P. Smithace55862015-04-07 15:57:54 -07003222 exported = set(subprocess.__all__)
3223 possible_exports = set()
3224 import types
3225 for name, value in subprocess.__dict__.items():
3226 if name.startswith('_'):
3227 continue
3228 if isinstance(value, (types.ModuleType,)):
3229 continue
3230 possible_exports.add(name)
3231 self.assertEqual(exported, possible_exports - intentionally_excluded)
3232
3233
Martin Panter23172bd2016-04-16 11:28:10 +00003234@unittest.skipUnless(hasattr(selectors, 'PollSelector'),
3235 "Test needs selectors.PollSelector")
3236class ProcessTestCaseNoPoll(ProcessTestCase):
3237 def setUp(self):
3238 self.orig_selector = subprocess._PopenSelector
3239 subprocess._PopenSelector = selectors.SelectSelector
3240 ProcessTestCase.setUp(self)
3241
3242 def tearDown(self):
3243 subprocess._PopenSelector = self.orig_selector
3244 ProcessTestCase.tearDown(self)
3245
Gregory P. Smithd06fa472009-07-04 02:46:54 +00003246
Victor Stinner937ee9e2018-06-26 02:11:06 +02003247@unittest.skipUnless(mswindows, "Windows-specific tests")
Tim Golden126c2962010-08-11 14:20:40 +00003248class CommandsWithSpaces (BaseTestCase):
3249
3250 def setUp(self):
3251 super().setUp()
Berker Peksag16a1f282015-09-28 13:33:14 +03003252 f, fname = tempfile.mkstemp(".py", "te st")
Tim Golden126c2962010-08-11 14:20:40 +00003253 self.fname = fname.lower ()
3254 os.write(f, b"import sys;"
3255 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
3256 )
3257 os.close(f)
3258
3259 def tearDown(self):
3260 os.remove(self.fname)
3261 super().tearDown()
3262
3263 def with_spaces(self, *args, **kwargs):
3264 kwargs['stdout'] = subprocess.PIPE
3265 p = subprocess.Popen(*args, **kwargs)
Victor Stinner7438c612016-05-20 12:43:15 +02003266 with p:
3267 self.assertEqual(
3268 p.stdout.read ().decode("mbcs"),
3269 "2 [%r, 'ab cd']" % self.fname
3270 )
Tim Golden126c2962010-08-11 14:20:40 +00003271
3272 def test_shell_string_with_spaces(self):
3273 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00003274 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
3275 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00003276
3277 def test_shell_sequence_with_spaces(self):
3278 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00003279 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00003280
3281 def test_noshell_string_with_spaces(self):
3282 # call() function with string argument with spaces on Windows
3283 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
3284 "ab cd"))
3285
3286 def test_noshell_sequence_with_spaces(self):
3287 # call() function with sequence argument with spaces on Windows
3288 self.with_spaces([sys.executable, self.fname, "ab cd"])
3289
Brian Curtin79cdb662010-12-03 02:46:02 +00003290
Georg Brandla86b2622012-02-20 21:34:57 +01003291class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00003292
3293 def test_pipe(self):
3294 with subprocess.Popen([sys.executable, "-c",
3295 "import sys;"
3296 "sys.stdout.write('stdout');"
3297 "sys.stderr.write('stderr');"],
3298 stdout=subprocess.PIPE,
3299 stderr=subprocess.PIPE) as proc:
3300 self.assertEqual(proc.stdout.read(), b"stdout")
3301 self.assertStderrEqual(proc.stderr.read(), b"stderr")
3302
3303 self.assertTrue(proc.stdout.closed)
3304 self.assertTrue(proc.stderr.closed)
3305
3306 def test_returncode(self):
3307 with subprocess.Popen([sys.executable, "-c",
3308 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07003309 pass
3310 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00003311 self.assertEqual(proc.returncode, 100)
3312
3313 def test_communicate_stdin(self):
3314 with subprocess.Popen([sys.executable, "-c",
3315 "import sys;"
3316 "sys.exit(sys.stdin.read() == 'context')"],
3317 stdin=subprocess.PIPE) as proc:
3318 proc.communicate(b"context")
3319 self.assertEqual(proc.returncode, 1)
3320
3321 def test_invalid_args(self):
Victor Stinnerb31206a2018-01-25 19:06:05 +01003322 with self.assertRaises(NONEXISTING_ERRORS):
Victor Stinner9a83f652017-08-21 23:51:31 +02003323 with subprocess.Popen(NONEXISTING_CMD,
Brian Curtin79cdb662010-12-03 02:46:02 +00003324 stdout=subprocess.PIPE,
3325 stderr=subprocess.PIPE) as proc:
3326 pass
3327
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003328 def test_broken_pipe_cleanup(self):
3329 """Broken pipe error should not prevent wait() (Issue 21619)"""
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003330 proc = subprocess.Popen([sys.executable, '-c', 'pass'],
Victor Stinner20f4bd42015-03-05 02:38:41 +01003331 stdin=subprocess.PIPE,
Victor Stinner20f4bd42015-03-05 02:38:41 +01003332 bufsize=support.PIPE_MAX_SIZE*2)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003333 proc = proc.__enter__()
3334 # Prepare to send enough data to overflow any OS pipe buffering and
3335 # guarantee a broken pipe error. Data is held in BufferedWriter
3336 # buffer until closed.
3337 proc.stdin.write(b'x' * support.PIPE_MAX_SIZE)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003338 self.assertIsNone(proc.returncode)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003339 # EPIPE expected under POSIX; EINVAL under Windows
Serhiy Storchakacf265fd2015-02-28 13:27:54 +02003340 self.assertRaises(OSError, proc.__exit__, None, None, None)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003341 self.assertEqual(proc.returncode, 0)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003342 self.assertTrue(proc.stdin.closed)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003343
Brian Curtin79cdb662010-12-03 02:46:02 +00003344
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003345if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04003346 unittest.main()