blob: 97dc09c564965ae9409d9990c4e5861131034470 [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
Gregory P. Smith580d2782019-09-11 04:23:05 -050013import traceback
Charles-François Natali3a4586a2013-11-08 19:56:59 +010014import selectors
Ezio Melotti184bdfb2010-02-18 09:37:05 +000015import sysconfig
Gregory P. Smith51ee2702010-12-13 07:59:39 +000016import select
Gregory P. Smith81ce6852011-03-15 02:04:11 -040017import shutil
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020018import threading
Benjamin Petersonb870aa12011-12-10 12:44:25 -050019import gc
Andrew Svetlov47ec25d2012-08-19 16:25:37 +030020import textwrap
Patrick McLean2b2ead72019-09-12 10:15:44 -070021import json
Serhiy Storchakab21d1552018-03-02 11:53:51 +020022from test.support import FakePath
Benjamin Peterson964561b2011-12-10 12:31:42 -050023
24try:
Victor Stinner7b7c6dc2017-08-10 12:37:39 +020025 import _testcapi
26except ImportError:
27 _testcapi = None
28
Patrick McLean2b2ead72019-09-12 10:15:44 -070029try:
30 import pwd
31except ImportError:
32 pwd = None
33try:
34 import grp
35except ImportError:
36 grp = None
Victor Stinner8f4ef3b2019-07-01 18:28:25 +020037
Steve Dower22d06982016-09-06 19:38:15 -070038if support.PGO:
39 raise unittest.SkipTest("test is not helpful for PGO")
40
Victor Stinner937ee9e2018-06-26 02:11:06 +020041mswindows = (sys.platform == "win32")
42
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000043#
44# Depends on the following external programs: Python
45#
46
Victor Stinner937ee9e2018-06-26 02:11:06 +020047if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000048 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
49 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000050else:
51 SETBINARY = ''
52
Victor Stinner9a83f652017-08-21 23:51:31 +020053NONEXISTING_CMD = ('nonexisting_i_hope',)
Victor Stinnerb31206a2018-01-25 19:06:05 +010054# Ignore errors that indicate the command was not found
55NONEXISTING_ERRORS = (FileNotFoundError, NotADirectoryError, PermissionError)
Victor Stinner9a83f652017-08-21 23:51:31 +020056
Gregory P. Smith67b93f82019-10-12 16:35:53 -070057ZERO_RETURN_CMD = (sys.executable, '-c', 'pass')
58
59
60def setUpModule():
61 shell_true = shutil.which('true')
Pablo Galindo46113e02019-10-13 02:40:24 +010062 if shell_true is None:
63 return
Gregory P. Smith67b93f82019-10-12 16:35:53 -070064 if (os.access(shell_true, os.X_OK) and
65 subprocess.run([shell_true]).returncode == 0):
66 global ZERO_RETURN_CMD
67 ZERO_RETURN_CMD = (shell_true,) # Faster than Python startup.
68
Florent Xiclunab1e94e82010-02-27 22:12:37 +000069
Florent Xiclunac049d872010-03-27 22:47:23 +000070class BaseTestCase(unittest.TestCase):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000071 def setUp(self):
72 # Try to minimize the number of children we have so this test
73 # doesn't crash on some buildbots (Alphas in particular).
Florent Xiclunab1e94e82010-02-27 22:12:37 +000074 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000075
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000076 def tearDown(self):
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +030077 if not mswindows:
78 # subprocess._active is not used on Windows and is set to None.
79 for inst in subprocess._active:
80 inst.wait()
81 subprocess._cleanup()
82 self.assertFalse(
83 subprocess._active, "subprocess._active not empty"
84 )
Victor Stinnercc42c122017-07-28 18:00:22 +020085 self.doCleanups()
86 support.reap_children()
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000087
Florent Xiclunab1e94e82010-02-27 22:12:37 +000088 def assertStderrEqual(self, stderr, expected, msg=None):
89 # In a debug build, stuff like "[6580 refs]" is printed to stderr at
90 # shutdown time. That frustrates tests trying to check stderr produced
91 # from a spawned Python process.
Antoine Pitrou62f68ed2010-08-04 11:48:56 +000092 actual = support.strip_python_stderr(stderr)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -040093 # strip_python_stderr also strips whitespace, so we do too.
94 expected = expected.strip()
Florent Xiclunab1e94e82010-02-27 22:12:37 +000095 self.assertEqual(actual, expected, msg)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000096
Florent Xiclunac049d872010-03-27 22:47:23 +000097
Gregory P. Smith3d8e7762012-11-10 22:32:22 -080098class PopenTestException(Exception):
99 pass
100
101
102class PopenExecuteChildRaises(subprocess.Popen):
103 """Popen subclass for testing cleanup of subprocess.PIPE filehandles when
104 _execute_child fails.
105 """
106 def _execute_child(self, *args, **kwargs):
107 raise PopenTestException("Forced Exception for Test")
108
109
Florent Xiclunac049d872010-03-27 22:47:23 +0000110class ProcessTestCase(BaseTestCase):
111
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700112 def test_io_buffered_by_default(self):
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700113 p = subprocess.Popen(ZERO_RETURN_CMD,
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700114 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
115 stderr=subprocess.PIPE)
116 try:
117 self.assertIsInstance(p.stdin, io.BufferedIOBase)
118 self.assertIsInstance(p.stdout, io.BufferedIOBase)
119 self.assertIsInstance(p.stderr, io.BufferedIOBase)
120 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -0700121 p.stdin.close()
122 p.stdout.close()
123 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700124 p.wait()
125
126 def test_io_unbuffered_works(self):
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700127 p = subprocess.Popen(ZERO_RETURN_CMD,
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700128 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
129 stderr=subprocess.PIPE, bufsize=0)
130 try:
131 self.assertIsInstance(p.stdin, io.RawIOBase)
132 self.assertIsInstance(p.stdout, io.RawIOBase)
133 self.assertIsInstance(p.stderr, io.RawIOBase)
134 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -0700135 p.stdin.close()
136 p.stdout.close()
137 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700138 p.wait()
139
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000140 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000141 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +0000142 rc = subprocess.call([sys.executable, "-c",
143 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000144 self.assertEqual(rc, 47)
145
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400146 def test_call_timeout(self):
147 # call() function with timeout argument; we want to test that the child
148 # process gets killed when the timeout expires. If the child isn't
149 # killed, this call will deadlock since subprocess.call waits for the
150 # child.
151 self.assertRaises(subprocess.TimeoutExpired, subprocess.call,
152 [sys.executable, "-c", "while True: pass"],
153 timeout=0.1)
154
Peter Astrand454f7672005-01-01 09:36:35 +0000155 def test_check_call_zero(self):
156 # check_call() function with zero return code
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700157 rc = subprocess.check_call(ZERO_RETURN_CMD)
Peter Astrand454f7672005-01-01 09:36:35 +0000158 self.assertEqual(rc, 0)
159
160 def test_check_call_nonzero(self):
161 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000162 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +0000163 subprocess.check_call([sys.executable, "-c",
164 "import sys; sys.exit(47)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000165 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +0000166
Georg Brandlf9734072008-12-07 15:30:06 +0000167 def test_check_output(self):
168 # check_output() function with zero return code
169 output = subprocess.check_output(
170 [sys.executable, "-c", "print('BDFL')"])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000171 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000172
173 def test_check_output_nonzero(self):
174 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000175 with self.assertRaises(subprocess.CalledProcessError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000176 subprocess.check_output(
177 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000178 self.assertEqual(c.exception.returncode, 5)
Georg Brandlf9734072008-12-07 15:30:06 +0000179
180 def test_check_output_stderr(self):
181 # check_output() function stderr redirected to stdout
182 output = subprocess.check_output(
183 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
184 stderr=subprocess.STDOUT)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000185 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000186
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300187 def test_check_output_stdin_arg(self):
188 # check_output() can be called with stdin set to a file
189 tf = tempfile.TemporaryFile()
190 self.addCleanup(tf.close)
191 tf.write(b'pear')
192 tf.seek(0)
193 output = subprocess.check_output(
194 [sys.executable, "-c",
195 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
196 stdin=tf)
197 self.assertIn(b'PEAR', output)
198
199 def test_check_output_input_arg(self):
200 # check_output() can be called with input set to a string
201 output = subprocess.check_output(
202 [sys.executable, "-c",
203 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
204 input=b'pear')
205 self.assertIn(b'PEAR', output)
206
Georg Brandlf9734072008-12-07 15:30:06 +0000207 def test_check_output_stdout_arg(self):
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300208 # check_output() refuses to accept 'stdout' argument
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000209 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000210 output = subprocess.check_output(
211 [sys.executable, "-c", "print('will not be run')"],
212 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +0000213 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000214 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +0000215
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300216 def test_check_output_stdin_with_input_arg(self):
217 # check_output() refuses to accept 'stdin' with 'input'
218 tf = tempfile.TemporaryFile()
219 self.addCleanup(tf.close)
220 tf.write(b'pear')
221 tf.seek(0)
222 with self.assertRaises(ValueError) as c:
223 output = subprocess.check_output(
224 [sys.executable, "-c", "print('will not be run')"],
225 stdin=tf, input=b'hare')
226 self.fail("Expected ValueError when stdin and input args supplied.")
227 self.assertIn('stdin', c.exception.args[0])
228 self.assertIn('input', c.exception.args[0])
229
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400230 def test_check_output_timeout(self):
231 # check_output() function with timeout arg
232 with self.assertRaises(subprocess.TimeoutExpired) as c:
233 output = subprocess.check_output(
234 [sys.executable, "-c",
Victor Stinner149b1c72011-06-06 23:43:02 +0200235 "import sys, time\n"
236 "sys.stdout.write('BDFL')\n"
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400237 "sys.stdout.flush()\n"
Victor Stinner149b1c72011-06-06 23:43:02 +0200238 "time.sleep(3600)"],
Reid Klecknerda9ac722011-03-16 17:08:21 -0400239 # Some heavily loaded buildbots (sparc Debian 3.x) require
240 # this much time to start and print.
241 timeout=3)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400242 self.fail("Expected TimeoutExpired.")
243 self.assertEqual(c.exception.output, b'BDFL')
244
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000245 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000246 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000247 newenv = os.environ.copy()
248 newenv["FRUIT"] = "banana"
249 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000250 'import sys, os;'
251 'sys.exit(os.getenv("FRUIT")=="banana")'],
252 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000253 self.assertEqual(rc, 1)
254
Victor Stinner87b9bc32011-06-01 00:57:47 +0200255 def test_invalid_args(self):
256 # Popen() called with invalid arguments should raise TypeError
257 # but Popen.__del__ should not complain (issue #12085)
258 with support.captured_stderr() as s:
259 self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1)
260 argcount = subprocess.Popen.__init__.__code__.co_argcount
261 too_many_args = [0] * (argcount + 1)
262 self.assertRaises(TypeError, subprocess.Popen, *too_many_args)
263 self.assertEqual(s.getvalue(), '')
264
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000265 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000266 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000267 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000268 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000269 self.addCleanup(p.stdout.close)
270 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000271 p.wait()
272 self.assertEqual(p.stdin, None)
273
274 def test_stdout_none(self):
Ezio Melotti42a541b2013-03-11 05:53:34 +0200275 # .stdout is None when not redirected, and the child's stdout will
276 # be inherited from the parent. In order to test this we run a
277 # subprocess in a subprocess:
278 # this_test
279 # \-- subprocess created by this test (parent)
280 # \-- subprocess created by the parent subprocess (child)
281 # The parent doesn't specify stdout, so the child will use the
282 # parent's stdout. This test checks that the message printed by the
283 # child goes to the parent stdout. The parent also checks that the
284 # child's stdout is None. See #11963.
285 code = ('import sys; from subprocess import Popen, PIPE;'
286 'p = Popen([sys.executable, "-c", "print(\'test_stdout_none\')"],'
287 ' stdin=PIPE, stderr=PIPE);'
288 'p.wait(); assert p.stdout is None;')
289 p = subprocess.Popen([sys.executable, "-c", code],
290 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
291 self.addCleanup(p.stdout.close)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000292 self.addCleanup(p.stderr.close)
Ezio Melotti42a541b2013-03-11 05:53:34 +0200293 out, err = p.communicate()
294 self.assertEqual(p.returncode, 0, err)
295 self.assertEqual(out.rstrip(), b'test_stdout_none')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000296
297 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000298 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000299 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000300 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000301 self.addCleanup(p.stdout.close)
302 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000303 p.wait()
304 self.assertEqual(p.stderr, None)
305
Chris Jerdonek776cb192012-10-08 15:56:43 -0700306 def _assert_python(self, pre_args, **kwargs):
307 # We include sys.exit() to prevent the test runner from hanging
308 # whenever python is found.
309 args = pre_args + ["import sys; sys.exit(47)"]
310 p = subprocess.Popen(args, **kwargs)
311 p.wait()
312 self.assertEqual(47, p.returncode)
313
314 def test_executable(self):
315 # Check that the executable argument works.
Chris Jerdonek86b0fb22012-10-09 13:17:49 -0700316 #
317 # On Unix (non-Mac and non-Windows), Python looks at args[0] to
318 # determine where its standard library is, so we need the directory
319 # of args[0] to be valid for the Popen() call to Python to succeed.
320 # See also issue #16170 and issue #7774.
321 doesnotexist = os.path.join(os.path.dirname(sys.executable),
322 "doesnotexist")
323 self._assert_python([doesnotexist, "-c"], executable=sys.executable)
Chris Jerdonek776cb192012-10-08 15:56:43 -0700324
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +0300325 def test_bytes_executable(self):
326 doesnotexist = os.path.join(os.path.dirname(sys.executable),
327 "doesnotexist")
328 self._assert_python([doesnotexist, "-c"],
329 executable=os.fsencode(sys.executable))
330
331 def test_pathlike_executable(self):
332 doesnotexist = os.path.join(os.path.dirname(sys.executable),
333 "doesnotexist")
334 self._assert_python([doesnotexist, "-c"],
335 executable=FakePath(sys.executable))
336
Chris Jerdonek776cb192012-10-08 15:56:43 -0700337 def test_executable_takes_precedence(self):
338 # Check that the executable argument takes precedence over args[0].
339 #
340 # Verify first that the call succeeds without the executable arg.
341 pre_args = [sys.executable, "-c"]
342 self._assert_python(pre_args)
Victor Stinnerb31206a2018-01-25 19:06:05 +0100343 self.assertRaises(NONEXISTING_ERRORS,
Xavier de Gaye38c8b7d2016-11-14 17:14:42 +0100344 self._assert_python, pre_args,
Victor Stinnerb31206a2018-01-25 19:06:05 +0100345 executable=NONEXISTING_CMD[0])
Chris Jerdonek776cb192012-10-08 15:56:43 -0700346
Victor Stinner937ee9e2018-06-26 02:11:06 +0200347 @unittest.skipIf(mswindows, "executable argument replaces shell")
Chris Jerdonek776cb192012-10-08 15:56:43 -0700348 def test_executable_replaces_shell(self):
349 # Check that the executable argument replaces the default shell
350 # when shell=True.
351 self._assert_python([], executable=sys.executable, shell=True)
352
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +0300353 @unittest.skipIf(mswindows, "executable argument replaces shell")
354 def test_bytes_executable_replaces_shell(self):
355 self._assert_python([], executable=os.fsencode(sys.executable),
356 shell=True)
357
358 @unittest.skipIf(mswindows, "executable argument replaces shell")
359 def test_pathlike_executable_replaces_shell(self):
360 self._assert_python([], executable=FakePath(sys.executable),
361 shell=True)
362
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700363 # For use in the test_cwd* tests below.
364 def _normalize_cwd(self, cwd):
365 # Normalize an expected cwd (for Tru64 support).
366 # We can't use os.path.realpath since it doesn't expand Tru64 {memb}
367 # strings. See bug #1063571.
Serhiy Storchaka2a23adf2015-09-06 14:13:25 +0300368 with support.change_cwd(cwd):
369 return os.getcwd()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700370
371 # For use in the test_cwd* tests below.
372 def _split_python_path(self):
373 # Return normalized (python_dir, python_base).
374 python_path = os.path.realpath(sys.executable)
375 return os.path.split(python_path)
376
377 # For use in the test_cwd* tests below.
378 def _assert_cwd(self, expected_cwd, python_arg, **kwargs):
379 # Invoke Python via Popen, and assert that (1) the call succeeds,
380 # and that (2) the current working directory of the child process
381 # matches *expected_cwd*.
382 p = subprocess.Popen([python_arg, "-c",
383 "import os, sys; "
384 "sys.stdout.write(os.getcwd()); "
385 "sys.exit(47)"],
386 stdout=subprocess.PIPE,
387 **kwargs)
388 self.addCleanup(p.stdout.close)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000389 p.wait()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700390 self.assertEqual(47, p.returncode)
391 normcase = os.path.normcase
392 self.assertEqual(normcase(expected_cwd),
393 normcase(p.stdout.read().decode("utf-8")))
394
395 def test_cwd(self):
396 # Check that cwd changes the cwd for the child process.
397 temp_dir = tempfile.gettempdir()
398 temp_dir = self._normalize_cwd(temp_dir)
399 self._assert_cwd(temp_dir, sys.executable, cwd=temp_dir)
400
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +0300401 def test_cwd_with_bytes(self):
402 temp_dir = tempfile.gettempdir()
403 temp_dir = self._normalize_cwd(temp_dir)
404 self._assert_cwd(temp_dir, sys.executable, cwd=os.fsencode(temp_dir))
405
Sayan Chowdhuryd5c11f72017-02-26 22:36:10 +0530406 def test_cwd_with_pathlike(self):
407 temp_dir = tempfile.gettempdir()
408 temp_dir = self._normalize_cwd(temp_dir)
Serhiy Storchakab21d1552018-03-02 11:53:51 +0200409 self._assert_cwd(temp_dir, sys.executable, cwd=FakePath(temp_dir))
Sayan Chowdhuryd5c11f72017-02-26 22:36:10 +0530410
Victor Stinner937ee9e2018-06-26 02:11:06 +0200411 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700412 def test_cwd_with_relative_arg(self):
413 # Check that Popen looks for args[0] relative to cwd if args[0]
414 # is relative.
415 python_dir, python_base = self._split_python_path()
416 rel_python = os.path.join(os.curdir, python_base)
417 with support.temp_cwd() as wrong_dir:
418 # Before calling with the correct cwd, confirm that the call fails
419 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700420 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700421 [rel_python])
Chris Jerdonek28714c82012-09-30 02:15:37 -0700422 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700423 [rel_python], cwd=wrong_dir)
424 python_dir = self._normalize_cwd(python_dir)
425 self._assert_cwd(python_dir, rel_python, cwd=python_dir)
426
Victor Stinner937ee9e2018-06-26 02:11:06 +0200427 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700428 def test_cwd_with_relative_executable(self):
429 # Check that Popen looks for executable relative to cwd if executable
430 # is relative (and that executable takes precedence over args[0]).
431 python_dir, python_base = self._split_python_path()
432 rel_python = os.path.join(os.curdir, python_base)
433 doesntexist = "somethingyoudonthave"
434 with support.temp_cwd() as wrong_dir:
435 # Before calling with the correct cwd, confirm that the call fails
436 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700437 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700438 [doesntexist], executable=rel_python)
Chris Jerdonek28714c82012-09-30 02:15:37 -0700439 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700440 [doesntexist], executable=rel_python,
441 cwd=wrong_dir)
442 python_dir = self._normalize_cwd(python_dir)
443 self._assert_cwd(python_dir, doesntexist, executable=rel_python,
444 cwd=python_dir)
445
446 def test_cwd_with_absolute_arg(self):
447 # Check that Popen can find the executable when the cwd is wrong
448 # if args[0] is an absolute path.
449 python_dir, python_base = self._split_python_path()
450 abs_python = os.path.join(python_dir, python_base)
451 rel_python = os.path.join(os.curdir, python_base)
Berker Peksagce643912015-05-06 06:33:17 +0300452 with support.temp_dir() as wrong_dir:
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700453 # Before calling with an absolute path, confirm that using a
454 # relative path fails.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700455 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700456 [rel_python], cwd=wrong_dir)
457 wrong_dir = self._normalize_cwd(wrong_dir)
458 self._assert_cwd(wrong_dir, abs_python, cwd=wrong_dir)
459
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100460 @unittest.skipIf(sys.base_prefix != sys.prefix,
461 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000462 def test_executable_with_cwd(self):
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700463 python_dir, python_base = self._split_python_path()
464 python_dir = self._normalize_cwd(python_dir)
465 self._assert_cwd(python_dir, "somethingyoudonthave",
466 executable=sys.executable, cwd=python_dir)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000467
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100468 @unittest.skipIf(sys.base_prefix != sys.prefix,
469 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000470 @unittest.skipIf(sysconfig.is_python_build(),
471 "need an installed Python. See #7774")
472 def test_executable_without_cwd(self):
473 # For a normal installation, it should work without 'cwd'
474 # argument. For test runs in the build directory, see #7774.
Ned Deilye92dfbf2013-08-02 18:02:21 -0700475 self._assert_cwd(os.getcwd(), "somethingyoudonthave",
476 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000477
478 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000479 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000480 p = subprocess.Popen([sys.executable, "-c",
481 'import sys; sys.exit(sys.stdin.read() == "pear")'],
482 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000483 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000484 p.stdin.close()
485 p.wait()
486 self.assertEqual(p.returncode, 1)
487
488 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000489 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000490 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000491 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000492 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000493 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000494 os.lseek(d, 0, 0)
495 p = subprocess.Popen([sys.executable, "-c",
496 'import sys; sys.exit(sys.stdin.read() == "pear")'],
497 stdin=d)
498 p.wait()
499 self.assertEqual(p.returncode, 1)
500
501 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000502 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000503 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000504 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000505 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000506 tf.seek(0)
507 p = subprocess.Popen([sys.executable, "-c",
508 'import sys; sys.exit(sys.stdin.read() == "pear")'],
509 stdin=tf)
510 p.wait()
511 self.assertEqual(p.returncode, 1)
512
513 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000514 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000515 p = subprocess.Popen([sys.executable, "-c",
516 'import sys; sys.stdout.write("orange")'],
517 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +0200518 with p:
519 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000520
521 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000522 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000523 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000524 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000525 d = tf.fileno()
526 p = subprocess.Popen([sys.executable, "-c",
527 'import sys; sys.stdout.write("orange")'],
528 stdout=d)
529 p.wait()
530 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000531 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000532
533 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000534 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000535 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000536 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000537 p = subprocess.Popen([sys.executable, "-c",
538 'import sys; sys.stdout.write("orange")'],
539 stdout=tf)
540 p.wait()
541 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000542 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000543
544 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000545 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000546 p = subprocess.Popen([sys.executable, "-c",
547 'import sys; sys.stderr.write("strawberry")'],
548 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +0200549 with p:
550 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000551
552 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000553 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000554 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000555 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000556 d = tf.fileno()
557 p = subprocess.Popen([sys.executable, "-c",
558 'import sys; sys.stderr.write("strawberry")'],
559 stderr=d)
560 p.wait()
561 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000562 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000563
564 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000565 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000566 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000567 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000568 p = subprocess.Popen([sys.executable, "-c",
569 'import sys; sys.stderr.write("strawberry")'],
570 stderr=tf)
571 p.wait()
572 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000573 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000574
Martin Panterc7635892016-05-13 01:54:44 +0000575 def test_stderr_redirect_with_no_stdout_redirect(self):
576 # test stderr=STDOUT while stdout=None (not set)
577
578 # - grandchild prints to stderr
579 # - child redirects grandchild's stderr to its stdout
580 # - the parent should get grandchild's stderr in child's stdout
581 p = subprocess.Popen([sys.executable, "-c",
582 'import sys, subprocess;'
583 'rc = subprocess.call([sys.executable, "-c",'
584 ' "import sys;"'
585 ' "sys.stderr.write(\'42\')"],'
586 ' stderr=subprocess.STDOUT);'
587 'sys.exit(rc)'],
588 stdout=subprocess.PIPE,
589 stderr=subprocess.PIPE)
590 stdout, stderr = p.communicate()
591 #NOTE: stdout should get stderr from grandchild
592 self.assertStderrEqual(stdout, b'42')
593 self.assertStderrEqual(stderr, b'') # should be empty
594 self.assertEqual(p.returncode, 0)
595
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000596 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000597 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000598 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000599 'import sys;'
600 'sys.stdout.write("apple");'
601 'sys.stdout.flush();'
602 'sys.stderr.write("orange")'],
603 stdout=subprocess.PIPE,
604 stderr=subprocess.STDOUT)
Victor Stinner7438c612016-05-20 12:43:15 +0200605 with p:
606 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000607
608 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000609 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000610 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000611 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000612 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000613 'import sys;'
614 'sys.stdout.write("apple");'
615 'sys.stdout.flush();'
616 'sys.stderr.write("orange")'],
617 stdout=tf,
618 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000619 p.wait()
620 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000621 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000622
Thomas Wouters89f507f2006-12-13 04:49:30 +0000623 def test_stdout_filedes_of_stdout(self):
624 # stdout is set to 1 (#1531862).
Ezio Melotti42a541b2013-03-11 05:53:34 +0200625 # To avoid printing the text on stdout, we do something similar to
626 # test_stdout_none (see above). The parent subprocess calls the child
627 # subprocess passing stdout=1, and this test uses stdout=PIPE in
628 # order to capture and check the output of the parent. See #11963.
629 code = ('import sys, subprocess; '
630 'rc = subprocess.call([sys.executable, "-c", '
631 ' "import os, sys; sys.exit(os.write(sys.stdout.fileno(), '
632 'b\'test with stdout=1\'))"], stdout=1); '
633 'assert rc == 18')
634 p = subprocess.Popen([sys.executable, "-c", code],
635 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
636 self.addCleanup(p.stdout.close)
637 self.addCleanup(p.stderr.close)
638 out, err = p.communicate()
639 self.assertEqual(p.returncode, 0, err)
640 self.assertEqual(out.rstrip(), b'test with stdout=1')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000641
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200642 def test_stdout_devnull(self):
643 p = subprocess.Popen([sys.executable, "-c",
644 'for i in range(10240):'
645 'print("x" * 1024)'],
646 stdout=subprocess.DEVNULL)
647 p.wait()
648 self.assertEqual(p.stdout, None)
649
650 def test_stderr_devnull(self):
651 p = subprocess.Popen([sys.executable, "-c",
652 'import sys\n'
653 'for i in range(10240):'
654 'sys.stderr.write("x" * 1024)'],
655 stderr=subprocess.DEVNULL)
656 p.wait()
657 self.assertEqual(p.stderr, None)
658
659 def test_stdin_devnull(self):
660 p = subprocess.Popen([sys.executable, "-c",
661 'import sys;'
662 'sys.stdin.read(1)'],
663 stdin=subprocess.DEVNULL)
664 p.wait()
665 self.assertEqual(p.stdin, None)
666
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000667 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000668 newenv = os.environ.copy()
669 newenv["FRUIT"] = "orange"
Victor Stinnerf1512a22011-06-21 17:18:38 +0200670 with subprocess.Popen([sys.executable, "-c",
671 'import sys,os;'
672 'sys.stdout.write(os.getenv("FRUIT"))'],
673 stdout=subprocess.PIPE,
674 env=newenv) as p:
675 stdout, stderr = p.communicate()
676 self.assertEqual(stdout, b"orange")
677
Victor Stinner62d51182011-06-23 01:02:25 +0200678 # Windows requires at least the SYSTEMROOT environment variable to start
679 # Python
680 @unittest.skipIf(sys.platform == 'win32',
681 'cannot test an empty env on Windows')
Gregory P. Smithb3512482017-05-30 14:40:37 -0700682 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') == 1,
683 'The Python shared library cannot be loaded '
684 'with an empty environment.')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200685 def test_empty_env(self):
Gregory P. Smithb3512482017-05-30 14:40:37 -0700686 """Verify that env={} is as empty as possible."""
687
Gregory P. Smith85aba232017-05-30 16:21:47 -0700688 def is_env_var_to_ignore(n):
Gregory P. Smithb3512482017-05-30 14:40:37 -0700689 """Determine if an environment variable is under our control."""
690 # This excludes some __CF_* and VERSIONER_* keys MacOS insists
691 # on adding even when the environment in exec is empty.
692 # Gentoo sandboxes also force LD_PRELOAD and SANDBOX_* to exist.
Gregory P. Smith85aba232017-05-30 16:21:47 -0700693 return ('VERSIONER' in n or '__CF' in n or # MacOS
Ned Deily918edc02017-09-04 00:00:21 -0400694 '__PYVENV_LAUNCHER__' in n or # MacOS framework build
Nick Coghlan6ea41862017-06-11 13:16:15 +1000695 n == 'LD_PRELOAD' or n.startswith('SANDBOX') or # Gentoo
696 n == 'LC_CTYPE') # Locale coercion triggered
Gregory P. Smithb3512482017-05-30 14:40:37 -0700697
Victor Stinnerf1512a22011-06-21 17:18:38 +0200698 with subprocess.Popen([sys.executable, "-c",
Gregory P. Smithb3512482017-05-30 14:40:37 -0700699 'import os; print(list(os.environ.keys()))'],
700 stdout=subprocess.PIPE, env={}) as p:
Victor Stinnerf1512a22011-06-21 17:18:38 +0200701 stdout, stderr = p.communicate()
Gregory P. Smithb3512482017-05-30 14:40:37 -0700702 child_env_names = eval(stdout.strip())
703 self.assertIsInstance(child_env_names, list)
704 child_env_names = [k for k in child_env_names
705 if not is_env_var_to_ignore(k)]
706 self.assertEqual(child_env_names, [])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000707
Serhiy Storchakad174d242017-06-23 19:39:27 +0300708 def test_invalid_cmd(self):
709 # null character in the command name
710 cmd = sys.executable + '\0'
711 with self.assertRaises(ValueError):
712 subprocess.Popen([cmd, "-c", "pass"])
713
714 # null character in the command argument
715 with self.assertRaises(ValueError):
716 subprocess.Popen([sys.executable, "-c", "pass#\0"])
717
718 def test_invalid_env(self):
Ville Skyttä49b27342017-08-03 09:00:59 +0300719 # null character in the environment variable name
Serhiy Storchakad174d242017-06-23 19:39:27 +0300720 newenv = os.environ.copy()
721 newenv["FRUIT\0VEGETABLE"] = "cabbage"
722 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700723 subprocess.Popen(ZERO_RETURN_CMD, env=newenv)
Serhiy Storchakad174d242017-06-23 19:39:27 +0300724
Ville Skyttä49b27342017-08-03 09:00:59 +0300725 # null character in the environment variable value
Serhiy Storchakad174d242017-06-23 19:39:27 +0300726 newenv = os.environ.copy()
727 newenv["FRUIT"] = "orange\0VEGETABLE=cabbage"
728 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700729 subprocess.Popen(ZERO_RETURN_CMD, env=newenv)
Serhiy Storchakad174d242017-06-23 19:39:27 +0300730
Ville Skyttä49b27342017-08-03 09:00:59 +0300731 # equal character in the environment variable name
Serhiy Storchakad174d242017-06-23 19:39:27 +0300732 newenv = os.environ.copy()
733 newenv["FRUIT=ORANGE"] = "lemon"
734 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700735 subprocess.Popen(ZERO_RETURN_CMD, env=newenv)
Serhiy Storchakad174d242017-06-23 19:39:27 +0300736
Ville Skyttä49b27342017-08-03 09:00:59 +0300737 # equal character in the environment variable value
Serhiy Storchakad174d242017-06-23 19:39:27 +0300738 newenv = os.environ.copy()
739 newenv["FRUIT"] = "orange=lemon"
740 with subprocess.Popen([sys.executable, "-c",
741 'import sys, os;'
742 'sys.stdout.write(os.getenv("FRUIT"))'],
743 stdout=subprocess.PIPE,
744 env=newenv) as p:
745 stdout, stderr = p.communicate()
746 self.assertEqual(stdout, b"orange=lemon")
747
Peter Astrandcbac93c2005-03-03 20:24:28 +0000748 def test_communicate_stdin(self):
749 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000750 'import sys;'
751 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000752 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000753 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000754 self.assertEqual(p.returncode, 1)
755
756 def test_communicate_stdout(self):
757 p = subprocess.Popen([sys.executable, "-c",
758 'import sys; sys.stdout.write("pineapple")'],
759 stdout=subprocess.PIPE)
760 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000761 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000762 self.assertEqual(stderr, None)
763
764 def test_communicate_stderr(self):
765 p = subprocess.Popen([sys.executable, "-c",
766 'import sys; sys.stderr.write("pineapple")'],
767 stderr=subprocess.PIPE)
768 (stdout, stderr) = p.communicate()
769 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000770 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000771
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000772 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000773 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000774 'import sys,os;'
775 'sys.stderr.write("pineapple");'
776 'sys.stdout.write(sys.stdin.read())'],
777 stdin=subprocess.PIPE,
778 stdout=subprocess.PIPE,
779 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000780 self.addCleanup(p.stdout.close)
781 self.addCleanup(p.stderr.close)
782 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000783 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000784 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000785 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000786
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400787 def test_communicate_timeout(self):
788 p = subprocess.Popen([sys.executable, "-c",
789 'import sys,os,time;'
790 'sys.stderr.write("pineapple\\n");'
791 'time.sleep(1);'
792 'sys.stderr.write("pear\\n");'
793 'sys.stdout.write(sys.stdin.read())'],
794 universal_newlines=True,
795 stdin=subprocess.PIPE,
796 stdout=subprocess.PIPE,
797 stderr=subprocess.PIPE)
798 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
799 timeout=0.3)
800 # Make sure we can keep waiting for it, and that we get the whole output
801 # after it completes.
802 (stdout, stderr) = p.communicate()
803 self.assertEqual(stdout, "banana")
804 self.assertStderrEqual(stderr.encode(), b"pineapple\npear\n")
805
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700806 def test_communicate_timeout_large_output(self):
Ross Lagerwall003c7a32012-02-12 09:02:01 +0200807 # Test an expiring timeout while the child is outputting lots of data.
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400808 p = subprocess.Popen([sys.executable, "-c",
809 'import sys,os,time;'
810 'sys.stdout.write("a" * (64 * 1024));'
811 'time.sleep(0.2);'
812 'sys.stdout.write("a" * (64 * 1024));'
813 'time.sleep(0.2);'
814 'sys.stdout.write("a" * (64 * 1024));'
815 'time.sleep(0.2);'
816 'sys.stdout.write("a" * (64 * 1024));'],
817 stdout=subprocess.PIPE)
818 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
819 (stdout, _) = p.communicate()
820 self.assertEqual(len(stdout), 4 * 64 * 1024)
821
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000822 # Test for the fd leak reported in http://bugs.python.org/issue2791.
823 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000824 for stdin_pipe in (False, True):
825 for stdout_pipe in (False, True):
826 for stderr_pipe in (False, True):
827 options = {}
828 if stdin_pipe:
829 options['stdin'] = subprocess.PIPE
830 if stdout_pipe:
831 options['stdout'] = subprocess.PIPE
832 if stderr_pipe:
833 options['stderr'] = subprocess.PIPE
834 if not options:
835 continue
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700836 p = subprocess.Popen(ZERO_RETURN_CMD, **options)
Victor Stinner667d4b52010-12-25 22:40:32 +0000837 p.communicate()
838 if p.stdin is not None:
839 self.assertTrue(p.stdin.closed)
840 if p.stdout is not None:
841 self.assertTrue(p.stdout.closed)
842 if p.stderr is not None:
843 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000844
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000845 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000846 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000847 p = subprocess.Popen([sys.executable, "-c",
848 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000849 (stdout, stderr) = p.communicate()
850 self.assertEqual(stdout, None)
851 self.assertEqual(stderr, None)
852
853 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000854 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000855 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000856 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000857 x, y = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000858 os.close(x)
859 os.close(y)
860 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000861 'import sys,os;'
862 'sys.stdout.write(sys.stdin.read(47));'
Charles-François Natali2d517212011-05-29 16:36:44 +0200863 'sys.stderr.write("x" * %d);'
864 'sys.stdout.write(sys.stdin.read())' %
865 support.PIPE_MAX_SIZE],
Guido van Rossum98297ee2007-11-06 21:34:58 +0000866 stdin=subprocess.PIPE,
867 stdout=subprocess.PIPE,
868 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000869 self.addCleanup(p.stdout.close)
870 self.addCleanup(p.stderr.close)
871 self.addCleanup(p.stdin.close)
Charles-François Natali2d517212011-05-29 16:36:44 +0200872 string_to_write = b"a" * support.PIPE_MAX_SIZE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000873 (stdout, stderr) = p.communicate(string_to_write)
874 self.assertEqual(stdout, string_to_write)
875
876 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000877 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000878 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000879 'import sys,os;'
880 'sys.stdout.write(sys.stdin.read())'],
881 stdin=subprocess.PIPE,
882 stdout=subprocess.PIPE,
883 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000884 self.addCleanup(p.stdout.close)
885 self.addCleanup(p.stderr.close)
886 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000887 p.stdin.write(b"banana")
888 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000889 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000890 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000891
andyclegg7fed7bd2017-10-23 03:01:19 +0100892 def test_universal_newlines_and_text(self):
893 args = [
894 sys.executable, "-c",
895 'import sys,os;' + SETBINARY +
896 'buf = sys.stdout.buffer;'
897 'buf.write(sys.stdin.readline().encode());'
898 'buf.flush();'
899 'buf.write(b"line2\\n");'
900 'buf.flush();'
901 'buf.write(sys.stdin.read().encode());'
902 'buf.flush();'
903 'buf.write(b"line4\\n");'
904 'buf.flush();'
905 'buf.write(b"line5\\r\\n");'
906 'buf.flush();'
907 'buf.write(b"line6\\r");'
908 'buf.flush();'
909 'buf.write(b"\\nline7");'
910 'buf.flush();'
911 'buf.write(b"\\nline8");']
912
913 for extra_kwarg in ('universal_newlines', 'text'):
914 p = subprocess.Popen(args, **{'stdin': subprocess.PIPE,
915 'stdout': subprocess.PIPE,
916 extra_kwarg: True})
917 with p:
918 p.stdin.write("line1\n")
919 p.stdin.flush()
920 self.assertEqual(p.stdout.readline(), "line1\n")
921 p.stdin.write("line3\n")
922 p.stdin.close()
923 self.addCleanup(p.stdout.close)
924 self.assertEqual(p.stdout.readline(),
925 "line2\n")
926 self.assertEqual(p.stdout.read(6),
927 "line3\n")
928 self.assertEqual(p.stdout.read(),
929 "line4\nline5\nline6\nline7\nline8")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000930
931 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000932 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000933 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000934 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200935 'buf = sys.stdout.buffer;'
936 'buf.write(b"line2\\n");'
937 'buf.flush();'
938 'buf.write(b"line4\\n");'
939 'buf.flush();'
940 'buf.write(b"line5\\r\\n");'
941 'buf.flush();'
942 'buf.write(b"line6\\r");'
943 'buf.flush();'
944 'buf.write(b"\\nline7");'
945 'buf.flush();'
946 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200947 stderr=subprocess.PIPE,
948 stdout=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000949 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000950 self.addCleanup(p.stdout.close)
951 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000952 (stdout, stderr) = p.communicate()
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200953 self.assertEqual(stdout,
954 "line2\nline4\nline5\nline6\nline7\nline8")
955
956 def test_universal_newlines_communicate_stdin(self):
957 # universal newlines through communicate(), with only stdin
958 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300959 'import sys,os;' + SETBINARY + textwrap.dedent('''
960 s = sys.stdin.readline()
961 assert s == "line1\\n", repr(s)
962 s = sys.stdin.read()
963 assert s == "line3\\n", repr(s)
964 ''')],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200965 stdin=subprocess.PIPE,
966 universal_newlines=1)
967 (stdout, stderr) = p.communicate("line1\nline3\n")
968 self.assertEqual(p.returncode, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000969
Andrew Svetlovf3765072012-08-14 18:35:17 +0300970 def test_universal_newlines_communicate_input_none(self):
971 # Test communicate(input=None) with universal newlines.
972 #
973 # We set stdout to PIPE because, as of this writing, a different
974 # code path is tested when the number of pipes is zero or one.
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700975 p = subprocess.Popen(ZERO_RETURN_CMD,
Andrew Svetlovf3765072012-08-14 18:35:17 +0300976 stdin=subprocess.PIPE,
977 stdout=subprocess.PIPE,
978 universal_newlines=True)
979 p.communicate()
980 self.assertEqual(p.returncode, 0)
981
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300982 def test_universal_newlines_communicate_stdin_stdout_stderr(self):
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300983 # universal newlines through communicate(), with stdin, stdout, stderr
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300984 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300985 'import sys,os;' + SETBINARY + textwrap.dedent('''
986 s = sys.stdin.buffer.readline()
987 sys.stdout.buffer.write(s)
988 sys.stdout.buffer.write(b"line2\\r")
989 sys.stderr.buffer.write(b"eline2\\n")
990 s = sys.stdin.buffer.read()
991 sys.stdout.buffer.write(s)
992 sys.stdout.buffer.write(b"line4\\n")
993 sys.stdout.buffer.write(b"line5\\r\\n")
994 sys.stderr.buffer.write(b"eline6\\r")
995 sys.stderr.buffer.write(b"eline7\\r\\nz")
996 ''')],
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300997 stdin=subprocess.PIPE,
998 stderr=subprocess.PIPE,
999 stdout=subprocess.PIPE,
Andrew Svetlov47ec25d2012-08-19 16:25:37 +03001000 universal_newlines=True)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +03001001 self.addCleanup(p.stdout.close)
1002 self.addCleanup(p.stderr.close)
1003 (stdout, stderr) = p.communicate("line1\nline3\n")
1004 self.assertEqual(p.returncode, 0)
Andrew Svetlov943c5b32012-08-16 20:17:47 +03001005 self.assertEqual("line1\nline2\nline3\nline4\nline5\n", stdout)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +03001006 # Python debug build push something like "[42442 refs]\n"
1007 # to stderr at exit of subprocess.
Andrew Svetlov943c5b32012-08-16 20:17:47 +03001008 # Don't use assertStderrEqual because it strips CR and LF from output.
1009 self.assertTrue(stderr.startswith("eline2\neline6\neline7\n"))
Andrew Svetlov5395d2f2012-08-15 22:46:43 +03001010
Andrew Svetlov82860712012-08-19 22:13:41 +03001011 def test_universal_newlines_communicate_encodings(self):
1012 # Check that universal newlines mode works for various encodings,
1013 # in particular for encodings in the UTF-16 and UTF-32 families.
1014 # See issue #15595.
1015 #
1016 # UTF-16 and UTF-32-BE are sufficient to check both with BOM and
1017 # without, and UTF-16 and UTF-32.
1018 for encoding in ['utf-16', 'utf-32-be']:
Andrew Svetlov82860712012-08-19 22:13:41 +03001019 code = ("import sys; "
1020 r"sys.stdout.buffer.write('1\r\n2\r3\n4'.encode('%s'))" %
1021 encoding)
1022 args = [sys.executable, '-c', code]
Steve Dower050acae2016-09-06 20:16:17 -07001023 # We set stdin to be non-None because, as of this writing,
1024 # a different code path is used when the number of pipes is
1025 # zero or one.
1026 popen = subprocess.Popen(args,
1027 stdin=subprocess.PIPE,
1028 stdout=subprocess.PIPE,
1029 encoding=encoding)
1030 stdout, stderr = popen.communicate(input='')
Andrew Svetlov82860712012-08-19 22:13:41 +03001031 self.assertEqual(stdout, '1\n2\n3\n4')
1032
Steve Dower050acae2016-09-06 20:16:17 -07001033 def test_communicate_errors(self):
1034 for errors, expected in [
1035 ('ignore', ''),
1036 ('replace', '\ufffd\ufffd'),
1037 ('surrogateescape', '\udc80\udc80'),
1038 ('backslashreplace', '\\x80\\x80'),
1039 ]:
1040 code = ("import sys; "
1041 r"sys.stdout.buffer.write(b'[\x80\x80]')")
1042 args = [sys.executable, '-c', code]
1043 # We set stdin to be non-None because, as of this writing,
1044 # a different code path is used when the number of pipes is
1045 # zero or one.
1046 popen = subprocess.Popen(args,
1047 stdin=subprocess.PIPE,
1048 stdout=subprocess.PIPE,
1049 encoding='utf-8',
1050 errors=errors)
1051 stdout, stderr = popen.communicate(input='')
1052 self.assertEqual(stdout, '[{}]'.format(expected))
1053
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001054 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +00001055 # Make sure we leak no resources
Victor Stinner937ee9e2018-06-26 02:11:06 +02001056 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +00001057 max_handles = 1026 # too much for most UNIX systems
1058 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +00001059 max_handles = 2050 # too much for (at least some) Windows setups
1060 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001061 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +00001062 try:
1063 for i in range(max_handles):
1064 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001065 tmpfile = os.path.join(tmpdir, support.TESTFN)
1066 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +00001067 except OSError as e:
1068 if e.errno != errno.EMFILE:
1069 raise
1070 break
1071 else:
1072 self.skipTest("failed to reach the file descriptor limit "
1073 "(tried %d)" % max_handles)
1074 # Close a couple of them (should be enough for a subprocess)
1075 for i in range(10):
1076 os.close(handles.pop())
1077 # Loop creating some subprocesses. If one of them leaks some fds,
1078 # the next loop iteration will fail by reaching the max fd limit.
1079 for i in range(15):
1080 p = subprocess.Popen([sys.executable, "-c",
1081 "import sys;"
1082 "sys.stdout.write(sys.stdin.read())"],
1083 stdin=subprocess.PIPE,
1084 stdout=subprocess.PIPE,
1085 stderr=subprocess.PIPE)
1086 data = p.communicate(b"lime")[0]
1087 self.assertEqual(data, b"lime")
1088 finally:
1089 for h in handles:
1090 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001091 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001092
1093 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001094 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
1095 '"a b c" d e')
1096 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
1097 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +00001098 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
1099 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001100 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
1101 'a\\\\\\b "de fg" h')
1102 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
1103 'a\\\\\\"b c d')
1104 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
1105 '"a\\\\b c" d e')
1106 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
1107 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001108 self.assertEqual(subprocess.list2cmdline(['ab', '']),
1109 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001110
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001111 def test_poll(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001112 p = subprocess.Popen([sys.executable, "-c",
Ross Lagerwalle7ad4192012-02-22 06:02:07 +02001113 "import os; os.read(0, 1)"],
1114 stdin=subprocess.PIPE)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001115 self.addCleanup(p.stdin.close)
1116 self.assertIsNone(p.poll())
1117 os.write(p.stdin.fileno(), b'A')
1118 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001119 # Subsequent invocations should just return the returncode
1120 self.assertEqual(p.poll(), 0)
1121
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001122 def test_wait(self):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001123 p = subprocess.Popen(ZERO_RETURN_CMD)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001124 self.assertEqual(p.wait(), 0)
1125 # Subsequent invocations should just return the returncode
1126 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +00001127
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001128 def test_wait_timeout(self):
1129 p = subprocess.Popen([sys.executable,
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001130 "-c", "import time; time.sleep(0.3)"])
Reid Kleckner2b228f02011-03-16 16:57:54 -04001131 with self.assertRaises(subprocess.TimeoutExpired) as c:
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001132 p.wait(timeout=0.0001)
1133 self.assertIn("0.0001", str(c.exception)) # For coverage of __str__.
Reid Klecknerda9ac722011-03-16 17:08:21 -04001134 # Some heavily loaded buildbots (sparc Debian 3.x) require this much
1135 # time to start.
1136 self.assertEqual(p.wait(timeout=3), 0)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001137
Peter Astrand738131d2004-11-30 21:04:45 +00001138 def test_invalid_bufsize(self):
1139 # an invalid type of the bufsize argument should raise
1140 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001141 with self.assertRaises(TypeError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001142 subprocess.Popen(ZERO_RETURN_CMD, "orange")
Peter Astrand738131d2004-11-30 21:04:45 +00001143
Guido van Rossum46a05a72007-06-07 21:56:45 +00001144 def test_bufsize_is_none(self):
1145 # bufsize=None should be the same as bufsize=0.
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001146 p = subprocess.Popen(ZERO_RETURN_CMD, None)
Guido van Rossum46a05a72007-06-07 21:56:45 +00001147 self.assertEqual(p.wait(), 0)
1148 # Again with keyword arg
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001149 p = subprocess.Popen(ZERO_RETURN_CMD, bufsize=None)
Guido van Rossum46a05a72007-06-07 21:56:45 +00001150 self.assertEqual(p.wait(), 0)
1151
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001152 def _test_bufsize_equal_one(self, line, expected, universal_newlines):
1153 # subprocess may deadlock with bufsize=1, see issue #21332
1154 with subprocess.Popen([sys.executable, "-c", "import sys;"
1155 "sys.stdout.write(sys.stdin.readline());"
1156 "sys.stdout.flush()"],
1157 stdin=subprocess.PIPE,
1158 stdout=subprocess.PIPE,
1159 stderr=subprocess.DEVNULL,
1160 bufsize=1,
1161 universal_newlines=universal_newlines) as p:
1162 p.stdin.write(line) # expect that it flushes the line in text mode
1163 os.close(p.stdin.fileno()) # close it without flushing the buffer
1164 read_line = p.stdout.readline()
Segev Finer4d385172017-08-18 16:18:13 +03001165 with support.SuppressCrashReport():
1166 try:
1167 p.stdin.close()
1168 except OSError:
1169 pass
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001170 p.stdin = None
1171 self.assertEqual(p.returncode, 0)
1172 self.assertEqual(read_line, expected)
1173
1174 def test_bufsize_equal_one_text_mode(self):
1175 # line is flushed in text mode with bufsize=1.
1176 # we should get the full line in return
1177 line = "line\n"
1178 self._test_bufsize_equal_one(line, line, universal_newlines=True)
1179
1180 def test_bufsize_equal_one_binary_mode(self):
1181 # line is not flushed in binary mode with bufsize=1.
1182 # we should get empty response
1183 line = b'line' + os.linesep.encode() # assume ascii-based locale
Alexey Izbysheva2670562018-10-20 03:22:31 +03001184 with self.assertWarnsRegex(RuntimeWarning, 'line buffering'):
1185 self._test_bufsize_equal_one(line, b'', universal_newlines=False)
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001186
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001187 def test_leaking_fds_on_error(self):
1188 # see bug #5179: Popen leaks file descriptors to PIPEs if
1189 # the child fails to execute; this will eventually exhaust
1190 # the maximum number of open fds. 1024 seems a very common
1191 # value for that limit, but Windows has 2048, so we loop
1192 # 1024 times (each call leaked two fds).
1193 for i in range(1024):
Victor Stinnerb31206a2018-01-25 19:06:05 +01001194 with self.assertRaises(NONEXISTING_ERRORS):
Victor Stinner9a83f652017-08-21 23:51:31 +02001195 subprocess.Popen(NONEXISTING_CMD,
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001196 stdout=subprocess.PIPE,
1197 stderr=subprocess.PIPE)
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001198
Victor Stinner9a83f652017-08-21 23:51:31 +02001199 def test_nonexisting_with_pipes(self):
1200 # bpo-30121: Popen with pipes must close properly pipes on error.
1201 # Previously, os.close() was called with a Windows handle which is not
1202 # a valid file descriptor.
1203 #
1204 # Run the test in a subprocess to control how the CRT reports errors
1205 # and to get stderr content.
1206 try:
1207 import msvcrt
1208 msvcrt.CrtSetReportMode
1209 except (AttributeError, ImportError):
1210 self.skipTest("need msvcrt.CrtSetReportMode")
1211
1212 code = textwrap.dedent(f"""
1213 import msvcrt
1214 import subprocess
1215
1216 cmd = {NONEXISTING_CMD!r}
1217
1218 for report_type in [msvcrt.CRT_WARN,
1219 msvcrt.CRT_ERROR,
1220 msvcrt.CRT_ASSERT]:
1221 msvcrt.CrtSetReportMode(report_type, msvcrt.CRTDBG_MODE_FILE)
1222 msvcrt.CrtSetReportFile(report_type, msvcrt.CRTDBG_FILE_STDERR)
1223
1224 try:
Zachary Ware55376462018-02-19 14:02:38 -06001225 subprocess.Popen(cmd,
Victor Stinner9a83f652017-08-21 23:51:31 +02001226 stdout=subprocess.PIPE,
1227 stderr=subprocess.PIPE)
1228 except OSError:
1229 pass
1230 """)
1231 cmd = [sys.executable, "-c", code]
1232 proc = subprocess.Popen(cmd,
1233 stderr=subprocess.PIPE,
1234 universal_newlines=True)
1235 with proc:
1236 stderr = proc.communicate()[1]
1237 self.assertEqual(stderr, "")
1238 self.assertEqual(proc.returncode, 0)
1239
Antoine Pitroua8392712013-08-30 23:38:13 +02001240 def test_double_close_on_error(self):
1241 # Issue #18851
1242 fds = []
1243 def open_fds():
1244 for i in range(20):
1245 fds.extend(os.pipe())
1246 time.sleep(0.001)
1247 t = threading.Thread(target=open_fds)
1248 t.start()
1249 try:
1250 with self.assertRaises(EnvironmentError):
Victor Stinner9a83f652017-08-21 23:51:31 +02001251 subprocess.Popen(NONEXISTING_CMD,
Antoine Pitroua8392712013-08-30 23:38:13 +02001252 stdin=subprocess.PIPE,
1253 stdout=subprocess.PIPE,
1254 stderr=subprocess.PIPE)
1255 finally:
1256 t.join()
1257 exc = None
1258 for fd in fds:
1259 # If a double close occurred, some of those fds will
1260 # already have been closed by mistake, and os.close()
1261 # here will raise.
1262 try:
1263 os.close(fd)
1264 except OSError as e:
1265 exc = e
1266 if exc is not None:
1267 raise exc
1268
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001269 def test_threadsafe_wait(self):
1270 """Issue21291: Popen.wait() needs to be threadsafe for returncode."""
1271 proc = subprocess.Popen([sys.executable, '-c',
1272 'import time; time.sleep(12)'])
1273 self.assertEqual(proc.returncode, None)
1274 results = []
1275
1276 def kill_proc_timer_thread():
1277 results.append(('thread-start-poll-result', proc.poll()))
1278 # terminate it from the thread and wait for the result.
1279 proc.kill()
1280 proc.wait()
1281 results.append(('thread-after-kill-and-wait', proc.returncode))
1282 # this wait should be a no-op given the above.
1283 proc.wait()
1284 results.append(('thread-after-second-wait', proc.returncode))
1285
1286 # This is a timing sensitive test, the failure mode is
1287 # triggered when both the main thread and this thread are in
1288 # the wait() call at once. The delay here is to allow the
1289 # main thread to most likely be blocked in its wait() call.
1290 t = threading.Timer(0.2, kill_proc_timer_thread)
1291 t.start()
1292
Victor Stinner937ee9e2018-06-26 02:11:06 +02001293 if mswindows:
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001294 expected_errorcode = 1
1295 else:
1296 # Should be -9 because of the proc.kill() from the thread.
1297 expected_errorcode = -9
1298
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001299 # Wait for the process to finish; the thread should kill it
1300 # long before it finishes on its own. Supplying a timeout
1301 # triggers a different code path for better coverage.
1302 proc.wait(timeout=20)
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001303 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001304 msg="unexpected result in wait from main thread")
1305
1306 # This should be a no-op with no change in returncode.
1307 proc.wait()
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001308 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001309 msg="unexpected result in second main wait.")
1310
1311 t.join()
1312 # Ensure that all of the thread results are as expected.
1313 # When a race condition occurs in wait(), the returncode could
1314 # be set by the wrong thread that doesn't actually have it
1315 # leading to an incorrect value.
1316 self.assertEqual([('thread-start-poll-result', None),
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001317 ('thread-after-kill-and-wait', expected_errorcode),
1318 ('thread-after-second-wait', expected_errorcode)],
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001319 results)
1320
Victor Stinnerb3693582010-05-21 20:13:12 +00001321 def test_issue8780(self):
1322 # Ensure that stdout is inherited from the parent
1323 # if stdout=PIPE is not used
1324 code = ';'.join((
1325 'import subprocess, sys',
1326 'retcode = subprocess.call('
1327 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
1328 'assert retcode == 0'))
1329 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001330 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +00001331
Tim Goldenaf5ac392010-08-06 13:03:56 +00001332 def test_handles_closed_on_exception(self):
1333 # If CreateProcess exits with an error, ensure the
1334 # duplicate output handles are released
Berker Peksag16a1f282015-09-28 13:33:14 +03001335 ifhandle, ifname = tempfile.mkstemp()
1336 ofhandle, ofname = tempfile.mkstemp()
1337 efhandle, efname = tempfile.mkstemp()
Tim Goldenaf5ac392010-08-06 13:03:56 +00001338 try:
1339 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
1340 stderr=efhandle)
1341 except OSError:
1342 os.close(ifhandle)
1343 os.remove(ifname)
1344 os.close(ofhandle)
1345 os.remove(ofname)
1346 os.close(efhandle)
1347 os.remove(efname)
1348 self.assertFalse(os.path.exists(ifname))
1349 self.assertFalse(os.path.exists(ofname))
1350 self.assertFalse(os.path.exists(efname))
1351
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001352 def test_communicate_epipe(self):
1353 # Issue 10963: communicate() should hide EPIPE
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001354 p = subprocess.Popen(ZERO_RETURN_CMD,
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001355 stdin=subprocess.PIPE,
1356 stdout=subprocess.PIPE,
1357 stderr=subprocess.PIPE)
1358 self.addCleanup(p.stdout.close)
1359 self.addCleanup(p.stderr.close)
1360 self.addCleanup(p.stdin.close)
1361 p.communicate(b"x" * 2**20)
1362
Andrey Doroschenko645005e2019-11-17 17:08:31 +03001363 def test_repr(self):
1364 # Run a command that waits for user input, to check the repr() of
1365 # a Proc object while and after the sub-process runs.
1366 code = 'import sys; input(); sys.exit(57)'
1367 cmd = [sys.executable, '-c', code]
1368 result = "<Popen: returncode: {}"
1369
1370 with subprocess.Popen(
1371 cmd, stdin=subprocess.PIPE, universal_newlines=True) as proc:
1372 self.assertIsNone(proc.returncode)
1373 self.assertTrue(
1374 repr(proc).startswith(result.format(proc.returncode)) and
1375 repr(proc).endswith('>')
1376 )
1377
1378 proc.communicate(input='exit...\n')
1379 proc.wait()
1380
1381 self.assertIsNotNone(proc.returncode)
1382 self.assertTrue(
1383 repr(proc).startswith(result.format(proc.returncode)) and
1384 repr(proc).endswith('>')
1385 )
1386
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001387 def test_communicate_epipe_only_stdin(self):
1388 # Issue 10963: communicate() should hide EPIPE
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001389 p = subprocess.Popen(ZERO_RETURN_CMD,
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001390 stdin=subprocess.PIPE)
1391 self.addCleanup(p.stdin.close)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001392 p.wait()
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001393 p.communicate(b"x" * 2**20)
1394
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001395 @unittest.skipUnless(hasattr(signal, 'SIGUSR1'),
1396 "Requires signal.SIGUSR1")
1397 @unittest.skipUnless(hasattr(os, 'kill'),
1398 "Requires os.kill")
1399 @unittest.skipUnless(hasattr(os, 'getppid'),
1400 "Requires os.getppid")
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001401 def test_communicate_eintr(self):
1402 # Issue #12493: communicate() should handle EINTR
1403 def handler(signum, frame):
1404 pass
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001405 old_handler = signal.signal(signal.SIGUSR1, handler)
1406 self.addCleanup(signal.signal, signal.SIGUSR1, old_handler)
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001407
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001408 args = [sys.executable, "-c",
1409 'import os, signal;'
1410 'os.kill(os.getppid(), signal.SIGUSR1)']
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001411 for stream in ('stdout', 'stderr'):
1412 kw = {stream: subprocess.PIPE}
1413 with subprocess.Popen(args, **kw) as process:
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001414 # communicate() will be interrupted by SIGUSR1
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001415 process.communicate()
1416
Tim Peterse718f612004-10-12 21:51:32 +00001417
Gregory P. Smith3d8e7762012-11-10 22:32:22 -08001418 # This test is Linux-ish specific for simplicity to at least have
1419 # some coverage. It is not a platform specific bug.
1420 @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
1421 "Linux specific")
1422 def test_failed_child_execute_fd_leak(self):
1423 """Test for the fork() failure fd leak reported in issue16327."""
1424 fd_directory = '/proc/%d/fd' % os.getpid()
1425 fds_before_popen = os.listdir(fd_directory)
1426 with self.assertRaises(PopenTestException):
1427 PopenExecuteChildRaises(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001428 ZERO_RETURN_CMD, stdin=subprocess.PIPE,
Gregory P. Smith3d8e7762012-11-10 22:32:22 -08001429 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1430
1431 # NOTE: This test doesn't verify that the real _execute_child
1432 # does not close the file descriptors itself on the way out
1433 # during an exception. Code inspection has confirmed that.
1434
1435 fds_after_exception = os.listdir(fd_directory)
1436 self.assertEqual(fds_before_popen, fds_after_exception)
1437
Victor Stinner937ee9e2018-06-26 02:11:06 +02001438 @unittest.skipIf(mswindows, "behavior currently not supported on Windows")
Gregory P. Smith8621bb52017-08-24 14:58:25 -07001439 def test_file_not_found_includes_filename(self):
1440 with self.assertRaises(FileNotFoundError) as c:
1441 subprocess.call(['/opt/nonexistent_binary', 'with', 'some', 'args'])
1442 self.assertEqual(c.exception.filename, '/opt/nonexistent_binary')
1443
Victor Stinner937ee9e2018-06-26 02:11:06 +02001444 @unittest.skipIf(mswindows, "behavior currently not supported on Windows")
Gregory P. Smith8621bb52017-08-24 14:58:25 -07001445 def test_file_not_found_with_bad_cwd(self):
1446 with self.assertRaises(FileNotFoundError) as c:
1447 subprocess.Popen(['exit', '0'], cwd='/some/nonexistent/directory')
1448 self.assertEqual(c.exception.filename, '/some/nonexistent/directory')
1449
Gregory P. Smith6e730002015-04-14 16:14:25 -07001450
1451class RunFuncTestCase(BaseTestCase):
1452 def run_python(self, code, **kwargs):
1453 """Run Python code in a subprocess using subprocess.run"""
1454 argv = [sys.executable, "-c", code]
1455 return subprocess.run(argv, **kwargs)
1456
1457 def test_returncode(self):
1458 # call() function with sequence argument
1459 cp = self.run_python("import sys; sys.exit(47)")
1460 self.assertEqual(cp.returncode, 47)
1461 with self.assertRaises(subprocess.CalledProcessError):
1462 cp.check_returncode()
1463
1464 def test_check(self):
1465 with self.assertRaises(subprocess.CalledProcessError) as c:
1466 self.run_python("import sys; sys.exit(47)", check=True)
1467 self.assertEqual(c.exception.returncode, 47)
1468
1469 def test_check_zero(self):
1470 # check_returncode shouldn't raise when returncode is zero
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001471 cp = subprocess.run(ZERO_RETURN_CMD, check=True)
Gregory P. Smith6e730002015-04-14 16:14:25 -07001472 self.assertEqual(cp.returncode, 0)
1473
1474 def test_timeout(self):
1475 # run() function with timeout argument; we want to test that the child
1476 # process gets killed when the timeout expires. If the child isn't
1477 # killed, this call will deadlock since subprocess.run waits for the
1478 # child.
1479 with self.assertRaises(subprocess.TimeoutExpired):
1480 self.run_python("while True: pass", timeout=0.0001)
1481
1482 def test_capture_stdout(self):
1483 # capture stdout with zero return code
1484 cp = self.run_python("print('BDFL')", stdout=subprocess.PIPE)
1485 self.assertIn(b'BDFL', cp.stdout)
1486
1487 def test_capture_stderr(self):
1488 cp = self.run_python("import sys; sys.stderr.write('BDFL')",
1489 stderr=subprocess.PIPE)
1490 self.assertIn(b'BDFL', cp.stderr)
1491
1492 def test_check_output_stdin_arg(self):
1493 # run() can be called with stdin set to a file
1494 tf = tempfile.TemporaryFile()
1495 self.addCleanup(tf.close)
1496 tf.write(b'pear')
1497 tf.seek(0)
1498 cp = self.run_python(
1499 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1500 stdin=tf, stdout=subprocess.PIPE)
1501 self.assertIn(b'PEAR', cp.stdout)
1502
1503 def test_check_output_input_arg(self):
1504 # check_output() can be called with input set to a string
1505 cp = self.run_python(
1506 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1507 input=b'pear', stdout=subprocess.PIPE)
1508 self.assertIn(b'PEAR', cp.stdout)
1509
1510 def test_check_output_stdin_with_input_arg(self):
1511 # run() refuses to accept 'stdin' with 'input'
1512 tf = tempfile.TemporaryFile()
1513 self.addCleanup(tf.close)
1514 tf.write(b'pear')
1515 tf.seek(0)
1516 with self.assertRaises(ValueError,
1517 msg="Expected ValueError when stdin and input args supplied.") as c:
1518 output = self.run_python("print('will not be run')",
1519 stdin=tf, input=b'hare')
1520 self.assertIn('stdin', c.exception.args[0])
1521 self.assertIn('input', c.exception.args[0])
1522
1523 def test_check_output_timeout(self):
1524 with self.assertRaises(subprocess.TimeoutExpired) as c:
1525 cp = self.run_python((
1526 "import sys, time\n"
1527 "sys.stdout.write('BDFL')\n"
1528 "sys.stdout.flush()\n"
1529 "time.sleep(3600)"),
1530 # Some heavily loaded buildbots (sparc Debian 3.x) require
1531 # this much time to start and print.
1532 timeout=3, stdout=subprocess.PIPE)
1533 self.assertEqual(c.exception.output, b'BDFL')
1534 # output is aliased to stdout
1535 self.assertEqual(c.exception.stdout, b'BDFL')
1536
1537 def test_run_kwargs(self):
1538 newenv = os.environ.copy()
1539 newenv["FRUIT"] = "banana"
1540 cp = self.run_python(('import sys, os;'
1541 'sys.exit(33 if os.getenv("FRUIT")=="banana" else 31)'),
1542 env=newenv)
1543 self.assertEqual(cp.returncode, 33)
1544
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +03001545 def test_run_with_pathlike_path(self):
1546 # bpo-31961: test run(pathlike_object)
1547 # the name of a command that can be run without
Min ho Kimc4cacc82019-07-31 08:16:13 +10001548 # any arguments that exit fast
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +03001549 prog = 'tree.com' if mswindows else 'ls'
1550 path = shutil.which(prog)
1551 if path is None:
1552 self.skipTest(f'{prog} required for this test')
1553 path = FakePath(path)
1554 res = subprocess.run(path, stdout=subprocess.DEVNULL)
1555 self.assertEqual(res.returncode, 0)
1556 with self.assertRaises(TypeError):
1557 subprocess.run(path, stdout=subprocess.DEVNULL, shell=True)
1558
1559 def test_run_with_bytes_path_and_arguments(self):
1560 # bpo-31961: test run([bytes_object, b'additional arguments'])
1561 path = os.fsencode(sys.executable)
1562 args = [path, '-c', b'import sys; sys.exit(57)']
1563 res = subprocess.run(args)
1564 self.assertEqual(res.returncode, 57)
1565
1566 def test_run_with_pathlike_path_and_arguments(self):
1567 # bpo-31961: test run([pathlike_object, 'additional arguments'])
1568 path = FakePath(sys.executable)
1569 args = [path, '-c', 'import sys; sys.exit(57)']
1570 res = subprocess.run(args)
1571 self.assertEqual(res.returncode, 57)
1572
Bo Baylesce0f33d2018-01-30 00:40:39 -06001573 def test_capture_output(self):
1574 cp = self.run_python(("import sys;"
1575 "sys.stdout.write('BDFL'); "
1576 "sys.stderr.write('FLUFL')"),
1577 capture_output=True)
1578 self.assertIn(b'BDFL', cp.stdout)
1579 self.assertIn(b'FLUFL', cp.stderr)
1580
1581 def test_stdout_with_capture_output_arg(self):
1582 # run() refuses to accept 'stdout' with 'capture_output'
1583 tf = tempfile.TemporaryFile()
1584 self.addCleanup(tf.close)
1585 with self.assertRaises(ValueError,
1586 msg=("Expected ValueError when stdout and capture_output "
1587 "args supplied.")) as c:
1588 output = self.run_python("print('will not be run')",
1589 capture_output=True, stdout=tf)
1590 self.assertIn('stdout', c.exception.args[0])
1591 self.assertIn('capture_output', c.exception.args[0])
1592
1593 def test_stderr_with_capture_output_arg(self):
1594 # run() refuses to accept 'stderr' with 'capture_output'
1595 tf = tempfile.TemporaryFile()
1596 self.addCleanup(tf.close)
1597 with self.assertRaises(ValueError,
1598 msg=("Expected ValueError when stderr and capture_output "
1599 "args supplied.")) as c:
1600 output = self.run_python("print('will not be run')",
1601 capture_output=True, stderr=tf)
1602 self.assertIn('stderr', c.exception.args[0])
1603 self.assertIn('capture_output', c.exception.args[0])
1604
Gregory P. Smith580d2782019-09-11 04:23:05 -05001605 # This test _might_ wind up a bit fragile on loaded build+test machines
1606 # as it depends on the timing with wide enough margins for normal situations
1607 # but does assert that it happened "soon enough" to believe the right thing
1608 # happened.
1609 @unittest.skipIf(mswindows, "requires posix like 'sleep' shell command")
1610 def test_run_with_shell_timeout_and_capture_output(self):
1611 """Output capturing after a timeout mustn't hang forever on open filehandles."""
1612 before_secs = time.monotonic()
1613 try:
1614 subprocess.run('sleep 3', shell=True, timeout=0.1,
1615 capture_output=True) # New session unspecified.
1616 except subprocess.TimeoutExpired as exc:
1617 after_secs = time.monotonic()
1618 stacks = traceback.format_exc() # assertRaises doesn't give this.
1619 else:
1620 self.fail("TimeoutExpired not raised.")
1621 self.assertLess(after_secs - before_secs, 1.5,
1622 msg="TimeoutExpired was delayed! Bad traceback:\n```\n"
1623 f"{stacks}```")
1624
Gregory P. Smith6e730002015-04-14 16:14:25 -07001625
Gregory P. Smith693aa802019-09-13 14:43:35 +01001626def _get_test_grp_name():
Victor Stinnerfaca8552019-09-25 15:52:49 +02001627 for name_group in ('staff', 'nogroup', 'grp', 'nobody', 'nfsnobody'):
Gregory P. Smith693aa802019-09-13 14:43:35 +01001628 if grp:
1629 try:
1630 grp.getgrnam(name_group)
1631 except KeyError:
1632 continue
1633 return name_group
1634 else:
1635 raise unittest.SkipTest('No identified group name to use for this test on this platform.')
1636
1637
Victor Stinner937ee9e2018-06-26 02:11:06 +02001638@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001639class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001640
Gregory P. Smith5591b022012-10-10 03:34:47 -07001641 def setUp(self):
1642 super().setUp()
1643 self._nonexistent_dir = "/_this/pa.th/does/not/exist"
1644
1645 def _get_chdir_exception(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001646 try:
Gregory P. Smith5591b022012-10-10 03:34:47 -07001647 os.chdir(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001648 except OSError as e:
1649 # This avoids hard coding the errno value or the OS perror()
1650 # string and instead capture the exception that we want to see
1651 # below for comparison.
1652 desired_exception = e
1653 else:
Martin Pantereb995702016-07-28 01:11:04 +00001654 self.fail("chdir to nonexistent directory %s succeeded." %
Gregory P. Smith5591b022012-10-10 03:34:47 -07001655 self._nonexistent_dir)
1656 return desired_exception
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001657
Gregory P. Smith5591b022012-10-10 03:34:47 -07001658 def test_exception_cwd(self):
1659 """Test error in the child raised in the parent for a bad cwd."""
1660 desired_exception = self._get_chdir_exception()
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001661 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001662 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smith5591b022012-10-10 03:34:47 -07001663 cwd=self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001664 except OSError as e:
1665 # Test that the child process chdir failure actually makes
1666 # it up to the parent process as the correct exception.
1667 self.assertEqual(desired_exception.errno, e.errno)
1668 self.assertEqual(desired_exception.strerror, e.strerror)
Zackery Spytz73870bf2018-09-11 09:54:07 -06001669 self.assertEqual(desired_exception.filename, e.filename)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001670 else:
1671 self.fail("Expected OSError: %s" % desired_exception)
1672
Gregory P. Smith5591b022012-10-10 03:34:47 -07001673 def test_exception_bad_executable(self):
1674 """Test error in the child raised in the parent for a bad executable."""
1675 desired_exception = self._get_chdir_exception()
1676 try:
1677 p = subprocess.Popen([sys.executable, "-c", ""],
1678 executable=self._nonexistent_dir)
1679 except OSError as e:
1680 # Test that the child process exec failure actually makes
1681 # it up to the parent process as the correct exception.
1682 self.assertEqual(desired_exception.errno, e.errno)
1683 self.assertEqual(desired_exception.strerror, e.strerror)
Zackery Spytz73870bf2018-09-11 09:54:07 -06001684 self.assertEqual(desired_exception.filename, e.filename)
Gregory P. Smith5591b022012-10-10 03:34:47 -07001685 else:
1686 self.fail("Expected OSError: %s" % desired_exception)
1687
1688 def test_exception_bad_args_0(self):
1689 """Test error in the child raised in the parent for a bad args[0]."""
1690 desired_exception = self._get_chdir_exception()
1691 try:
1692 p = subprocess.Popen([self._nonexistent_dir, "-c", ""])
1693 except OSError as e:
1694 # Test that the child process exec failure actually makes
1695 # it up to the parent process as the correct exception.
1696 self.assertEqual(desired_exception.errno, e.errno)
1697 self.assertEqual(desired_exception.strerror, e.strerror)
Zackery Spytz73870bf2018-09-11 09:54:07 -06001698 self.assertEqual(desired_exception.filename, e.filename)
Gregory P. Smith5591b022012-10-10 03:34:47 -07001699 else:
1700 self.fail("Expected OSError: %s" % desired_exception)
1701
Ammar Askar3fc499b2017-09-06 02:41:30 -04001702 # We mock the __del__ method for Popen in the next two tests
1703 # because it does cleanup based on the pid returned by fork_exec
1704 # along with issuing a resource warning if it still exists. Since
1705 # we don't actually spawn a process in these tests we can forego
1706 # the destructor. An alternative would be to set _child_created to
1707 # False before the destructor is called but there is no easy way
1708 # to do that
1709 class PopenNoDestructor(subprocess.Popen):
1710 def __del__(self):
1711 pass
1712
1713 @mock.patch("subprocess._posixsubprocess.fork_exec")
1714 def test_exception_errpipe_normal(self, fork_exec):
1715 """Test error passing done through errpipe_write in the good case"""
1716 def proper_error(*args):
1717 errpipe_write = args[13]
1718 # Write the hex for the error code EISDIR: 'is a directory'
1719 err_code = '{:x}'.format(errno.EISDIR).encode()
1720 os.write(errpipe_write, b"OSError:" + err_code + b":")
1721 return 0
1722
1723 fork_exec.side_effect = proper_error
1724
Victor Stinner11045c92017-10-05 06:32:53 -07001725 with mock.patch("subprocess.os.waitpid",
1726 side_effect=ChildProcessError):
1727 with self.assertRaises(IsADirectoryError):
1728 self.PopenNoDestructor(["non_existent_command"])
Ammar Askar3fc499b2017-09-06 02:41:30 -04001729
1730 @mock.patch("subprocess._posixsubprocess.fork_exec")
1731 def test_exception_errpipe_bad_data(self, fork_exec):
1732 """Test error passing done through errpipe_write where its not
1733 in the expected format"""
1734 error_data = b"\xFF\x00\xDE\xAD"
1735 def bad_error(*args):
1736 errpipe_write = args[13]
1737 # Anything can be in the pipe, no assumptions should
1738 # be made about its encoding, so we'll write some
1739 # arbitrary hex bytes to test it out
1740 os.write(errpipe_write, error_data)
1741 return 0
1742
1743 fork_exec.side_effect = bad_error
1744
Victor Stinner11045c92017-10-05 06:32:53 -07001745 with mock.patch("subprocess.os.waitpid",
1746 side_effect=ChildProcessError):
1747 with self.assertRaises(subprocess.SubprocessError) as e:
1748 self.PopenNoDestructor(["non_existent_command"])
Ammar Askar3fc499b2017-09-06 02:41:30 -04001749
1750 self.assertIn(repr(error_data), str(e.exception))
1751
Gregory P. Smith5f3d04f2018-06-05 12:00:57 -07001752 @unittest.skipIf(not os.path.exists('/proc/self/status'),
1753 "need /proc/self/status")
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001754 def test_restore_signals(self):
Gregory P. Smith5f3d04f2018-06-05 12:00:57 -07001755 # Blindly assume that cat exists on systems with /proc/self/status...
1756 default_proc_status = subprocess.check_output(
1757 ['cat', '/proc/self/status'],
1758 restore_signals=False)
1759 for line in default_proc_status.splitlines():
1760 if line.startswith(b'SigIgn'):
1761 default_sig_ign_mask = line
1762 break
1763 else:
1764 self.skipTest("SigIgn not found in /proc/self/status.")
1765 restored_proc_status = subprocess.check_output(
1766 ['cat', '/proc/self/status'],
1767 restore_signals=True)
1768 for line in restored_proc_status.splitlines():
1769 if line.startswith(b'SigIgn'):
1770 restored_sig_ign_mask = line
1771 break
1772 self.assertNotEqual(default_sig_ign_mask, restored_sig_ign_mask,
1773 msg="restore_signals=True should've unblocked "
1774 "SIGPIPE and friends.")
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001775
1776 def test_start_new_session(self):
1777 # For code coverage of calling setsid(). We don't care if we get an
1778 # EPERM error from it depending on the test execution environment, that
1779 # still indicates that it was called.
1780 try:
1781 output = subprocess.check_output(
Victor Stinner58840432019-06-14 19:31:43 +02001782 [sys.executable, "-c", "import os; print(os.getsid(0))"],
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001783 start_new_session=True)
1784 except OSError as e:
1785 if e.errno != errno.EPERM:
1786 raise
1787 else:
Victor Stinner58840432019-06-14 19:31:43 +02001788 parent_sid = os.getsid(0)
1789 child_sid = int(output)
1790 self.assertNotEqual(parent_sid, child_sid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001791
Patrick McLean2b2ead72019-09-12 10:15:44 -07001792 @unittest.skipUnless(hasattr(os, 'setreuid'), 'no setreuid on platform')
1793 def test_user(self):
1794 # For code coverage of the user parameter. We don't care if we get an
1795 # EPERM error from it depending on the test execution environment, that
1796 # still indicates that it was called.
1797
1798 uid = os.geteuid()
1799 test_users = [65534 if uid != 65534 else 65533, uid]
1800 name_uid = "nobody" if sys.platform != 'darwin' else "unknown"
1801
1802 if pwd is not None:
1803 test_users.append(name_uid)
1804
1805 for user in test_users:
Victor Stinnerfaca8552019-09-25 15:52:49 +02001806 # posix_spawn() may be used with close_fds=False
1807 for close_fds in (False, True):
1808 with self.subTest(user=user, close_fds=close_fds):
1809 try:
1810 output = subprocess.check_output(
1811 [sys.executable, "-c",
1812 "import os; print(os.getuid())"],
1813 user=user,
1814 close_fds=close_fds)
1815 except PermissionError: # (EACCES, EPERM)
1816 pass
1817 except OSError as e:
1818 if e.errno not in (errno.EACCES, errno.EPERM):
1819 raise
Patrick McLean2b2ead72019-09-12 10:15:44 -07001820 else:
Victor Stinnerfaca8552019-09-25 15:52:49 +02001821 if isinstance(user, str):
1822 user_uid = pwd.getpwnam(user).pw_uid
1823 else:
1824 user_uid = user
1825 child_user = int(output)
1826 self.assertEqual(child_user, user_uid)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001827
1828 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001829 subprocess.check_call(ZERO_RETURN_CMD, user=-1)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001830
1831 if pwd is None:
1832 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001833 subprocess.check_call(ZERO_RETURN_CMD, user=name_uid)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001834
1835 @unittest.skipIf(hasattr(os, 'setreuid'), 'setreuid() available on platform')
1836 def test_user_error(self):
1837 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001838 subprocess.check_call(ZERO_RETURN_CMD, user=65535)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001839
1840 @unittest.skipUnless(hasattr(os, 'setregid'), 'no setregid() on platform')
1841 def test_group(self):
1842 gid = os.getegid()
1843 group_list = [65534 if gid != 65534 else 65533]
Gregory P. Smith693aa802019-09-13 14:43:35 +01001844 name_group = _get_test_grp_name()
Patrick McLean2b2ead72019-09-12 10:15:44 -07001845
1846 if grp is not None:
1847 group_list.append(name_group)
1848
1849 for group in group_list + [gid]:
Victor Stinnerfaca8552019-09-25 15:52:49 +02001850 # posix_spawn() may be used with close_fds=False
1851 for close_fds in (False, True):
1852 with self.subTest(group=group, close_fds=close_fds):
1853 try:
1854 output = subprocess.check_output(
1855 [sys.executable, "-c",
1856 "import os; print(os.getgid())"],
1857 group=group,
1858 close_fds=close_fds)
1859 except PermissionError: # (EACCES, EPERM)
1860 pass
Patrick McLean2b2ead72019-09-12 10:15:44 -07001861 else:
Victor Stinnerfaca8552019-09-25 15:52:49 +02001862 if isinstance(group, str):
1863 group_gid = grp.getgrnam(group).gr_gid
1864 else:
1865 group_gid = group
Patrick McLean2b2ead72019-09-12 10:15:44 -07001866
Victor Stinnerfaca8552019-09-25 15:52:49 +02001867 child_group = int(output)
1868 self.assertEqual(child_group, group_gid)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001869
1870 # make sure we bomb on negative values
1871 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001872 subprocess.check_call(ZERO_RETURN_CMD, group=-1)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001873
1874 if grp is None:
1875 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001876 subprocess.check_call(ZERO_RETURN_CMD, group=name_group)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001877
1878 @unittest.skipIf(hasattr(os, 'setregid'), 'setregid() available on platform')
1879 def test_group_error(self):
1880 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001881 subprocess.check_call(ZERO_RETURN_CMD, group=65535)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001882
1883 @unittest.skipUnless(hasattr(os, 'setgroups'), 'no setgroups() on platform')
1884 def test_extra_groups(self):
1885 gid = os.getegid()
1886 group_list = [65534 if gid != 65534 else 65533]
Gregory P. Smith693aa802019-09-13 14:43:35 +01001887 name_group = _get_test_grp_name()
Patrick McLean2b2ead72019-09-12 10:15:44 -07001888 perm_error = False
1889
1890 if grp is not None:
1891 group_list.append(name_group)
1892
1893 try:
1894 output = subprocess.check_output(
1895 [sys.executable, "-c",
1896 "import os, sys, json; json.dump(os.getgroups(), sys.stdout)"],
1897 extra_groups=group_list)
1898 except OSError as ex:
1899 if ex.errno != errno.EPERM:
1900 raise
1901 perm_error = True
1902
1903 else:
1904 parent_groups = os.getgroups()
1905 child_groups = json.loads(output)
1906
1907 if grp is not None:
1908 desired_gids = [grp.getgrnam(g).gr_gid if isinstance(g, str) else g
1909 for g in group_list]
1910 else:
1911 desired_gids = group_list
1912
1913 if perm_error:
1914 self.assertEqual(set(child_groups), set(parent_groups))
1915 else:
1916 self.assertEqual(set(desired_gids), set(child_groups))
1917
1918 # make sure we bomb on negative values
1919 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001920 subprocess.check_call(ZERO_RETURN_CMD, extra_groups=[-1])
Patrick McLean2b2ead72019-09-12 10:15:44 -07001921
1922 if grp is None:
1923 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001924 subprocess.check_call(ZERO_RETURN_CMD,
Patrick McLean2b2ead72019-09-12 10:15:44 -07001925 extra_groups=[name_group])
1926
1927 @unittest.skipIf(hasattr(os, 'setgroups'), 'setgroups() available on platform')
1928 def test_extra_groups_error(self):
1929 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001930 subprocess.check_call(ZERO_RETURN_CMD, extra_groups=[])
Patrick McLean2b2ead72019-09-12 10:15:44 -07001931
Gregory P. Smithf3751ef2019-10-12 13:24:56 -07001932 @unittest.skipIf(mswindows or not hasattr(os, 'umask'),
1933 'POSIX umask() is not available.')
1934 def test_umask(self):
1935 tmpdir = None
1936 try:
1937 tmpdir = tempfile.mkdtemp()
1938 name = os.path.join(tmpdir, "beans")
1939 # We set an unusual umask in the child so as a unique mode
1940 # for us to test the child's touched file for.
1941 subprocess.check_call(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001942 [sys.executable, "-c", f"open({name!r}, 'w').close()"],
Gregory P. Smithf3751ef2019-10-12 13:24:56 -07001943 umask=0o053)
1944 # Ignore execute permissions entirely in our test,
1945 # filesystems could be mounted to ignore or force that.
1946 st_mode = os.stat(name).st_mode & 0o666
1947 expected_mode = 0o624
1948 self.assertEqual(expected_mode, st_mode,
1949 msg=f'{oct(expected_mode)} != {oct(st_mode)}')
1950 finally:
1951 if tmpdir is not None:
1952 shutil.rmtree(tmpdir)
1953
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001954 def test_run_abort(self):
1955 # returncode handles signal termination
Antoine Pitrou77e904e2013-10-08 23:04:32 +02001956 with support.SuppressCrashReport():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001957 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001958 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001959 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001960 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001961
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00001962 def test_CalledProcessError_str_signal(self):
1963 err = subprocess.CalledProcessError(-int(signal.SIGABRT), "fake cmd")
1964 error_string = str(err)
1965 # We're relying on the repr() of the signal.Signals intenum to provide
1966 # the word signal, the signal name and the numeric value.
1967 self.assertIn("signal", error_string.lower())
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)b4149062016-06-03 06:19:35 +00001968 # We're not being specific about the signal name as some signals have
1969 # multiple names and which name is revealed can vary.
1970 self.assertIn("SIG", error_string)
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00001971 self.assertIn(str(signal.SIGABRT), error_string)
1972
1973 def test_CalledProcessError_str_unknown_signal(self):
1974 err = subprocess.CalledProcessError(-9876543, "fake cmd")
1975 error_string = str(err)
1976 self.assertIn("unknown signal 9876543.", error_string)
1977
1978 def test_CalledProcessError_str_non_zero(self):
1979 err = subprocess.CalledProcessError(2, "fake cmd")
1980 error_string = str(err)
1981 self.assertIn("non-zero exit status 2.", error_string)
1982
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001983 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001984 # DISCLAIMER: Setting environment variables is *not* a good use
1985 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001986 p = subprocess.Popen([sys.executable, "-c",
1987 'import sys,os;'
1988 'sys.stdout.write(os.getenv("FRUIT"))'],
1989 stdout=subprocess.PIPE,
1990 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Victor Stinner7438c612016-05-20 12:43:15 +02001991 with p:
1992 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001993
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001994 def test_preexec_exception(self):
1995 def raise_it():
1996 raise ValueError("What if two swallows carried a coconut?")
1997 try:
1998 p = subprocess.Popen([sys.executable, "-c", ""],
1999 preexec_fn=raise_it)
Gregory P. Smith8d07c262012-11-10 23:53:47 -08002000 except subprocess.SubprocessError as e:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002001 self.assertTrue(
2002 subprocess._posixsubprocess,
2003 "Expected a ValueError from the preexec_fn")
2004 except ValueError as e:
2005 self.assertIn("coconut", e.args[0])
2006 else:
2007 self.fail("Exception raised by preexec_fn did not make it "
2008 "to the parent process.")
2009
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002010 class _TestExecuteChildPopen(subprocess.Popen):
2011 """Used to test behavior at the end of _execute_child."""
2012 def __init__(self, testcase, *args, **kwargs):
2013 self._testcase = testcase
2014 subprocess.Popen.__init__(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08002015
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002016 def _execute_child(self, *args, **kwargs):
Gregory P. Smith12489d92012-11-11 01:37:02 -08002017 try:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002018 subprocess.Popen._execute_child(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08002019 finally:
2020 # Open a bunch of file descriptors and verify that
2021 # none of them are the same as the ones the Popen
2022 # instance is using for stdin/stdout/stderr.
2023 devzero_fds = [os.open("/dev/zero", os.O_RDONLY)
2024 for _ in range(8)]
2025 try:
2026 for fd in devzero_fds:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002027 self._testcase.assertNotIn(
2028 fd, (self.stdin.fileno(), self.stdout.fileno(),
2029 self.stderr.fileno()),
Gregory P. Smith12489d92012-11-11 01:37:02 -08002030 msg="At least one fd was closed early.")
2031 finally:
Richard Oudkerk0e547b62013-06-10 16:29:19 +01002032 for fd in devzero_fds:
2033 os.close(fd)
Gregory P. Smith12489d92012-11-11 01:37:02 -08002034
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002035 @unittest.skipIf(not os.path.exists("/dev/zero"), "/dev/zero required.")
2036 def test_preexec_errpipe_does_not_double_close_pipes(self):
2037 """Issue16140: Don't double close pipes on preexec error."""
2038
2039 def raise_it():
Gregory P. Smith65ee6ec2012-11-11 10:12:40 -08002040 raise subprocess.SubprocessError(
2041 "force the _execute_child() errpipe_data path.")
Gregory P. Smith12489d92012-11-11 01:37:02 -08002042
Gregory P. Smithc2c4cb62012-11-11 01:41:49 -08002043 with self.assertRaises(subprocess.SubprocessError):
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002044 self._TestExecuteChildPopen(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002045 self, ZERO_RETURN_CMD,
Gregory P. Smith12489d92012-11-11 01:37:02 -08002046 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2047 stderr=subprocess.PIPE, preexec_fn=raise_it)
2048
Gregory P. Smith32ec9da2010-03-19 16:53:08 +00002049 def test_preexec_gc_module_failure(self):
2050 # This tests the code that disables garbage collection if the child
2051 # process will execute any Python.
2052 def raise_runtime_error():
2053 raise RuntimeError("this shouldn't escape")
2054 enabled = gc.isenabled()
2055 orig_gc_disable = gc.disable
2056 orig_gc_isenabled = gc.isenabled
2057 try:
2058 gc.disable()
2059 self.assertFalse(gc.isenabled())
2060 subprocess.call([sys.executable, '-c', ''],
2061 preexec_fn=lambda: None)
2062 self.assertFalse(gc.isenabled(),
2063 "Popen enabled gc when it shouldn't.")
2064
2065 gc.enable()
2066 self.assertTrue(gc.isenabled())
2067 subprocess.call([sys.executable, '-c', ''],
2068 preexec_fn=lambda: None)
2069 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
2070
2071 gc.disable = raise_runtime_error
2072 self.assertRaises(RuntimeError, subprocess.Popen,
2073 [sys.executable, '-c', ''],
2074 preexec_fn=lambda: None)
2075
2076 del gc.isenabled # force an AttributeError
2077 self.assertRaises(AttributeError, subprocess.Popen,
2078 [sys.executable, '-c', ''],
2079 preexec_fn=lambda: None)
2080 finally:
2081 gc.disable = orig_gc_disable
2082 gc.isenabled = orig_gc_isenabled
2083 if not enabled:
2084 gc.disable()
2085
Martin Panterf7fdbda2015-12-05 09:51:52 +00002086 @unittest.skipIf(
2087 sys.platform == 'darwin', 'setrlimit() seems to fail on OS X')
Martin Panterafdd5132015-11-30 02:21:41 +00002088 def test_preexec_fork_failure(self):
2089 # The internal code did not preserve the previous exception when
2090 # re-enabling garbage collection
2091 try:
2092 from resource import getrlimit, setrlimit, RLIMIT_NPROC
2093 except ImportError as err:
2094 self.skipTest(err) # RLIMIT_NPROC is specific to Linux and BSD
2095 limits = getrlimit(RLIMIT_NPROC)
2096 [_, hard] = limits
2097 setrlimit(RLIMIT_NPROC, (0, hard))
2098 self.addCleanup(setrlimit, RLIMIT_NPROC, limits)
Martin Panter5cf791b2015-12-11 05:40:14 +00002099 try:
Martin Panterafdd5132015-11-30 02:21:41 +00002100 subprocess.call([sys.executable, '-c', ''],
2101 preexec_fn=lambda: None)
Martin Panter5cf791b2015-12-11 05:40:14 +00002102 except BlockingIOError:
2103 # Forking should raise EAGAIN, translated to BlockingIOError
2104 pass
2105 else:
2106 self.skipTest('RLIMIT_NPROC had no effect; probably superuser')
Martin Panterafdd5132015-11-30 02:21:41 +00002107
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002108 def test_args_string(self):
2109 # args is a string
Berker Peksag16a1f282015-09-28 13:33:14 +03002110 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002111 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00002112 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02002113 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002114 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
2115 sys.executable)
2116 os.chmod(fname, 0o700)
2117 p = subprocess.Popen(fname)
2118 p.wait()
2119 os.remove(fname)
2120 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002121
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002122 def test_invalid_args(self):
2123 # invalid arguments should raise ValueError
2124 self.assertRaises(ValueError, subprocess.call,
2125 [sys.executable, "-c",
2126 "import sys; sys.exit(47)"],
2127 startupinfo=47)
2128 self.assertRaises(ValueError, subprocess.call,
2129 [sys.executable, "-c",
2130 "import sys; sys.exit(47)"],
2131 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002132
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002133 def test_shell_sequence(self):
2134 # Run command through the shell (sequence)
2135 newenv = os.environ.copy()
2136 newenv["FRUIT"] = "apple"
2137 p = subprocess.Popen(["echo $FRUIT"], shell=1,
2138 stdout=subprocess.PIPE,
2139 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02002140 with p:
2141 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002142
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002143 def test_shell_string(self):
2144 # Run command through the shell (string)
2145 newenv = os.environ.copy()
2146 newenv["FRUIT"] = "apple"
2147 p = subprocess.Popen("echo $FRUIT", shell=1,
2148 stdout=subprocess.PIPE,
2149 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02002150 with p:
2151 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +00002152
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002153 def test_call_string(self):
2154 # call() function with string argument on UNIX
Berker Peksag16a1f282015-09-28 13:33:14 +03002155 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002156 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00002157 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02002158 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002159 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
2160 sys.executable)
2161 os.chmod(fname, 0o700)
2162 rc = subprocess.call(fname)
2163 os.remove(fname)
2164 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00002165
Stefan Krah9542cc62010-07-19 14:20:53 +00002166 def test_specific_shell(self):
2167 # Issue #9265: Incorrect name passed as arg[0].
2168 shells = []
2169 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
2170 for name in ['bash', 'ksh']:
2171 sh = os.path.join(prefix, name)
2172 if os.path.isfile(sh):
2173 shells.append(sh)
2174 if not shells: # Will probably work for any shell but csh.
2175 self.skipTest("bash or ksh required for this test")
2176 sh = '/bin/sh'
2177 if os.path.isfile(sh) and not os.path.islink(sh):
2178 # Test will fail if /bin/sh is a symlink to csh.
2179 shells.append(sh)
2180 for sh in shells:
2181 p = subprocess.Popen("echo $0", executable=sh, shell=True,
2182 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02002183 with p:
2184 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
Stefan Krah9542cc62010-07-19 14:20:53 +00002185
Florent Xicluna4886d242010-03-08 13:27:26 +00002186 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00002187 # Do not inherit file handles from the parent.
2188 # It should fix failures on some platforms.
Gregory P. Smithdee04342013-08-29 13:35:27 -07002189 # Also set the SIGINT handler to the default to make sure it's not
2190 # being ignored (some tests rely on that.)
2191 old_handler = signal.signal(signal.SIGINT, signal.default_int_handler)
2192 try:
2193 p = subprocess.Popen([sys.executable, "-c", """if 1:
2194 import sys, time
2195 sys.stdout.write('x\\n')
2196 sys.stdout.flush()
2197 time.sleep(30)
2198 """],
2199 close_fds=True,
2200 stdin=subprocess.PIPE,
2201 stdout=subprocess.PIPE,
2202 stderr=subprocess.PIPE)
2203 finally:
2204 signal.signal(signal.SIGINT, old_handler)
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00002205 # Wait for the interpreter to be completely initialized before
2206 # sending any signal.
2207 p.stdout.read(1)
2208 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00002209 return p
2210
Charles-François Natali53221e32013-01-12 16:52:20 +01002211 @unittest.skipIf(sys.platform.startswith(('netbsd', 'openbsd')),
2212 "Due to known OS bug (issue #16762)")
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002213 def _kill_dead_process(self, method, *args):
2214 # Do not inherit file handles from the parent.
2215 # It should fix failures on some platforms.
2216 p = subprocess.Popen([sys.executable, "-c", """if 1:
2217 import sys, time
2218 sys.stdout.write('x\\n')
2219 sys.stdout.flush()
2220 """],
2221 close_fds=True,
2222 stdin=subprocess.PIPE,
2223 stdout=subprocess.PIPE,
2224 stderr=subprocess.PIPE)
2225 # Wait for the interpreter to be completely initialized before
2226 # sending any signal.
2227 p.stdout.read(1)
2228 # The process should end after this
2229 time.sleep(1)
2230 # This shouldn't raise even though the child is now dead
2231 getattr(p, method)(*args)
2232 p.communicate()
2233
Florent Xicluna4886d242010-03-08 13:27:26 +00002234 def test_send_signal(self):
2235 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00002236 _, stderr = p.communicate()
2237 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002238 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00002239
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002240 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002241 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00002242 _, stderr = p.communicate()
2243 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002244 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00002245
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002246 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002247 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00002248 _, stderr = p.communicate()
2249 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002250 self.assertEqual(p.wait(), -signal.SIGTERM)
2251
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002252 def test_send_signal_dead(self):
2253 # Sending a signal to a dead process
2254 self._kill_dead_process('send_signal', signal.SIGINT)
2255
2256 def test_kill_dead(self):
2257 # Killing a dead process
2258 self._kill_dead_process('kill')
2259
2260 def test_terminate_dead(self):
2261 # Terminating a dead process
2262 self._kill_dead_process('terminate')
2263
Victor Stinnerdaf45552013-08-28 00:53:59 +02002264 def _save_fds(self, save_fds):
2265 fds = []
2266 for fd in save_fds:
2267 inheritable = os.get_inheritable(fd)
2268 saved = os.dup(fd)
2269 fds.append((fd, saved, inheritable))
2270 return fds
2271
2272 def _restore_fds(self, fds):
2273 for fd, saved, inheritable in fds:
2274 os.dup2(saved, fd, inheritable=inheritable)
2275 os.close(saved)
2276
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002277 def check_close_std_fds(self, fds):
2278 # Issue #9905: test that subprocess pipes still work properly with
2279 # some standard fds closed
2280 stdin = 0
Victor Stinnerdaf45552013-08-28 00:53:59 +02002281 saved_fds = self._save_fds(fds)
2282 for fd, saved, inheritable in saved_fds:
2283 if fd == 0:
2284 stdin = saved
2285 break
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002286 try:
2287 for fd in fds:
2288 os.close(fd)
2289 out, err = subprocess.Popen([sys.executable, "-c",
2290 'import sys;'
2291 'sys.stdout.write("apple");'
2292 'sys.stdout.flush();'
2293 'sys.stderr.write("orange")'],
2294 stdin=stdin,
2295 stdout=subprocess.PIPE,
2296 stderr=subprocess.PIPE).communicate()
2297 err = support.strip_python_stderr(err)
2298 self.assertEqual((out, err), (b'apple', b'orange'))
2299 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002300 self._restore_fds(saved_fds)
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002301
2302 def test_close_fd_0(self):
2303 self.check_close_std_fds([0])
2304
2305 def test_close_fd_1(self):
2306 self.check_close_std_fds([1])
2307
2308 def test_close_fd_2(self):
2309 self.check_close_std_fds([2])
2310
2311 def test_close_fds_0_1(self):
2312 self.check_close_std_fds([0, 1])
2313
2314 def test_close_fds_0_2(self):
2315 self.check_close_std_fds([0, 2])
2316
2317 def test_close_fds_1_2(self):
2318 self.check_close_std_fds([1, 2])
2319
2320 def test_close_fds_0_1_2(self):
2321 # Issue #10806: test that subprocess pipes still work properly with
2322 # all standard fds closed.
2323 self.check_close_std_fds([0, 1, 2])
2324
Gregory P. Smith53dd8162013-12-01 16:03:24 -08002325 def test_small_errpipe_write_fd(self):
2326 """Issue #15798: Popen should work when stdio fds are available."""
2327 new_stdin = os.dup(0)
2328 new_stdout = os.dup(1)
2329 try:
2330 os.close(0)
2331 os.close(1)
2332
2333 # Side test: if errpipe_write fails to have its CLOEXEC
2334 # flag set this should cause the parent to think the exec
2335 # failed. Extremely unlikely: everyone supports CLOEXEC.
2336 subprocess.Popen([
2337 sys.executable, "-c",
2338 "print('AssertionError:0:CLOEXEC failure.')"]).wait()
2339 finally:
2340 # Restore original stdin and stdout
2341 os.dup2(new_stdin, 0)
2342 os.dup2(new_stdout, 1)
2343 os.close(new_stdin)
2344 os.close(new_stdout)
2345
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002346 def test_remapping_std_fds(self):
2347 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03002348 temps = [tempfile.mkstemp() for i in range(3)]
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002349 try:
2350 temp_fds = [fd for fd, fname in temps]
2351
2352 # unlink the files -- we won't need to reopen them
2353 for fd, fname in temps:
2354 os.unlink(fname)
2355
2356 # write some data to what will become stdin, and rewind
2357 os.write(temp_fds[1], b"STDIN")
2358 os.lseek(temp_fds[1], 0, 0)
2359
2360 # move the standard file descriptors out of the way
Victor Stinnerdaf45552013-08-28 00:53:59 +02002361 saved_fds = self._save_fds(range(3))
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002362 try:
2363 # duplicate the file objects over the standard fd's
2364 for fd, temp_fd in enumerate(temp_fds):
2365 os.dup2(temp_fd, fd)
2366
2367 # now use those files in the "wrong" order, so that subprocess
2368 # has to rearrange them in the child
2369 p = subprocess.Popen([sys.executable, "-c",
2370 'import sys; got = sys.stdin.read();'
2371 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
2372 stdin=temp_fds[1],
2373 stdout=temp_fds[2],
2374 stderr=temp_fds[0])
2375 p.wait()
2376 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002377 self._restore_fds(saved_fds)
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002378
2379 for fd in temp_fds:
2380 os.lseek(fd, 0, 0)
2381
2382 out = os.read(temp_fds[2], 1024)
2383 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
2384 self.assertEqual(out, b"got STDIN")
2385 self.assertEqual(err, b"err")
2386
2387 finally:
2388 for fd in temp_fds:
2389 os.close(fd)
2390
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002391 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
2392 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03002393 temps = [tempfile.mkstemp() for i in range(3)]
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002394 temp_fds = [fd for fd, fname in temps]
2395 try:
2396 # unlink the files -- we won't need to reopen them
2397 for fd, fname in temps:
2398 os.unlink(fname)
2399
2400 # save a copy of the standard file descriptors
Victor Stinnerdaf45552013-08-28 00:53:59 +02002401 saved_fds = self._save_fds(range(3))
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002402 try:
2403 # duplicate the temp files over the standard fd's 0, 1, 2
2404 for fd, temp_fd in enumerate(temp_fds):
2405 os.dup2(temp_fd, fd)
2406
2407 # write some data to what will become stdin, and rewind
2408 os.write(stdin_no, b"STDIN")
2409 os.lseek(stdin_no, 0, 0)
2410
2411 # now use those files in the given order, so that subprocess
2412 # has to rearrange them in the child
2413 p = subprocess.Popen([sys.executable, "-c",
2414 'import sys; got = sys.stdin.read();'
2415 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
2416 stdin=stdin_no,
2417 stdout=stdout_no,
2418 stderr=stderr_no)
2419 p.wait()
2420
2421 for fd in temp_fds:
2422 os.lseek(fd, 0, 0)
2423
2424 out = os.read(stdout_no, 1024)
2425 err = support.strip_python_stderr(os.read(stderr_no, 1024))
2426 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002427 self._restore_fds(saved_fds)
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002428
2429 self.assertEqual(out, b"got STDIN")
2430 self.assertEqual(err, b"err")
2431
2432 finally:
2433 for fd in temp_fds:
2434 os.close(fd)
2435
2436 # When duping fds, if there arises a situation where one of the fds is
2437 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
2438 # This tests all combinations of this.
2439 def test_swap_fds(self):
2440 self.check_swap_fds(0, 1, 2)
2441 self.check_swap_fds(0, 2, 1)
2442 self.check_swap_fds(1, 0, 2)
2443 self.check_swap_fds(1, 2, 0)
2444 self.check_swap_fds(2, 0, 1)
2445 self.check_swap_fds(2, 1, 0)
2446
Alexey Izbyshev0e7144b2018-03-26 22:49:35 +03002447 def _check_swap_std_fds_with_one_closed(self, from_fds, to_fds):
2448 saved_fds = self._save_fds(range(3))
2449 try:
2450 for from_fd in from_fds:
2451 with tempfile.TemporaryFile() as f:
2452 os.dup2(f.fileno(), from_fd)
2453
2454 fd_to_close = (set(range(3)) - set(from_fds)).pop()
2455 os.close(fd_to_close)
2456
2457 arg_names = ['stdin', 'stdout', 'stderr']
2458 kwargs = {}
2459 for from_fd, to_fd in zip(from_fds, to_fds):
2460 kwargs[arg_names[to_fd]] = from_fd
2461
2462 code = textwrap.dedent(r'''
2463 import os, sys
2464 skipped_fd = int(sys.argv[1])
2465 for fd in range(3):
2466 if fd != skipped_fd:
2467 os.write(fd, str(fd).encode('ascii'))
2468 ''')
2469
2470 skipped_fd = (set(range(3)) - set(to_fds)).pop()
2471
2472 rc = subprocess.call([sys.executable, '-c', code, str(skipped_fd)],
2473 **kwargs)
2474 self.assertEqual(rc, 0)
2475
2476 for from_fd, to_fd in zip(from_fds, to_fds):
2477 os.lseek(from_fd, 0, os.SEEK_SET)
2478 read_bytes = os.read(from_fd, 1024)
2479 read_fds = list(map(int, read_bytes.decode('ascii')))
2480 msg = textwrap.dedent(f"""
2481 When testing {from_fds} to {to_fds} redirection,
2482 parent descriptor {from_fd} got redirected
2483 to descriptor(s) {read_fds} instead of descriptor {to_fd}.
2484 """)
2485 self.assertEqual([to_fd], read_fds, msg)
2486 finally:
2487 self._restore_fds(saved_fds)
2488
2489 # Check that subprocess can remap std fds correctly even
2490 # if one of them is closed (#32844).
2491 def test_swap_std_fds_with_one_closed(self):
2492 for from_fds in itertools.combinations(range(3), 2):
2493 for to_fds in itertools.permutations(range(3), 2):
2494 self._check_swap_std_fds_with_one_closed(from_fds, to_fds)
2495
Victor Stinner13bb71c2010-04-23 21:41:56 +00002496 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00002497 def prepare():
2498 raise ValueError("surrogate:\uDCff")
2499
2500 try:
2501 subprocess.call(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002502 ZERO_RETURN_CMD,
Victor Stinner4d078042010-04-23 19:28:32 +00002503 preexec_fn=prepare)
2504 except ValueError as err:
2505 # Pure Python implementations keeps the message
2506 self.assertIsNone(subprocess._posixsubprocess)
2507 self.assertEqual(str(err), "surrogate:\uDCff")
Gregory P. Smith8d07c262012-11-10 23:53:47 -08002508 except subprocess.SubprocessError as err:
Victor Stinner4d078042010-04-23 19:28:32 +00002509 # _posixsubprocess uses a default message
2510 self.assertIsNotNone(subprocess._posixsubprocess)
2511 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
2512 else:
Gregory P. Smith8d07c262012-11-10 23:53:47 -08002513 self.fail("Expected ValueError or subprocess.SubprocessError")
Victor Stinner4d078042010-04-23 19:28:32 +00002514
Victor Stinner13bb71c2010-04-23 21:41:56 +00002515 def test_undecodable_env(self):
2516 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner5323fb02013-11-19 23:46:06 +01002517 encoded_value = value.encode("ascii", "surrogateescape")
2518
Victor Stinner13bb71c2010-04-23 21:41:56 +00002519 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00002520 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002521 env = os.environ.copy()
2522 env[key] = value
Victor Stinner5323fb02013-11-19 23:46:06 +01002523 # Use C locale to get ASCII for the locale encoding to force
Michael Felt89d79b12018-08-26 19:29:36 +02002524 # surrogate-escaping of \xFF in the child process
Victor Stinnerebc78d22010-10-14 10:38:17 +00002525 env['LC_ALL'] = 'C'
Michael Felt89d79b12018-08-26 19:29:36 +02002526 decoded_value = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00002527 stdout = subprocess.check_output(
2528 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002529 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00002530 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01002531 self.assertEqual(stdout.decode('ascii'), ascii(decoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00002532
2533 # test bytes
2534 key = key.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00002535 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002536 env = os.environ.copy()
Victor Stinner5323fb02013-11-19 23:46:06 +01002537 env[key] = encoded_value
Victor Stinner13bb71c2010-04-23 21:41:56 +00002538 stdout = subprocess.check_output(
2539 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002540 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00002541 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01002542 self.assertEqual(stdout.decode('ascii'), ascii(encoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00002543
Victor Stinnerb745a742010-05-18 17:17:23 +00002544 def test_bytes_program(self):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002545 abs_program = os.fsencode(ZERO_RETURN_CMD[0])
2546 args = list(ZERO_RETURN_CMD[1:])
2547 path, program = os.path.split(ZERO_RETURN_CMD[0])
Victor Stinnerb745a742010-05-18 17:17:23 +00002548 program = os.fsencode(program)
2549
2550 # absolute bytes path
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002551 exitcode = subprocess.call([abs_program]+args)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002552 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002553
Victor Stinner7b3b20a2011-03-03 12:54:05 +00002554 # absolute bytes path as a string
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002555 cmd = b"'%s' %s" % (abs_program, " ".join(args).encode("utf-8"))
Victor Stinner7b3b20a2011-03-03 12:54:05 +00002556 exitcode = subprocess.call(cmd, shell=True)
2557 self.assertEqual(exitcode, 0)
2558
Victor Stinnerb745a742010-05-18 17:17:23 +00002559 # bytes program, unicode PATH
2560 env = os.environ.copy()
2561 env["PATH"] = path
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002562 exitcode = subprocess.call([program]+args, env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002563 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002564
2565 # bytes program, bytes PATH
2566 envb = os.environb.copy()
2567 envb[b"PATH"] = os.fsencode(path)
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002568 exitcode = subprocess.call([program]+args, env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002569 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002570
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002571 def test_pipe_cloexec(self):
2572 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
2573 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2574
2575 p1 = subprocess.Popen([sys.executable, sleeper],
2576 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2577 stderr=subprocess.PIPE, close_fds=False)
2578
2579 self.addCleanup(p1.communicate, b'')
2580
2581 p2 = subprocess.Popen([sys.executable, fd_status],
2582 stdout=subprocess.PIPE, close_fds=False)
2583
2584 output, error = p2.communicate()
2585 result_fds = set(map(int, output.split(b',')))
2586 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
2587 p1.stderr.fileno()])
2588
2589 self.assertFalse(result_fds & unwanted_fds,
2590 "Expected no fds from %r to be open in child, "
2591 "found %r" %
2592 (unwanted_fds, result_fds & unwanted_fds))
2593
2594 def test_pipe_cloexec_real_tools(self):
2595 qcat = support.findfile("qcat.py", subdir="subprocessdata")
2596 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
2597
2598 subdata = b'zxcvbn'
2599 data = subdata * 4 + b'\n'
2600
2601 p1 = subprocess.Popen([sys.executable, qcat],
2602 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2603 close_fds=False)
2604
2605 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
2606 stdin=p1.stdout, stdout=subprocess.PIPE,
2607 close_fds=False)
2608
2609 self.addCleanup(p1.wait)
2610 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08002611 def kill_p1():
2612 try:
2613 p1.terminate()
2614 except ProcessLookupError:
2615 pass
2616 def kill_p2():
2617 try:
2618 p2.terminate()
2619 except ProcessLookupError:
2620 pass
2621 self.addCleanup(kill_p1)
2622 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002623
2624 p1.stdin.write(data)
2625 p1.stdin.close()
2626
2627 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
2628
2629 self.assertTrue(readfiles, "The child hung")
2630 self.assertEqual(p2.stdout.read(), data)
2631
Victor Stinnerfaa8c132011-01-03 16:36:00 +00002632 p1.stdout.close()
2633 p2.stdout.close()
2634
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002635 def test_close_fds(self):
2636 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2637
2638 fds = os.pipe()
2639 self.addCleanup(os.close, fds[0])
2640 self.addCleanup(os.close, fds[1])
2641
2642 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002643 # add a bunch more fds
2644 for _ in range(9):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002645 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002646 self.addCleanup(os.close, fd)
2647 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002648
Victor Stinnerdaf45552013-08-28 00:53:59 +02002649 for fd in open_fds:
2650 os.set_inheritable(fd, True)
2651
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002652 p = subprocess.Popen([sys.executable, fd_status],
2653 stdout=subprocess.PIPE, close_fds=False)
2654 output, ignored = p.communicate()
2655 remaining_fds = set(map(int, output.split(b',')))
2656
2657 self.assertEqual(remaining_fds & open_fds, open_fds,
2658 "Some fds were closed")
2659
2660 p = subprocess.Popen([sys.executable, fd_status],
2661 stdout=subprocess.PIPE, close_fds=True)
2662 output, ignored = p.communicate()
2663 remaining_fds = set(map(int, output.split(b',')))
2664
2665 self.assertFalse(remaining_fds & open_fds,
2666 "Some fds were left open")
2667 self.assertIn(1, remaining_fds, "Subprocess failed")
2668
Gregory P. Smith8facece2012-01-21 14:01:08 -08002669 # Keep some of the fd's we opened open in the subprocess.
2670 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
2671 fds_to_keep = set(open_fds.pop() for _ in range(8))
2672 p = subprocess.Popen([sys.executable, fd_status],
2673 stdout=subprocess.PIPE, close_fds=True,
izbyshev2d8f0632017-12-19 03:26:49 +07002674 pass_fds=fds_to_keep)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002675 output, ignored = p.communicate()
2676 remaining_fds = set(map(int, output.split(b',')))
2677
izbyshev2d8f0632017-12-19 03:26:49 +07002678 self.assertFalse((remaining_fds - fds_to_keep) & open_fds,
Gregory P. Smith8facece2012-01-21 14:01:08 -08002679 "Some fds not in pass_fds were left open")
2680 self.assertIn(1, remaining_fds, "Subprocess failed")
2681
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002682
Gregory P. Smithd04f6992014-06-01 15:27:28 -07002683 @unittest.skipIf(sys.platform.startswith("freebsd") and
2684 os.stat("/dev").st_dev == os.stat("/dev/fd").st_dev,
2685 "Requires fdescfs mounted on /dev/fd on FreeBSD.")
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002686 def test_close_fds_when_max_fd_is_lowered(self):
2687 """Confirm that issue21618 is fixed (may fail under valgrind)."""
2688 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2689
Gregory P. Smith634aa682014-06-15 17:51:04 -07002690 # This launches the meat of the test in a child process to
2691 # avoid messing with the larger unittest processes maximum
2692 # number of file descriptors.
2693 # This process launches:
2694 # +--> Process that lowers its RLIMIT_NOFILE aftr setting up
2695 # a bunch of high open fds above the new lower rlimit.
2696 # Those are reported via stdout before launching a new
2697 # process with close_fds=False to run the actual test:
2698 # +--> The TEST: This one launches a fd_status.py
2699 # subprocess with close_fds=True so we can find out if
2700 # any of the fds above the lowered rlimit are still open.
2701 p = subprocess.Popen([sys.executable, '-c', textwrap.dedent(
2702 '''
2703 import os, resource, subprocess, sys, textwrap
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002704 open_fds = set()
2705 # Add a bunch more fds to pass down.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002706 for _ in range(40):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002707 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002708 open_fds.add(fd)
2709
2710 # Leave a two pairs of low ones available for use by the
2711 # internal child error pipe and the stdout pipe.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002712 # We also leave 10 more open as some Python buildbots run into
2713 # "too many open files" errors during the test if we do not.
2714 for fd in sorted(open_fds)[:14]:
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002715 os.close(fd)
2716 open_fds.remove(fd)
2717
2718 for fd in open_fds:
Gregory P. Smith634aa682014-06-15 17:51:04 -07002719 #self.addCleanup(os.close, fd)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002720 os.set_inheritable(fd, True)
2721
2722 max_fd_open = max(open_fds)
2723
Gregory P. Smith634aa682014-06-15 17:51:04 -07002724 # Communicate the open_fds to the parent unittest.TestCase process.
2725 print(','.join(map(str, sorted(open_fds))))
2726 sys.stdout.flush()
2727
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002728 rlim_cur, rlim_max = resource.getrlimit(resource.RLIMIT_NOFILE)
2729 try:
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002730 # 29 is lower than the highest fds we are leaving open.
2731 resource.setrlimit(resource.RLIMIT_NOFILE, (29, rlim_max))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002732 # Launch a new Python interpreter with our low fd rlim_cur that
2733 # inherits open fds above that limit. It then uses subprocess
2734 # with close_fds=True to get a report of open fds in the child.
2735 # An explicit list of fds to check is passed to fd_status.py as
2736 # letting fd_status rely on its default logic would miss the
2737 # fds above rlim_cur as it normally only checks up to that limit.
Gregory P. Smith634aa682014-06-15 17:51:04 -07002738 subprocess.Popen(
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002739 [sys.executable, '-c',
2740 textwrap.dedent("""
2741 import subprocess, sys
Gregory P. Smith634aa682014-06-15 17:51:04 -07002742 subprocess.Popen([sys.executable, %r] +
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002743 [str(x) for x in range({max_fd})],
Gregory P. Smithffd529c2014-06-01 13:46:54 -07002744 close_fds=True).wait()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002745 """.format(max_fd=max_fd_open+1))],
2746 close_fds=False).wait()
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002747 finally:
2748 resource.setrlimit(resource.RLIMIT_NOFILE, (rlim_cur, rlim_max))
Gregory P. Smith634aa682014-06-15 17:51:04 -07002749 ''' % fd_status)], stdout=subprocess.PIPE)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002750
2751 output, unused_stderr = p.communicate()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002752 output_lines = output.splitlines()
2753 self.assertEqual(len(output_lines), 2,
Gregory P. Smith9204e092014-06-15 20:16:01 -07002754 msg="expected exactly two lines of output:\n%r" % output)
Gregory P. Smith634aa682014-06-15 17:51:04 -07002755 opened_fds = set(map(int, output_lines[0].strip().split(b',')))
2756 remaining_fds = set(map(int, output_lines[1].strip().split(b',')))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002757
Gregory P. Smith634aa682014-06-15 17:51:04 -07002758 self.assertFalse(remaining_fds & opened_fds,
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002759 msg="Some fds were left open.")
2760
2761
Victor Stinner88701e22011-06-01 13:13:04 +02002762 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
2763 # descriptor of a pipe closed in the parent process is valid in the
2764 # child process according to fstat(), but the mode of the file
2765 # descriptor is invalid, and read or write raise an error.
2766 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002767 def test_pass_fds(self):
2768 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2769
2770 open_fds = set()
2771
2772 for x in range(5):
2773 fds = os.pipe()
2774 self.addCleanup(os.close, fds[0])
2775 self.addCleanup(os.close, fds[1])
Victor Stinnerdaf45552013-08-28 00:53:59 +02002776 os.set_inheritable(fds[0], True)
2777 os.set_inheritable(fds[1], True)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002778 open_fds.update(fds)
2779
2780 for fd in open_fds:
2781 p = subprocess.Popen([sys.executable, fd_status],
2782 stdout=subprocess.PIPE, close_fds=True,
2783 pass_fds=(fd, ))
2784 output, ignored = p.communicate()
2785
2786 remaining_fds = set(map(int, output.split(b',')))
2787 to_be_closed = open_fds - {fd}
2788
2789 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
2790 self.assertFalse(remaining_fds & to_be_closed,
2791 "fd to be closed passed")
2792
2793 # pass_fds overrides close_fds with a warning.
2794 with self.assertWarns(RuntimeWarning) as context:
2795 self.assertFalse(subprocess.call(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002796 ZERO_RETURN_CMD,
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002797 close_fds=False, pass_fds=(fd, )))
2798 self.assertIn('overriding close_fds', str(context.warning))
2799
Victor Stinnerdaf45552013-08-28 00:53:59 +02002800 def test_pass_fds_inheritable(self):
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002801 script = support.findfile("fd_status.py", subdir="subprocessdata")
Victor Stinnerdaf45552013-08-28 00:53:59 +02002802
2803 inheritable, non_inheritable = os.pipe()
2804 self.addCleanup(os.close, inheritable)
2805 self.addCleanup(os.close, non_inheritable)
2806 os.set_inheritable(inheritable, True)
2807 os.set_inheritable(non_inheritable, False)
2808 pass_fds = (inheritable, non_inheritable)
2809 args = [sys.executable, script]
2810 args += list(map(str, pass_fds))
2811
2812 p = subprocess.Popen(args,
2813 stdout=subprocess.PIPE, close_fds=True,
2814 pass_fds=pass_fds)
2815 output, ignored = p.communicate()
2816 fds = set(map(int, output.split(b',')))
2817
2818 # the inheritable file descriptor must be inherited, so its inheritable
2819 # flag must be set in the child process after fork() and before exec()
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002820 self.assertEqual(fds, set(pass_fds), "output=%a" % output)
Victor Stinnerdaf45552013-08-28 00:53:59 +02002821
2822 # inheritable flag must not be changed in the parent process
2823 self.assertEqual(os.get_inheritable(inheritable), True)
2824 self.assertEqual(os.get_inheritable(non_inheritable), False)
2825
Gregory P. Smithce344102018-09-10 17:46:22 -07002826
2827 # bpo-32270: Ensure that descriptors specified in pass_fds
2828 # are inherited even if they are used in redirections.
2829 # Contributed by @izbyshev.
2830 def test_pass_fds_redirected(self):
2831 """Regression test for https://bugs.python.org/issue32270."""
2832 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2833 pass_fds = []
2834 for _ in range(2):
2835 fd = os.open(os.devnull, os.O_RDWR)
2836 self.addCleanup(os.close, fd)
2837 pass_fds.append(fd)
2838
2839 stdout_r, stdout_w = os.pipe()
2840 self.addCleanup(os.close, stdout_r)
2841 self.addCleanup(os.close, stdout_w)
2842 pass_fds.insert(1, stdout_w)
2843
2844 with subprocess.Popen([sys.executable, fd_status],
2845 stdin=pass_fds[0],
2846 stdout=pass_fds[1],
2847 stderr=pass_fds[2],
2848 close_fds=True,
2849 pass_fds=pass_fds):
2850 output = os.read(stdout_r, 1024)
2851 fds = {int(num) for num in output.split(b',')}
2852
2853 self.assertEqual(fds, {0, 1, 2} | frozenset(pass_fds), f"output={output!a}")
2854
2855
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002856 def test_stdout_stdin_are_single_inout_fd(self):
2857 with io.open(os.devnull, "r+") as inout:
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002858 p = subprocess.Popen(ZERO_RETURN_CMD,
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002859 stdout=inout, stdin=inout)
2860 p.wait()
2861
2862 def test_stdout_stderr_are_single_inout_fd(self):
2863 with io.open(os.devnull, "r+") as inout:
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002864 p = subprocess.Popen(ZERO_RETURN_CMD,
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002865 stdout=inout, stderr=inout)
2866 p.wait()
2867
2868 def test_stderr_stdin_are_single_inout_fd(self):
2869 with io.open(os.devnull, "r+") as inout:
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002870 p = subprocess.Popen(ZERO_RETURN_CMD,
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002871 stderr=inout, stdin=inout)
2872 p.wait()
2873
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002874 def test_wait_when_sigchild_ignored(self):
2875 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
2876 sigchild_ignore = support.findfile("sigchild_ignore.py",
2877 subdir="subprocessdata")
2878 p = subprocess.Popen([sys.executable, sigchild_ignore],
2879 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
2880 stdout, stderr = p.communicate()
2881 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00002882 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00002883 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002884
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002885 def test_select_unbuffered(self):
2886 # Issue #11459: bufsize=0 should really set the pipes as
2887 # unbuffered (and therefore let select() work properly).
2888 select = support.import_module("select")
2889 p = subprocess.Popen([sys.executable, "-c",
2890 'import sys;'
2891 'sys.stdout.write("apple")'],
2892 stdout=subprocess.PIPE,
2893 bufsize=0)
2894 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02002895 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002896 try:
2897 self.assertEqual(f.read(4), b"appl")
2898 self.assertIn(f, select.select([f], [], [], 0.0)[0])
2899 finally:
2900 p.wait()
2901
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002902 def test_zombie_fast_process_del(self):
2903 # Issue #12650: on Unix, if Popen.__del__() was called before the
2904 # process exited, it wouldn't be added to subprocess._active, and would
2905 # remain a zombie.
2906 # spawn a Popen, and delete its reference before it exits
2907 p = subprocess.Popen([sys.executable, "-c",
2908 'import sys, time;'
2909 'time.sleep(0.2)'],
2910 stdout=subprocess.PIPE,
2911 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002912 self.addCleanup(p.stdout.close)
2913 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002914 ident = id(p)
2915 pid = p.pid
Victor Stinner5a48e212016-05-20 12:11:15 +02002916 with support.check_warnings(('', ResourceWarning)):
2917 p = None
2918
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +03002919 if mswindows:
2920 # subprocess._active is not used on Windows and is set to None.
2921 self.assertIsNone(subprocess._active)
2922 else:
2923 # check that p is in the active processes list
2924 self.assertIn(ident, [id(o) for o in subprocess._active])
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002925
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002926 def test_leak_fast_process_del_killed(self):
2927 # Issue #12650: on Unix, if Popen.__del__() was called before the
2928 # process exited, and the process got killed by a signal, it would never
2929 # be removed from subprocess._active, which triggered a FD and memory
2930 # leak.
2931 # spawn a Popen, delete its reference and kill it
2932 p = subprocess.Popen([sys.executable, "-c",
2933 'import time;'
2934 'time.sleep(3)'],
2935 stdout=subprocess.PIPE,
2936 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002937 self.addCleanup(p.stdout.close)
2938 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002939 ident = id(p)
2940 pid = p.pid
Victor Stinner5a48e212016-05-20 12:11:15 +02002941 with support.check_warnings(('', ResourceWarning)):
2942 p = None
2943
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002944 os.kill(pid, signal.SIGKILL)
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +03002945 if mswindows:
2946 # subprocess._active is not used on Windows and is set to None.
2947 self.assertIsNone(subprocess._active)
2948 else:
2949 # check that p is in the active processes list
2950 self.assertIn(ident, [id(o) for o in subprocess._active])
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002951
2952 # let some time for the process to exit, and create a new Popen: this
2953 # should trigger the wait() of p
2954 time.sleep(0.2)
Victor Stinnerb31206a2018-01-25 19:06:05 +01002955 with self.assertRaises(OSError):
Victor Stinner9a83f652017-08-21 23:51:31 +02002956 with subprocess.Popen(NONEXISTING_CMD,
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002957 stdout=subprocess.PIPE,
2958 stderr=subprocess.PIPE) as proc:
2959 pass
2960 # p should have been wait()ed on, and removed from the _active list
2961 self.assertRaises(OSError, os.waitpid, pid, 0)
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +03002962 if mswindows:
2963 # subprocess._active is not used on Windows and is set to None.
2964 self.assertIsNone(subprocess._active)
2965 else:
2966 self.assertNotIn(ident, [id(o) for o in subprocess._active])
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002967
Charles-François Natali249cdc32013-08-25 18:24:45 +02002968 def test_close_fds_after_preexec(self):
2969 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2970
2971 # this FD is used as dup2() target by preexec_fn, and should be closed
2972 # in the child process
2973 fd = os.dup(1)
2974 self.addCleanup(os.close, fd)
2975
2976 p = subprocess.Popen([sys.executable, fd_status],
2977 stdout=subprocess.PIPE, close_fds=True,
2978 preexec_fn=lambda: os.dup2(1, fd))
2979 output, ignored = p.communicate()
2980
2981 remaining_fds = set(map(int, output.split(b',')))
2982
2983 self.assertNotIn(fd, remaining_fds)
2984
Victor Stinner8f437aa2014-10-05 17:25:19 +02002985 @support.cpython_only
2986 def test_fork_exec(self):
2987 # Issue #22290: fork_exec() must not crash on memory allocation failure
2988 # or other errors
2989 import _posixsubprocess
2990 gc_enabled = gc.isenabled()
2991 try:
2992 # Use a preexec function and enable the garbage collector
2993 # to force fork_exec() to re-enable the garbage collector
2994 # on error.
2995 func = lambda: None
2996 gc.enable()
2997
Victor Stinner8f437aa2014-10-05 17:25:19 +02002998 for args, exe_list, cwd, env_list in (
2999 (123, [b"exe"], None, [b"env"]),
3000 ([b"arg"], 123, None, [b"env"]),
3001 ([b"arg"], [b"exe"], 123, [b"env"]),
3002 ([b"arg"], [b"exe"], None, 123),
3003 ):
Patrick McLean2b2ead72019-09-12 10:15:44 -07003004 with self.assertRaises(TypeError) as err:
Victor Stinner8f437aa2014-10-05 17:25:19 +02003005 _posixsubprocess.fork_exec(
3006 args, exe_list,
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03003007 True, (), cwd, env_list,
Victor Stinner8f437aa2014-10-05 17:25:19 +02003008 -1, -1, -1, -1,
3009 1, 2, 3, 4,
Patrick McLean2b2ead72019-09-12 10:15:44 -07003010 True, True,
Gregory P. Smithf3751ef2019-10-12 13:24:56 -07003011 False, [], 0, -1,
Patrick McLean2b2ead72019-09-12 10:15:44 -07003012 func)
3013 # Attempt to prevent
3014 # "TypeError: fork_exec() takes exactly N arguments (M given)"
3015 # from passing the test. More refactoring to have us start
3016 # with a valid *args list, confirm a good call with that works
3017 # before mutating it in various ways to ensure that bad calls
3018 # with individual arg type errors raise a typeerror would be
3019 # ideal. Saving that for a future PR...
3020 self.assertNotIn('takes exactly', str(err.exception))
Victor Stinner8f437aa2014-10-05 17:25:19 +02003021 finally:
3022 if not gc_enabled:
3023 gc.disable()
3024
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08003025 @support.cpython_only
3026 def test_fork_exec_sorted_fd_sanity_check(self):
3027 # Issue #23564: sanity check the fork_exec() fds_to_keep sanity check.
3028 import _posixsubprocess
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03003029 class BadInt:
3030 first = True
3031 def __init__(self, value):
3032 self.value = value
3033 def __int__(self):
3034 if self.first:
3035 self.first = False
3036 return self.value
3037 raise ValueError
3038
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08003039 gc_enabled = gc.isenabled()
3040 try:
3041 gc.enable()
3042
3043 for fds_to_keep in (
3044 (-1, 2, 3, 4, 5), # Negative number.
3045 ('str', 4), # Not an int.
3046 (18, 23, 42, 2**63), # Out of range.
3047 (5, 4), # Not sorted.
3048 (6, 7, 7, 8), # Duplicate.
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03003049 (BadInt(1), BadInt(2)),
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08003050 ):
3051 with self.assertRaises(
3052 ValueError,
3053 msg='fds_to_keep={}'.format(fds_to_keep)) as c:
3054 _posixsubprocess.fork_exec(
3055 [b"false"], [b"false"],
3056 True, fds_to_keep, None, [b"env"],
3057 -1, -1, -1, -1,
3058 1, 2, 3, 4,
Patrick McLean2b2ead72019-09-12 10:15:44 -07003059 True, True,
Gregory P. Smithf3751ef2019-10-12 13:24:56 -07003060 None, None, None, -1,
Patrick McLean2b2ead72019-09-12 10:15:44 -07003061 None)
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08003062 self.assertIn('fds_to_keep', str(c.exception))
3063 finally:
3064 if not gc_enabled:
3065 gc.disable()
Victor Stinner8f437aa2014-10-05 17:25:19 +02003066
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)2daf8e72016-06-05 02:57:47 +00003067 def test_communicate_BrokenPipeError_stdin_close(self):
3068 # By not setting stdout or stderr or a timeout we force the fast path
3069 # that just calls _stdin_write() internally due to our mock.
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003070 proc = subprocess.Popen(ZERO_RETURN_CMD)
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)2daf8e72016-06-05 02:57:47 +00003071 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
3072 mock_proc_stdin.close.side_effect = BrokenPipeError
3073 proc.communicate() # Should swallow BrokenPipeError from close.
3074 mock_proc_stdin.close.assert_called_with()
3075
3076 def test_communicate_BrokenPipeError_stdin_write(self):
3077 # By not setting stdout or stderr or a timeout we force the fast path
3078 # that just calls _stdin_write() internally due to our mock.
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003079 proc = subprocess.Popen(ZERO_RETURN_CMD)
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)2daf8e72016-06-05 02:57:47 +00003080 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
3081 mock_proc_stdin.write.side_effect = BrokenPipeError
3082 proc.communicate(b'stuff') # Should swallow the BrokenPipeError.
3083 mock_proc_stdin.write.assert_called_once_with(b'stuff')
3084 mock_proc_stdin.close.assert_called_once_with()
3085
3086 def test_communicate_BrokenPipeError_stdin_flush(self):
3087 # Setting stdin and stdout forces the ._communicate() code path.
3088 # python -h exits faster than python -c pass (but spams stdout).
3089 proc = subprocess.Popen([sys.executable, '-h'],
3090 stdin=subprocess.PIPE,
3091 stdout=subprocess.PIPE)
3092 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin, \
3093 open(os.devnull, 'wb') as dev_null:
3094 mock_proc_stdin.flush.side_effect = BrokenPipeError
3095 # because _communicate registers a selector using proc.stdin...
3096 mock_proc_stdin.fileno.return_value = dev_null.fileno()
3097 # _communicate() should swallow BrokenPipeError from flush.
3098 proc.communicate(b'stuff')
3099 mock_proc_stdin.flush.assert_called_once_with()
3100
3101 def test_communicate_BrokenPipeError_stdin_close_with_timeout(self):
3102 # Setting stdin and stdout forces the ._communicate() code path.
3103 # python -h exits faster than python -c pass (but spams stdout).
3104 proc = subprocess.Popen([sys.executable, '-h'],
3105 stdin=subprocess.PIPE,
3106 stdout=subprocess.PIPE)
3107 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
3108 mock_proc_stdin.close.side_effect = BrokenPipeError
3109 # _communicate() should swallow BrokenPipeError from close.
3110 proc.communicate(timeout=999)
3111 mock_proc_stdin.close.assert_called_once_with()
3112
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003113 @unittest.skipUnless(_testcapi is not None
3114 and hasattr(_testcapi, 'W_STOPCODE'),
3115 'need _testcapi.W_STOPCODE')
3116 def test_stopped(self):
Gregory P. Smith50e16e32017-01-22 17:28:38 -08003117 """Test wait() behavior when waitpid returns WIFSTOPPED; issue29335."""
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003118 args = ZERO_RETURN_CMD
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003119 proc = subprocess.Popen(args)
Victor Stinnercdee3f12017-06-26 17:23:03 +02003120
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003121 # Wait until the real process completes to avoid zombie process
3122 pid = proc.pid
3123 pid, status = os.waitpid(pid, 0)
3124 self.assertEqual(status, 0)
Victor Stinnercdee3f12017-06-26 17:23:03 +02003125
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003126 status = _testcapi.W_STOPCODE(3)
3127 with mock.patch('subprocess.os.waitpid', return_value=(pid, status)):
3128 returncode = proc.wait()
Victor Stinnercdee3f12017-06-26 17:23:03 +02003129
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003130 self.assertEqual(returncode, -3)
Gregory P. Smith50e16e32017-01-22 17:28:38 -08003131
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003132
Victor Stinner937ee9e2018-06-26 02:11:06 +02003133@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00003134class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00003135
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003136 def test_startupinfo(self):
3137 # startupinfo argument
3138 # We uses hardcoded constants, because we do not want to
3139 # depend on win32all.
3140 STARTF_USESHOWWINDOW = 1
3141 SW_MAXIMIZE = 3
3142 startupinfo = subprocess.STARTUPINFO()
3143 startupinfo.dwFlags = STARTF_USESHOWWINDOW
3144 startupinfo.wShowWindow = SW_MAXIMIZE
3145 # Since Python is a console process, it won't be affected
3146 # by wShowWindow, but the argument should be silently
3147 # ignored
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003148 subprocess.call(ZERO_RETURN_CMD,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003149 startupinfo=startupinfo)
3150
Subhendu Ghoshae160bb2017-02-25 20:29:05 +05303151 def test_startupinfo_keywords(self):
3152 # startupinfo argument
3153 # We use hardcoded constants, because we do not want to
3154 # depend on win32all.
3155 STARTF_USERSHOWWINDOW = 1
3156 SW_MAXIMIZE = 3
3157 startupinfo = subprocess.STARTUPINFO(
3158 dwFlags=STARTF_USERSHOWWINDOW,
3159 wShowWindow=SW_MAXIMIZE
3160 )
3161 # Since Python is a console process, it won't be affected
3162 # by wShowWindow, but the argument should be silently
3163 # ignored
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003164 subprocess.call(ZERO_RETURN_CMD,
Subhendu Ghoshae160bb2017-02-25 20:29:05 +05303165 startupinfo=startupinfo)
3166
Victor Stinner483422f2018-07-05 22:54:17 +02003167 def test_startupinfo_copy(self):
3168 # bpo-34044: Popen must not modify input STARTUPINFO structure
3169 startupinfo = subprocess.STARTUPINFO()
3170 startupinfo.dwFlags = subprocess.STARTF_USESHOWWINDOW
3171 startupinfo.wShowWindow = subprocess.SW_HIDE
3172
3173 # Call Popen() twice with the same startupinfo object to make sure
3174 # that it's not modified
3175 for _ in range(2):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003176 cmd = ZERO_RETURN_CMD
Victor Stinner483422f2018-07-05 22:54:17 +02003177 with open(os.devnull, 'w') as null:
3178 proc = subprocess.Popen(cmd,
3179 stdout=null,
3180 stderr=subprocess.STDOUT,
3181 startupinfo=startupinfo)
3182 with proc:
3183 proc.communicate()
3184 self.assertEqual(proc.returncode, 0)
3185
3186 self.assertEqual(startupinfo.dwFlags,
3187 subprocess.STARTF_USESHOWWINDOW)
3188 self.assertIsNone(startupinfo.hStdInput)
3189 self.assertIsNone(startupinfo.hStdOutput)
3190 self.assertIsNone(startupinfo.hStdError)
3191 self.assertEqual(startupinfo.wShowWindow, subprocess.SW_HIDE)
3192 self.assertEqual(startupinfo.lpAttributeList, {"handle_list": []})
3193
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003194 def test_creationflags(self):
3195 # creationflags argument
3196 CREATE_NEW_CONSOLE = 16
3197 sys.stderr.write(" a DOS box should flash briefly ...\n")
3198 subprocess.call(sys.executable +
3199 ' -c "import time; time.sleep(0.25)"',
3200 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003201
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003202 def test_invalid_args(self):
3203 # invalid arguments should raise ValueError
3204 self.assertRaises(ValueError, subprocess.call,
3205 [sys.executable, "-c",
3206 "import sys; sys.exit(47)"],
3207 preexec_fn=lambda: 1)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003208
Oren Milman0b3a87e2017-09-14 22:30:28 +03003209 @support.cpython_only
3210 def test_issue31471(self):
3211 # There shouldn't be an assertion failure in Popen() in case the env
3212 # argument has a bad keys() method.
3213 class BadEnv(dict):
3214 keys = None
3215 with self.assertRaises(TypeError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003216 subprocess.Popen(ZERO_RETURN_CMD, env=BadEnv())
Oren Milman0b3a87e2017-09-14 22:30:28 +03003217
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003218 def test_close_fds(self):
3219 # close file descriptors
3220 rc = subprocess.call([sys.executable, "-c",
3221 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003222 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003223 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003224
Segev Finerb2a60832017-12-18 11:28:19 +02003225 def test_close_fds_with_stdio(self):
3226 import msvcrt
3227
3228 fds = os.pipe()
3229 self.addCleanup(os.close, fds[0])
3230 self.addCleanup(os.close, fds[1])
3231
3232 handles = []
3233 for fd in fds:
3234 os.set_inheritable(fd, True)
3235 handles.append(msvcrt.get_osfhandle(fd))
3236
3237 p = subprocess.Popen([sys.executable, "-c",
3238 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3239 stdout=subprocess.PIPE, close_fds=False)
3240 stdout, stderr = p.communicate()
3241 self.assertEqual(p.returncode, 0)
3242 int(stdout.strip()) # Check that stdout is an integer
3243
3244 p = subprocess.Popen([sys.executable, "-c",
3245 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3246 stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
3247 stdout, stderr = p.communicate()
3248 self.assertEqual(p.returncode, 1)
3249 self.assertIn(b"OSError", stderr)
3250
3251 # The same as the previous call, but with an empty handle_list
3252 handle_list = []
3253 startupinfo = subprocess.STARTUPINFO()
3254 startupinfo.lpAttributeList = {"handle_list": handle_list}
3255 p = subprocess.Popen([sys.executable, "-c",
3256 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3257 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
3258 startupinfo=startupinfo, close_fds=True)
3259 stdout, stderr = p.communicate()
3260 self.assertEqual(p.returncode, 1)
3261 self.assertIn(b"OSError", stderr)
3262
3263 # Check for a warning due to using handle_list and close_fds=False
3264 with support.check_warnings((".*overriding close_fds", RuntimeWarning)):
3265 startupinfo = subprocess.STARTUPINFO()
3266 startupinfo.lpAttributeList = {"handle_list": handles[:]}
3267 p = subprocess.Popen([sys.executable, "-c",
3268 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3269 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
3270 startupinfo=startupinfo, close_fds=False)
3271 stdout, stderr = p.communicate()
3272 self.assertEqual(p.returncode, 0)
3273
3274 def test_empty_attribute_list(self):
3275 startupinfo = subprocess.STARTUPINFO()
3276 startupinfo.lpAttributeList = {}
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003277 subprocess.call(ZERO_RETURN_CMD,
Segev Finerb2a60832017-12-18 11:28:19 +02003278 startupinfo=startupinfo)
3279
3280 def test_empty_handle_list(self):
3281 startupinfo = subprocess.STARTUPINFO()
3282 startupinfo.lpAttributeList = {"handle_list": []}
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003283 subprocess.call(ZERO_RETURN_CMD,
Segev Finerb2a60832017-12-18 11:28:19 +02003284 startupinfo=startupinfo)
3285
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003286 def test_shell_sequence(self):
3287 # Run command through the shell (sequence)
3288 newenv = os.environ.copy()
3289 newenv["FRUIT"] = "physalis"
3290 p = subprocess.Popen(["set"], shell=1,
3291 stdout=subprocess.PIPE,
3292 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02003293 with p:
3294 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00003295
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003296 def test_shell_string(self):
3297 # Run command through the shell (string)
3298 newenv = os.environ.copy()
3299 newenv["FRUIT"] = "physalis"
3300 p = subprocess.Popen("set", shell=1,
3301 stdout=subprocess.PIPE,
3302 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02003303 with p:
3304 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003305
Steve Dower050acae2016-09-06 20:16:17 -07003306 def test_shell_encodings(self):
3307 # Run command through the shell (string)
3308 for enc in ['ansi', 'oem']:
3309 newenv = os.environ.copy()
3310 newenv["FRUIT"] = "physalis"
3311 p = subprocess.Popen("set", shell=1,
3312 stdout=subprocess.PIPE,
3313 env=newenv,
3314 encoding=enc)
3315 with p:
3316 self.assertIn("physalis", p.stdout.read(), enc)
3317
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003318 def test_call_string(self):
3319 # call() function with string argument on Windows
3320 rc = subprocess.call(sys.executable +
3321 ' -c "import sys; sys.exit(47)"')
3322 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003323
Florent Xicluna4886d242010-03-08 13:27:26 +00003324 def _kill_process(self, method, *args):
3325 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00003326 p = subprocess.Popen([sys.executable, "-c", """if 1:
3327 import sys, time
3328 sys.stdout.write('x\\n')
3329 sys.stdout.flush()
3330 time.sleep(30)
3331 """],
3332 stdin=subprocess.PIPE,
3333 stdout=subprocess.PIPE,
3334 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02003335 with p:
3336 # Wait for the interpreter to be completely initialized before
3337 # sending any signal.
3338 p.stdout.read(1)
3339 getattr(p, method)(*args)
3340 _, stderr = p.communicate()
3341 self.assertStderrEqual(stderr, b'')
3342 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00003343 self.assertNotEqual(returncode, 0)
3344
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003345 def _kill_dead_process(self, method, *args):
3346 p = subprocess.Popen([sys.executable, "-c", """if 1:
3347 import sys, time
3348 sys.stdout.write('x\\n')
3349 sys.stdout.flush()
3350 sys.exit(42)
3351 """],
3352 stdin=subprocess.PIPE,
3353 stdout=subprocess.PIPE,
3354 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02003355 with p:
3356 # Wait for the interpreter to be completely initialized before
3357 # sending any signal.
3358 p.stdout.read(1)
3359 # The process should end after this
3360 time.sleep(1)
3361 # This shouldn't raise even though the child is now dead
3362 getattr(p, method)(*args)
3363 _, stderr = p.communicate()
3364 self.assertStderrEqual(stderr, b'')
3365 rc = p.wait()
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003366 self.assertEqual(rc, 42)
3367
Florent Xicluna4886d242010-03-08 13:27:26 +00003368 def test_send_signal(self):
3369 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00003370
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003371 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00003372 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00003373
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003374 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00003375 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00003376
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003377 def test_send_signal_dead(self):
3378 self._kill_dead_process('send_signal', signal.SIGTERM)
3379
3380 def test_kill_dead(self):
3381 self._kill_dead_process('kill')
3382
3383 def test_terminate_dead(self):
3384 self._kill_dead_process('terminate')
3385
Martin Panter23172bd2016-04-16 11:28:10 +00003386class MiscTests(unittest.TestCase):
Gregory P. Smithf4d644f2018-01-29 21:27:39 -08003387
3388 class RecordingPopen(subprocess.Popen):
3389 """A Popen that saves a reference to each instance for testing."""
3390 instances_created = []
3391
3392 def __init__(self, *args, **kwargs):
3393 super().__init__(*args, **kwargs)
3394 self.instances_created.append(self)
3395
3396 @mock.patch.object(subprocess.Popen, "_communicate")
3397 def _test_keyboardinterrupt_no_kill(self, popener, mock__communicate,
3398 **kwargs):
3399 """Fake a SIGINT happening during Popen._communicate() and ._wait().
3400
3401 This avoids the need to actually try and get test environments to send
3402 and receive signals reliably across platforms. The net effect of a ^C
3403 happening during a blocking subprocess execution which we want to clean
3404 up from is a KeyboardInterrupt coming out of communicate() or wait().
3405 """
3406
3407 mock__communicate.side_effect = KeyboardInterrupt
3408 try:
3409 with mock.patch.object(subprocess.Popen, "_wait") as mock__wait:
3410 # We patch out _wait() as no signal was involved so the
3411 # child process isn't actually going to exit rapidly.
3412 mock__wait.side_effect = KeyboardInterrupt
3413 with mock.patch.object(subprocess, "Popen",
3414 self.RecordingPopen):
3415 with self.assertRaises(KeyboardInterrupt):
3416 popener([sys.executable, "-c",
3417 "import time\ntime.sleep(9)\nimport sys\n"
3418 "sys.stderr.write('\\n!runaway child!\\n')"],
3419 stdout=subprocess.DEVNULL, **kwargs)
3420 for call in mock__wait.call_args_list[1:]:
3421 self.assertNotEqual(
3422 call, mock.call(timeout=None),
3423 "no open-ended wait() after the first allowed: "
3424 f"{mock__wait.call_args_list}")
3425 sigint_calls = []
3426 for call in mock__wait.call_args_list:
3427 if call == mock.call(timeout=0.25): # from Popen.__init__
3428 sigint_calls.append(call)
3429 self.assertLessEqual(mock__wait.call_count, 2,
3430 msg=mock__wait.call_args_list)
3431 self.assertEqual(len(sigint_calls), 1,
3432 msg=mock__wait.call_args_list)
3433 finally:
3434 # cleanup the forgotten (due to our mocks) child process
3435 process = self.RecordingPopen.instances_created.pop()
3436 process.kill()
3437 process.wait()
3438 self.assertEqual([], self.RecordingPopen.instances_created)
3439
3440 def test_call_keyboardinterrupt_no_kill(self):
3441 self._test_keyboardinterrupt_no_kill(subprocess.call, timeout=6.282)
3442
3443 def test_run_keyboardinterrupt_no_kill(self):
3444 self._test_keyboardinterrupt_no_kill(subprocess.run, timeout=6.282)
3445
3446 def test_context_manager_keyboardinterrupt_no_kill(self):
3447 def popen_via_context_manager(*args, **kwargs):
3448 with subprocess.Popen(*args, **kwargs) as unused_process:
3449 raise KeyboardInterrupt # Test how __exit__ handles ^C.
3450 self._test_keyboardinterrupt_no_kill(popen_via_context_manager)
3451
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003452 def test_getoutput(self):
3453 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
3454 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
3455 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00003456
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003457 # we use mkdtemp in the next line to create an empty directory
3458 # under our exclusive control; from that, we can invent a pathname
3459 # that we _know_ won't exist. This is guaranteed to fail.
3460 dir = None
3461 try:
3462 dir = tempfile.mkdtemp()
3463 name = os.path.join(dir, "foo")
Tim Goldene0041752013-11-03 12:53:17 +00003464 status, output = subprocess.getstatusoutput(
Victor Stinner937ee9e2018-06-26 02:11:06 +02003465 ("type " if mswindows else "cat ") + name)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003466 self.assertNotEqual(status, 0)
3467 finally:
3468 if dir is not None:
3469 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00003470
Gregory P. Smithace55862015-04-07 15:57:54 -07003471 def test__all__(self):
3472 """Ensure that __all__ is populated properly."""
Patrick McLean2b2ead72019-09-12 10:15:44 -07003473 intentionally_excluded = {"list2cmdline", "Handle", "pwd", "grp"}
Gregory P. Smithace55862015-04-07 15:57:54 -07003474 exported = set(subprocess.__all__)
3475 possible_exports = set()
3476 import types
3477 for name, value in subprocess.__dict__.items():
3478 if name.startswith('_'):
3479 continue
3480 if isinstance(value, (types.ModuleType,)):
3481 continue
3482 possible_exports.add(name)
3483 self.assertEqual(exported, possible_exports - intentionally_excluded)
3484
3485
Martin Panter23172bd2016-04-16 11:28:10 +00003486@unittest.skipUnless(hasattr(selectors, 'PollSelector'),
3487 "Test needs selectors.PollSelector")
3488class ProcessTestCaseNoPoll(ProcessTestCase):
3489 def setUp(self):
3490 self.orig_selector = subprocess._PopenSelector
3491 subprocess._PopenSelector = selectors.SelectSelector
3492 ProcessTestCase.setUp(self)
3493
3494 def tearDown(self):
3495 subprocess._PopenSelector = self.orig_selector
3496 ProcessTestCase.tearDown(self)
3497
Gregory P. Smithd06fa472009-07-04 02:46:54 +00003498
Victor Stinner937ee9e2018-06-26 02:11:06 +02003499@unittest.skipUnless(mswindows, "Windows-specific tests")
Tim Golden126c2962010-08-11 14:20:40 +00003500class CommandsWithSpaces (BaseTestCase):
3501
3502 def setUp(self):
3503 super().setUp()
Berker Peksag16a1f282015-09-28 13:33:14 +03003504 f, fname = tempfile.mkstemp(".py", "te st")
Tim Golden126c2962010-08-11 14:20:40 +00003505 self.fname = fname.lower ()
3506 os.write(f, b"import sys;"
3507 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
3508 )
3509 os.close(f)
3510
3511 def tearDown(self):
3512 os.remove(self.fname)
3513 super().tearDown()
3514
3515 def with_spaces(self, *args, **kwargs):
3516 kwargs['stdout'] = subprocess.PIPE
3517 p = subprocess.Popen(*args, **kwargs)
Victor Stinner7438c612016-05-20 12:43:15 +02003518 with p:
3519 self.assertEqual(
3520 p.stdout.read ().decode("mbcs"),
3521 "2 [%r, 'ab cd']" % self.fname
3522 )
Tim Golden126c2962010-08-11 14:20:40 +00003523
3524 def test_shell_string_with_spaces(self):
3525 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00003526 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
3527 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00003528
3529 def test_shell_sequence_with_spaces(self):
3530 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00003531 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00003532
3533 def test_noshell_string_with_spaces(self):
3534 # call() function with string argument with spaces on Windows
3535 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
3536 "ab cd"))
3537
3538 def test_noshell_sequence_with_spaces(self):
3539 # call() function with sequence argument with spaces on Windows
3540 self.with_spaces([sys.executable, self.fname, "ab cd"])
3541
Brian Curtin79cdb662010-12-03 02:46:02 +00003542
Georg Brandla86b2622012-02-20 21:34:57 +01003543class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00003544
3545 def test_pipe(self):
3546 with subprocess.Popen([sys.executable, "-c",
3547 "import sys;"
3548 "sys.stdout.write('stdout');"
3549 "sys.stderr.write('stderr');"],
3550 stdout=subprocess.PIPE,
3551 stderr=subprocess.PIPE) as proc:
3552 self.assertEqual(proc.stdout.read(), b"stdout")
3553 self.assertStderrEqual(proc.stderr.read(), b"stderr")
3554
3555 self.assertTrue(proc.stdout.closed)
3556 self.assertTrue(proc.stderr.closed)
3557
3558 def test_returncode(self):
3559 with subprocess.Popen([sys.executable, "-c",
3560 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07003561 pass
3562 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00003563 self.assertEqual(proc.returncode, 100)
3564
3565 def test_communicate_stdin(self):
3566 with subprocess.Popen([sys.executable, "-c",
3567 "import sys;"
3568 "sys.exit(sys.stdin.read() == 'context')"],
3569 stdin=subprocess.PIPE) as proc:
3570 proc.communicate(b"context")
3571 self.assertEqual(proc.returncode, 1)
3572
3573 def test_invalid_args(self):
Victor Stinnerb31206a2018-01-25 19:06:05 +01003574 with self.assertRaises(NONEXISTING_ERRORS):
Victor Stinner9a83f652017-08-21 23:51:31 +02003575 with subprocess.Popen(NONEXISTING_CMD,
Brian Curtin79cdb662010-12-03 02:46:02 +00003576 stdout=subprocess.PIPE,
3577 stderr=subprocess.PIPE) as proc:
3578 pass
3579
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003580 def test_broken_pipe_cleanup(self):
3581 """Broken pipe error should not prevent wait() (Issue 21619)"""
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003582 proc = subprocess.Popen(ZERO_RETURN_CMD,
Victor Stinner20f4bd42015-03-05 02:38:41 +01003583 stdin=subprocess.PIPE,
Victor Stinner20f4bd42015-03-05 02:38:41 +01003584 bufsize=support.PIPE_MAX_SIZE*2)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003585 proc = proc.__enter__()
3586 # Prepare to send enough data to overflow any OS pipe buffering and
3587 # guarantee a broken pipe error. Data is held in BufferedWriter
3588 # buffer until closed.
3589 proc.stdin.write(b'x' * support.PIPE_MAX_SIZE)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003590 self.assertIsNone(proc.returncode)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003591 # EPIPE expected under POSIX; EINVAL under Windows
Serhiy Storchakacf265fd2015-02-28 13:27:54 +02003592 self.assertRaises(OSError, proc.__exit__, None, None, None)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003593 self.assertEqual(proc.returncode, 0)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003594 self.assertTrue(proc.stdin.closed)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003595
Brian Curtin79cdb662010-12-03 02:46:02 +00003596
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003597if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04003598 unittest.main()