blob: 7cf31e1f0921dc62bb67434121ea95cbbae3d38a [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 Xiclunac049d872010-03-27 22:47:23 +000088
Gregory P. Smith3d8e7762012-11-10 22:32:22 -080089class PopenTestException(Exception):
90 pass
91
92
93class PopenExecuteChildRaises(subprocess.Popen):
94 """Popen subclass for testing cleanup of subprocess.PIPE filehandles when
95 _execute_child fails.
96 """
97 def _execute_child(self, *args, **kwargs):
98 raise PopenTestException("Forced Exception for Test")
99
100
Florent Xiclunac049d872010-03-27 22:47:23 +0000101class ProcessTestCase(BaseTestCase):
102
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700103 def test_io_buffered_by_default(self):
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700104 p = subprocess.Popen(ZERO_RETURN_CMD,
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700105 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
106 stderr=subprocess.PIPE)
107 try:
108 self.assertIsInstance(p.stdin, io.BufferedIOBase)
109 self.assertIsInstance(p.stdout, io.BufferedIOBase)
110 self.assertIsInstance(p.stderr, io.BufferedIOBase)
111 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -0700112 p.stdin.close()
113 p.stdout.close()
114 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700115 p.wait()
116
117 def test_io_unbuffered_works(self):
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700118 p = subprocess.Popen(ZERO_RETURN_CMD,
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700119 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
120 stderr=subprocess.PIPE, bufsize=0)
121 try:
122 self.assertIsInstance(p.stdin, io.RawIOBase)
123 self.assertIsInstance(p.stdout, io.RawIOBase)
124 self.assertIsInstance(p.stderr, io.RawIOBase)
125 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -0700126 p.stdin.close()
127 p.stdout.close()
128 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700129 p.wait()
130
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000131 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000132 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +0000133 rc = subprocess.call([sys.executable, "-c",
134 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000135 self.assertEqual(rc, 47)
136
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400137 def test_call_timeout(self):
138 # call() function with timeout argument; we want to test that the child
139 # process gets killed when the timeout expires. If the child isn't
140 # killed, this call will deadlock since subprocess.call waits for the
141 # child.
142 self.assertRaises(subprocess.TimeoutExpired, subprocess.call,
143 [sys.executable, "-c", "while True: pass"],
144 timeout=0.1)
145
Peter Astrand454f7672005-01-01 09:36:35 +0000146 def test_check_call_zero(self):
147 # check_call() function with zero return code
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700148 rc = subprocess.check_call(ZERO_RETURN_CMD)
Peter Astrand454f7672005-01-01 09:36:35 +0000149 self.assertEqual(rc, 0)
150
151 def test_check_call_nonzero(self):
152 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000153 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +0000154 subprocess.check_call([sys.executable, "-c",
155 "import sys; sys.exit(47)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000156 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +0000157
Georg Brandlf9734072008-12-07 15:30:06 +0000158 def test_check_output(self):
159 # check_output() function with zero return code
160 output = subprocess.check_output(
161 [sys.executable, "-c", "print('BDFL')"])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000162 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000163
164 def test_check_output_nonzero(self):
165 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000166 with self.assertRaises(subprocess.CalledProcessError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000167 subprocess.check_output(
168 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000169 self.assertEqual(c.exception.returncode, 5)
Georg Brandlf9734072008-12-07 15:30:06 +0000170
171 def test_check_output_stderr(self):
172 # check_output() function stderr redirected to stdout
173 output = subprocess.check_output(
174 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
175 stderr=subprocess.STDOUT)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000176 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000177
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300178 def test_check_output_stdin_arg(self):
179 # check_output() can be called with stdin set to a file
180 tf = tempfile.TemporaryFile()
181 self.addCleanup(tf.close)
182 tf.write(b'pear')
183 tf.seek(0)
184 output = subprocess.check_output(
185 [sys.executable, "-c",
186 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
187 stdin=tf)
188 self.assertIn(b'PEAR', output)
189
190 def test_check_output_input_arg(self):
191 # check_output() can be called with input set to a string
192 output = subprocess.check_output(
193 [sys.executable, "-c",
194 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
195 input=b'pear')
196 self.assertIn(b'PEAR', output)
197
Georg Brandlf9734072008-12-07 15:30:06 +0000198 def test_check_output_stdout_arg(self):
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300199 # check_output() refuses to accept 'stdout' argument
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000200 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000201 output = subprocess.check_output(
202 [sys.executable, "-c", "print('will not be run')"],
203 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +0000204 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000205 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +0000206
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300207 def test_check_output_stdin_with_input_arg(self):
208 # check_output() refuses to accept 'stdin' with 'input'
209 tf = tempfile.TemporaryFile()
210 self.addCleanup(tf.close)
211 tf.write(b'pear')
212 tf.seek(0)
213 with self.assertRaises(ValueError) as c:
214 output = subprocess.check_output(
215 [sys.executable, "-c", "print('will not be run')"],
216 stdin=tf, input=b'hare')
217 self.fail("Expected ValueError when stdin and input args supplied.")
218 self.assertIn('stdin', c.exception.args[0])
219 self.assertIn('input', c.exception.args[0])
220
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400221 def test_check_output_timeout(self):
222 # check_output() function with timeout arg
223 with self.assertRaises(subprocess.TimeoutExpired) as c:
224 output = subprocess.check_output(
225 [sys.executable, "-c",
Victor Stinner149b1c72011-06-06 23:43:02 +0200226 "import sys, time\n"
227 "sys.stdout.write('BDFL')\n"
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400228 "sys.stdout.flush()\n"
Victor Stinner149b1c72011-06-06 23:43:02 +0200229 "time.sleep(3600)"],
Reid Klecknerda9ac722011-03-16 17:08:21 -0400230 # Some heavily loaded buildbots (sparc Debian 3.x) require
231 # this much time to start and print.
232 timeout=3)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400233 self.fail("Expected TimeoutExpired.")
234 self.assertEqual(c.exception.output, b'BDFL')
235
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000236 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000237 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000238 newenv = os.environ.copy()
239 newenv["FRUIT"] = "banana"
240 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000241 'import sys, os;'
242 'sys.exit(os.getenv("FRUIT")=="banana")'],
243 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000244 self.assertEqual(rc, 1)
245
Victor Stinner87b9bc32011-06-01 00:57:47 +0200246 def test_invalid_args(self):
247 # Popen() called with invalid arguments should raise TypeError
248 # but Popen.__del__ should not complain (issue #12085)
249 with support.captured_stderr() as s:
250 self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1)
251 argcount = subprocess.Popen.__init__.__code__.co_argcount
252 too_many_args = [0] * (argcount + 1)
253 self.assertRaises(TypeError, subprocess.Popen, *too_many_args)
254 self.assertEqual(s.getvalue(), '')
255
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000256 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000257 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000258 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000259 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000260 self.addCleanup(p.stdout.close)
261 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000262 p.wait()
263 self.assertEqual(p.stdin, None)
264
265 def test_stdout_none(self):
Ezio Melotti42a541b2013-03-11 05:53:34 +0200266 # .stdout is None when not redirected, and the child's stdout will
267 # be inherited from the parent. In order to test this we run a
268 # subprocess in a subprocess:
269 # this_test
270 # \-- subprocess created by this test (parent)
271 # \-- subprocess created by the parent subprocess (child)
272 # The parent doesn't specify stdout, so the child will use the
273 # parent's stdout. This test checks that the message printed by the
274 # child goes to the parent stdout. The parent also checks that the
275 # child's stdout is None. See #11963.
276 code = ('import sys; from subprocess import Popen, PIPE;'
277 'p = Popen([sys.executable, "-c", "print(\'test_stdout_none\')"],'
278 ' stdin=PIPE, stderr=PIPE);'
279 'p.wait(); assert p.stdout is None;')
280 p = subprocess.Popen([sys.executable, "-c", code],
281 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
282 self.addCleanup(p.stdout.close)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000283 self.addCleanup(p.stderr.close)
Ezio Melotti42a541b2013-03-11 05:53:34 +0200284 out, err = p.communicate()
285 self.assertEqual(p.returncode, 0, err)
286 self.assertEqual(out.rstrip(), b'test_stdout_none')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000287
288 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000289 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000290 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000291 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000292 self.addCleanup(p.stdout.close)
293 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000294 p.wait()
295 self.assertEqual(p.stderr, None)
296
Chris Jerdonek776cb192012-10-08 15:56:43 -0700297 def _assert_python(self, pre_args, **kwargs):
298 # We include sys.exit() to prevent the test runner from hanging
299 # whenever python is found.
300 args = pre_args + ["import sys; sys.exit(47)"]
301 p = subprocess.Popen(args, **kwargs)
302 p.wait()
303 self.assertEqual(47, p.returncode)
304
305 def test_executable(self):
306 # Check that the executable argument works.
Chris Jerdonek86b0fb22012-10-09 13:17:49 -0700307 #
308 # On Unix (non-Mac and non-Windows), Python looks at args[0] to
309 # determine where its standard library is, so we need the directory
310 # of args[0] to be valid for the Popen() call to Python to succeed.
311 # See also issue #16170 and issue #7774.
312 doesnotexist = os.path.join(os.path.dirname(sys.executable),
313 "doesnotexist")
314 self._assert_python([doesnotexist, "-c"], executable=sys.executable)
Chris Jerdonek776cb192012-10-08 15:56:43 -0700315
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +0300316 def test_bytes_executable(self):
317 doesnotexist = os.path.join(os.path.dirname(sys.executable),
318 "doesnotexist")
319 self._assert_python([doesnotexist, "-c"],
320 executable=os.fsencode(sys.executable))
321
322 def test_pathlike_executable(self):
323 doesnotexist = os.path.join(os.path.dirname(sys.executable),
324 "doesnotexist")
325 self._assert_python([doesnotexist, "-c"],
326 executable=FakePath(sys.executable))
327
Chris Jerdonek776cb192012-10-08 15:56:43 -0700328 def test_executable_takes_precedence(self):
329 # Check that the executable argument takes precedence over args[0].
330 #
331 # Verify first that the call succeeds without the executable arg.
332 pre_args = [sys.executable, "-c"]
333 self._assert_python(pre_args)
Victor Stinnerb31206a2018-01-25 19:06:05 +0100334 self.assertRaises(NONEXISTING_ERRORS,
Xavier de Gaye38c8b7d2016-11-14 17:14:42 +0100335 self._assert_python, pre_args,
Victor Stinnerb31206a2018-01-25 19:06:05 +0100336 executable=NONEXISTING_CMD[0])
Chris Jerdonek776cb192012-10-08 15:56:43 -0700337
Victor Stinner937ee9e2018-06-26 02:11:06 +0200338 @unittest.skipIf(mswindows, "executable argument replaces shell")
Chris Jerdonek776cb192012-10-08 15:56:43 -0700339 def test_executable_replaces_shell(self):
340 # Check that the executable argument replaces the default shell
341 # when shell=True.
342 self._assert_python([], executable=sys.executable, shell=True)
343
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +0300344 @unittest.skipIf(mswindows, "executable argument replaces shell")
345 def test_bytes_executable_replaces_shell(self):
346 self._assert_python([], executable=os.fsencode(sys.executable),
347 shell=True)
348
349 @unittest.skipIf(mswindows, "executable argument replaces shell")
350 def test_pathlike_executable_replaces_shell(self):
351 self._assert_python([], executable=FakePath(sys.executable),
352 shell=True)
353
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700354 # For use in the test_cwd* tests below.
355 def _normalize_cwd(self, cwd):
356 # Normalize an expected cwd (for Tru64 support).
357 # We can't use os.path.realpath since it doesn't expand Tru64 {memb}
358 # strings. See bug #1063571.
Serhiy Storchaka2a23adf2015-09-06 14:13:25 +0300359 with support.change_cwd(cwd):
360 return os.getcwd()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700361
362 # For use in the test_cwd* tests below.
363 def _split_python_path(self):
364 # Return normalized (python_dir, python_base).
365 python_path = os.path.realpath(sys.executable)
366 return os.path.split(python_path)
367
368 # For use in the test_cwd* tests below.
369 def _assert_cwd(self, expected_cwd, python_arg, **kwargs):
370 # Invoke Python via Popen, and assert that (1) the call succeeds,
371 # and that (2) the current working directory of the child process
372 # matches *expected_cwd*.
373 p = subprocess.Popen([python_arg, "-c",
374 "import os, sys; "
375 "sys.stdout.write(os.getcwd()); "
376 "sys.exit(47)"],
377 stdout=subprocess.PIPE,
378 **kwargs)
379 self.addCleanup(p.stdout.close)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000380 p.wait()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700381 self.assertEqual(47, p.returncode)
382 normcase = os.path.normcase
383 self.assertEqual(normcase(expected_cwd),
384 normcase(p.stdout.read().decode("utf-8")))
385
386 def test_cwd(self):
387 # Check that cwd changes the cwd for the child process.
388 temp_dir = tempfile.gettempdir()
389 temp_dir = self._normalize_cwd(temp_dir)
390 self._assert_cwd(temp_dir, sys.executable, cwd=temp_dir)
391
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +0300392 def test_cwd_with_bytes(self):
393 temp_dir = tempfile.gettempdir()
394 temp_dir = self._normalize_cwd(temp_dir)
395 self._assert_cwd(temp_dir, sys.executable, cwd=os.fsencode(temp_dir))
396
Sayan Chowdhuryd5c11f72017-02-26 22:36:10 +0530397 def test_cwd_with_pathlike(self):
398 temp_dir = tempfile.gettempdir()
399 temp_dir = self._normalize_cwd(temp_dir)
Serhiy Storchakab21d1552018-03-02 11:53:51 +0200400 self._assert_cwd(temp_dir, sys.executable, cwd=FakePath(temp_dir))
Sayan Chowdhuryd5c11f72017-02-26 22:36:10 +0530401
Victor Stinner937ee9e2018-06-26 02:11:06 +0200402 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700403 def test_cwd_with_relative_arg(self):
404 # Check that Popen looks for args[0] relative to cwd if args[0]
405 # is relative.
406 python_dir, python_base = self._split_python_path()
407 rel_python = os.path.join(os.curdir, python_base)
408 with support.temp_cwd() as wrong_dir:
409 # Before calling with the correct cwd, confirm that the call fails
410 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700411 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700412 [rel_python])
Chris Jerdonek28714c82012-09-30 02:15:37 -0700413 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700414 [rel_python], cwd=wrong_dir)
415 python_dir = self._normalize_cwd(python_dir)
416 self._assert_cwd(python_dir, rel_python, cwd=python_dir)
417
Victor Stinner937ee9e2018-06-26 02:11:06 +0200418 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700419 def test_cwd_with_relative_executable(self):
420 # Check that Popen looks for executable relative to cwd if executable
421 # is relative (and that executable takes precedence over args[0]).
422 python_dir, python_base = self._split_python_path()
423 rel_python = os.path.join(os.curdir, python_base)
424 doesntexist = "somethingyoudonthave"
425 with support.temp_cwd() as wrong_dir:
426 # Before calling with the correct cwd, confirm that the call fails
427 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700428 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700429 [doesntexist], executable=rel_python)
Chris Jerdonek28714c82012-09-30 02:15:37 -0700430 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700431 [doesntexist], executable=rel_python,
432 cwd=wrong_dir)
433 python_dir = self._normalize_cwd(python_dir)
434 self._assert_cwd(python_dir, doesntexist, executable=rel_python,
435 cwd=python_dir)
436
437 def test_cwd_with_absolute_arg(self):
438 # Check that Popen can find the executable when the cwd is wrong
439 # if args[0] is an absolute path.
440 python_dir, python_base = self._split_python_path()
441 abs_python = os.path.join(python_dir, python_base)
442 rel_python = os.path.join(os.curdir, python_base)
Berker Peksagce643912015-05-06 06:33:17 +0300443 with support.temp_dir() as wrong_dir:
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700444 # Before calling with an absolute path, confirm that using a
445 # relative path fails.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700446 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700447 [rel_python], cwd=wrong_dir)
448 wrong_dir = self._normalize_cwd(wrong_dir)
449 self._assert_cwd(wrong_dir, abs_python, cwd=wrong_dir)
450
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100451 @unittest.skipIf(sys.base_prefix != sys.prefix,
452 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000453 def test_executable_with_cwd(self):
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700454 python_dir, python_base = self._split_python_path()
455 python_dir = self._normalize_cwd(python_dir)
456 self._assert_cwd(python_dir, "somethingyoudonthave",
457 executable=sys.executable, cwd=python_dir)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000458
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100459 @unittest.skipIf(sys.base_prefix != sys.prefix,
460 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000461 @unittest.skipIf(sysconfig.is_python_build(),
462 "need an installed Python. See #7774")
463 def test_executable_without_cwd(self):
464 # For a normal installation, it should work without 'cwd'
465 # argument. For test runs in the build directory, see #7774.
Ned Deilye92dfbf2013-08-02 18:02:21 -0700466 self._assert_cwd(os.getcwd(), "somethingyoudonthave",
467 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000468
469 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000470 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000471 p = subprocess.Popen([sys.executable, "-c",
472 'import sys; sys.exit(sys.stdin.read() == "pear")'],
473 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000474 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000475 p.stdin.close()
476 p.wait()
477 self.assertEqual(p.returncode, 1)
478
479 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000480 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000481 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000482 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000483 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000484 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000485 os.lseek(d, 0, 0)
486 p = subprocess.Popen([sys.executable, "-c",
487 'import sys; sys.exit(sys.stdin.read() == "pear")'],
488 stdin=d)
489 p.wait()
490 self.assertEqual(p.returncode, 1)
491
492 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000493 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000494 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000495 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000496 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000497 tf.seek(0)
498 p = subprocess.Popen([sys.executable, "-c",
499 'import sys; sys.exit(sys.stdin.read() == "pear")'],
500 stdin=tf)
501 p.wait()
502 self.assertEqual(p.returncode, 1)
503
504 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000505 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000506 p = subprocess.Popen([sys.executable, "-c",
507 'import sys; sys.stdout.write("orange")'],
508 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +0200509 with p:
510 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000511
512 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000513 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000514 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000515 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000516 d = tf.fileno()
517 p = subprocess.Popen([sys.executable, "-c",
518 'import sys; sys.stdout.write("orange")'],
519 stdout=d)
520 p.wait()
521 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000522 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000523
524 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000525 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000526 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000527 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000528 p = subprocess.Popen([sys.executable, "-c",
529 'import sys; sys.stdout.write("orange")'],
530 stdout=tf)
531 p.wait()
532 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000533 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000534
535 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000536 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000537 p = subprocess.Popen([sys.executable, "-c",
538 'import sys; sys.stderr.write("strawberry")'],
539 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +0200540 with p:
Victor Stinner6cac1132019-12-08 08:38:16 +0100541 self.assertEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000542
543 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000544 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000545 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000546 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000547 d = tf.fileno()
548 p = subprocess.Popen([sys.executable, "-c",
549 'import sys; sys.stderr.write("strawberry")'],
550 stderr=d)
551 p.wait()
552 os.lseek(d, 0, 0)
Victor Stinner6cac1132019-12-08 08:38:16 +0100553 self.assertEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000554
555 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000556 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000557 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000558 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000559 p = subprocess.Popen([sys.executable, "-c",
560 'import sys; sys.stderr.write("strawberry")'],
561 stderr=tf)
562 p.wait()
563 tf.seek(0)
Victor Stinner6cac1132019-12-08 08:38:16 +0100564 self.assertEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000565
Martin Panterc7635892016-05-13 01:54:44 +0000566 def test_stderr_redirect_with_no_stdout_redirect(self):
567 # test stderr=STDOUT while stdout=None (not set)
568
569 # - grandchild prints to stderr
570 # - child redirects grandchild's stderr to its stdout
571 # - the parent should get grandchild's stderr in child's stdout
572 p = subprocess.Popen([sys.executable, "-c",
573 'import sys, subprocess;'
574 'rc = subprocess.call([sys.executable, "-c",'
575 ' "import sys;"'
576 ' "sys.stderr.write(\'42\')"],'
577 ' stderr=subprocess.STDOUT);'
578 'sys.exit(rc)'],
579 stdout=subprocess.PIPE,
580 stderr=subprocess.PIPE)
581 stdout, stderr = p.communicate()
582 #NOTE: stdout should get stderr from grandchild
Victor Stinner6cac1132019-12-08 08:38:16 +0100583 self.assertEqual(stdout, b'42')
584 self.assertEqual(stderr, b'') # should be empty
Martin Panterc7635892016-05-13 01:54:44 +0000585 self.assertEqual(p.returncode, 0)
586
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000587 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000588 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000589 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000590 'import sys;'
591 'sys.stdout.write("apple");'
592 'sys.stdout.flush();'
593 'sys.stderr.write("orange")'],
594 stdout=subprocess.PIPE,
595 stderr=subprocess.STDOUT)
Victor Stinner7438c612016-05-20 12:43:15 +0200596 with p:
Victor Stinner6cac1132019-12-08 08:38:16 +0100597 self.assertEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000598
599 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000600 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000601 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000602 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000603 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000604 'import sys;'
605 'sys.stdout.write("apple");'
606 'sys.stdout.flush();'
607 'sys.stderr.write("orange")'],
608 stdout=tf,
609 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000610 p.wait()
611 tf.seek(0)
Victor Stinner6cac1132019-12-08 08:38:16 +0100612 self.assertEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000613
Thomas Wouters89f507f2006-12-13 04:49:30 +0000614 def test_stdout_filedes_of_stdout(self):
615 # stdout is set to 1 (#1531862).
Ezio Melotti42a541b2013-03-11 05:53:34 +0200616 # To avoid printing the text on stdout, we do something similar to
617 # test_stdout_none (see above). The parent subprocess calls the child
618 # subprocess passing stdout=1, and this test uses stdout=PIPE in
619 # order to capture and check the output of the parent. See #11963.
620 code = ('import sys, subprocess; '
621 'rc = subprocess.call([sys.executable, "-c", '
622 ' "import os, sys; sys.exit(os.write(sys.stdout.fileno(), '
623 'b\'test with stdout=1\'))"], stdout=1); '
624 'assert rc == 18')
625 p = subprocess.Popen([sys.executable, "-c", code],
626 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
627 self.addCleanup(p.stdout.close)
628 self.addCleanup(p.stderr.close)
629 out, err = p.communicate()
630 self.assertEqual(p.returncode, 0, err)
631 self.assertEqual(out.rstrip(), b'test with stdout=1')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000632
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200633 def test_stdout_devnull(self):
634 p = subprocess.Popen([sys.executable, "-c",
635 'for i in range(10240):'
636 'print("x" * 1024)'],
637 stdout=subprocess.DEVNULL)
638 p.wait()
639 self.assertEqual(p.stdout, None)
640
641 def test_stderr_devnull(self):
642 p = subprocess.Popen([sys.executable, "-c",
643 'import sys\n'
644 'for i in range(10240):'
645 'sys.stderr.write("x" * 1024)'],
646 stderr=subprocess.DEVNULL)
647 p.wait()
648 self.assertEqual(p.stderr, None)
649
650 def test_stdin_devnull(self):
651 p = subprocess.Popen([sys.executable, "-c",
652 'import sys;'
653 'sys.stdin.read(1)'],
654 stdin=subprocess.DEVNULL)
655 p.wait()
656 self.assertEqual(p.stdin, None)
657
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000658 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000659 newenv = os.environ.copy()
660 newenv["FRUIT"] = "orange"
Victor Stinnerf1512a22011-06-21 17:18:38 +0200661 with subprocess.Popen([sys.executable, "-c",
662 'import sys,os;'
663 'sys.stdout.write(os.getenv("FRUIT"))'],
664 stdout=subprocess.PIPE,
665 env=newenv) as p:
666 stdout, stderr = p.communicate()
667 self.assertEqual(stdout, b"orange")
668
Victor Stinner62d51182011-06-23 01:02:25 +0200669 # Windows requires at least the SYSTEMROOT environment variable to start
670 # Python
671 @unittest.skipIf(sys.platform == 'win32',
672 'cannot test an empty env on Windows')
Gregory P. Smithb3512482017-05-30 14:40:37 -0700673 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') == 1,
674 'The Python shared library cannot be loaded '
675 'with an empty environment.')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200676 def test_empty_env(self):
Gregory P. Smithb3512482017-05-30 14:40:37 -0700677 """Verify that env={} is as empty as possible."""
678
Gregory P. Smith85aba232017-05-30 16:21:47 -0700679 def is_env_var_to_ignore(n):
Gregory P. Smithb3512482017-05-30 14:40:37 -0700680 """Determine if an environment variable is under our control."""
681 # This excludes some __CF_* and VERSIONER_* keys MacOS insists
682 # on adding even when the environment in exec is empty.
683 # Gentoo sandboxes also force LD_PRELOAD and SANDBOX_* to exist.
Gregory P. Smith85aba232017-05-30 16:21:47 -0700684 return ('VERSIONER' in n or '__CF' in n or # MacOS
Nick Coghlan6ea41862017-06-11 13:16:15 +1000685 n == 'LD_PRELOAD' or n.startswith('SANDBOX') or # Gentoo
686 n == 'LC_CTYPE') # Locale coercion triggered
Gregory P. Smithb3512482017-05-30 14:40:37 -0700687
Victor Stinnerf1512a22011-06-21 17:18:38 +0200688 with subprocess.Popen([sys.executable, "-c",
Gregory P. Smithb3512482017-05-30 14:40:37 -0700689 'import os; print(list(os.environ.keys()))'],
690 stdout=subprocess.PIPE, env={}) as p:
Victor Stinnerf1512a22011-06-21 17:18:38 +0200691 stdout, stderr = p.communicate()
Gregory P. Smithb3512482017-05-30 14:40:37 -0700692 child_env_names = eval(stdout.strip())
693 self.assertIsInstance(child_env_names, list)
694 child_env_names = [k for k in child_env_names
695 if not is_env_var_to_ignore(k)]
696 self.assertEqual(child_env_names, [])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000697
Serhiy Storchakad174d242017-06-23 19:39:27 +0300698 def test_invalid_cmd(self):
699 # null character in the command name
700 cmd = sys.executable + '\0'
701 with self.assertRaises(ValueError):
702 subprocess.Popen([cmd, "-c", "pass"])
703
704 # null character in the command argument
705 with self.assertRaises(ValueError):
706 subprocess.Popen([sys.executable, "-c", "pass#\0"])
707
708 def test_invalid_env(self):
Ville Skyttä49b27342017-08-03 09:00:59 +0300709 # null character in the environment variable name
Serhiy Storchakad174d242017-06-23 19:39:27 +0300710 newenv = os.environ.copy()
711 newenv["FRUIT\0VEGETABLE"] = "cabbage"
712 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700713 subprocess.Popen(ZERO_RETURN_CMD, env=newenv)
Serhiy Storchakad174d242017-06-23 19:39:27 +0300714
Ville Skyttä49b27342017-08-03 09:00:59 +0300715 # null character in the environment variable value
Serhiy Storchakad174d242017-06-23 19:39:27 +0300716 newenv = os.environ.copy()
717 newenv["FRUIT"] = "orange\0VEGETABLE=cabbage"
718 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700719 subprocess.Popen(ZERO_RETURN_CMD, env=newenv)
Serhiy Storchakad174d242017-06-23 19:39:27 +0300720
Ville Skyttä49b27342017-08-03 09:00:59 +0300721 # equal character in the environment variable name
Serhiy Storchakad174d242017-06-23 19:39:27 +0300722 newenv = os.environ.copy()
723 newenv["FRUIT=ORANGE"] = "lemon"
724 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700725 subprocess.Popen(ZERO_RETURN_CMD, env=newenv)
Serhiy Storchakad174d242017-06-23 19:39:27 +0300726
Ville Skyttä49b27342017-08-03 09:00:59 +0300727 # equal character in the environment variable value
Serhiy Storchakad174d242017-06-23 19:39:27 +0300728 newenv = os.environ.copy()
729 newenv["FRUIT"] = "orange=lemon"
730 with subprocess.Popen([sys.executable, "-c",
731 'import sys, os;'
732 'sys.stdout.write(os.getenv("FRUIT"))'],
733 stdout=subprocess.PIPE,
734 env=newenv) as p:
735 stdout, stderr = p.communicate()
736 self.assertEqual(stdout, b"orange=lemon")
737
Peter Astrandcbac93c2005-03-03 20:24:28 +0000738 def test_communicate_stdin(self):
739 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000740 'import sys;'
741 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000742 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000743 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000744 self.assertEqual(p.returncode, 1)
745
746 def test_communicate_stdout(self):
747 p = subprocess.Popen([sys.executable, "-c",
748 'import sys; sys.stdout.write("pineapple")'],
749 stdout=subprocess.PIPE)
750 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000751 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000752 self.assertEqual(stderr, None)
753
754 def test_communicate_stderr(self):
755 p = subprocess.Popen([sys.executable, "-c",
756 'import sys; sys.stderr.write("pineapple")'],
757 stderr=subprocess.PIPE)
758 (stdout, stderr) = p.communicate()
759 self.assertEqual(stdout, None)
Victor Stinner6cac1132019-12-08 08:38:16 +0100760 self.assertEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000761
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000762 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000763 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000764 'import sys,os;'
765 'sys.stderr.write("pineapple");'
766 'sys.stdout.write(sys.stdin.read())'],
767 stdin=subprocess.PIPE,
768 stdout=subprocess.PIPE,
769 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000770 self.addCleanup(p.stdout.close)
771 self.addCleanup(p.stderr.close)
772 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000773 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000774 self.assertEqual(stdout, b"banana")
Victor Stinner6cac1132019-12-08 08:38:16 +0100775 self.assertEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000776
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400777 def test_communicate_timeout(self):
778 p = subprocess.Popen([sys.executable, "-c",
779 'import sys,os,time;'
780 'sys.stderr.write("pineapple\\n");'
781 'time.sleep(1);'
782 'sys.stderr.write("pear\\n");'
783 'sys.stdout.write(sys.stdin.read())'],
784 universal_newlines=True,
785 stdin=subprocess.PIPE,
786 stdout=subprocess.PIPE,
787 stderr=subprocess.PIPE)
788 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
789 timeout=0.3)
790 # Make sure we can keep waiting for it, and that we get the whole output
791 # after it completes.
792 (stdout, stderr) = p.communicate()
793 self.assertEqual(stdout, "banana")
Victor Stinner6cac1132019-12-08 08:38:16 +0100794 self.assertEqual(stderr.encode(), b"pineapple\npear\n")
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400795
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700796 def test_communicate_timeout_large_output(self):
Ross Lagerwall003c7a32012-02-12 09:02:01 +0200797 # Test an expiring timeout while the child is outputting lots of data.
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400798 p = subprocess.Popen([sys.executable, "-c",
799 'import sys,os,time;'
800 'sys.stdout.write("a" * (64 * 1024));'
801 'time.sleep(0.2);'
802 'sys.stdout.write("a" * (64 * 1024));'
803 'time.sleep(0.2);'
804 'sys.stdout.write("a" * (64 * 1024));'
805 'time.sleep(0.2);'
806 'sys.stdout.write("a" * (64 * 1024));'],
807 stdout=subprocess.PIPE)
808 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
809 (stdout, _) = p.communicate()
810 self.assertEqual(len(stdout), 4 * 64 * 1024)
811
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000812 # Test for the fd leak reported in http://bugs.python.org/issue2791.
813 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000814 for stdin_pipe in (False, True):
815 for stdout_pipe in (False, True):
816 for stderr_pipe in (False, True):
817 options = {}
818 if stdin_pipe:
819 options['stdin'] = subprocess.PIPE
820 if stdout_pipe:
821 options['stdout'] = subprocess.PIPE
822 if stderr_pipe:
823 options['stderr'] = subprocess.PIPE
824 if not options:
825 continue
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700826 p = subprocess.Popen(ZERO_RETURN_CMD, **options)
Victor Stinner667d4b52010-12-25 22:40:32 +0000827 p.communicate()
828 if p.stdin is not None:
829 self.assertTrue(p.stdin.closed)
830 if p.stdout is not None:
831 self.assertTrue(p.stdout.closed)
832 if p.stderr is not None:
833 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000834
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000835 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000836 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000837 p = subprocess.Popen([sys.executable, "-c",
838 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000839 (stdout, stderr) = p.communicate()
840 self.assertEqual(stdout, None)
841 self.assertEqual(stderr, None)
842
843 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000844 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000845 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000846 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000847 x, y = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000848 os.close(x)
849 os.close(y)
850 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000851 'import sys,os;'
852 'sys.stdout.write(sys.stdin.read(47));'
Charles-François Natali2d517212011-05-29 16:36:44 +0200853 'sys.stderr.write("x" * %d);'
854 'sys.stdout.write(sys.stdin.read())' %
855 support.PIPE_MAX_SIZE],
Guido van Rossum98297ee2007-11-06 21:34:58 +0000856 stdin=subprocess.PIPE,
857 stdout=subprocess.PIPE,
858 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000859 self.addCleanup(p.stdout.close)
860 self.addCleanup(p.stderr.close)
861 self.addCleanup(p.stdin.close)
Charles-François Natali2d517212011-05-29 16:36:44 +0200862 string_to_write = b"a" * support.PIPE_MAX_SIZE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000863 (stdout, stderr) = p.communicate(string_to_write)
864 self.assertEqual(stdout, string_to_write)
865
866 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000867 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000868 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000869 'import sys,os;'
870 'sys.stdout.write(sys.stdin.read())'],
871 stdin=subprocess.PIPE,
872 stdout=subprocess.PIPE,
873 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000874 self.addCleanup(p.stdout.close)
875 self.addCleanup(p.stderr.close)
876 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000877 p.stdin.write(b"banana")
878 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000879 self.assertEqual(stdout, b"bananasplit")
Victor Stinner6cac1132019-12-08 08:38:16 +0100880 self.assertEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000881
andyclegg7fed7bd2017-10-23 03:01:19 +0100882 def test_universal_newlines_and_text(self):
883 args = [
884 sys.executable, "-c",
885 'import sys,os;' + SETBINARY +
886 'buf = sys.stdout.buffer;'
887 'buf.write(sys.stdin.readline().encode());'
888 'buf.flush();'
889 'buf.write(b"line2\\n");'
890 'buf.flush();'
891 'buf.write(sys.stdin.read().encode());'
892 'buf.flush();'
893 'buf.write(b"line4\\n");'
894 'buf.flush();'
895 'buf.write(b"line5\\r\\n");'
896 'buf.flush();'
897 'buf.write(b"line6\\r");'
898 'buf.flush();'
899 'buf.write(b"\\nline7");'
900 'buf.flush();'
901 'buf.write(b"\\nline8");']
902
903 for extra_kwarg in ('universal_newlines', 'text'):
904 p = subprocess.Popen(args, **{'stdin': subprocess.PIPE,
905 'stdout': subprocess.PIPE,
906 extra_kwarg: True})
907 with p:
908 p.stdin.write("line1\n")
909 p.stdin.flush()
910 self.assertEqual(p.stdout.readline(), "line1\n")
911 p.stdin.write("line3\n")
912 p.stdin.close()
913 self.addCleanup(p.stdout.close)
914 self.assertEqual(p.stdout.readline(),
915 "line2\n")
916 self.assertEqual(p.stdout.read(6),
917 "line3\n")
918 self.assertEqual(p.stdout.read(),
919 "line4\nline5\nline6\nline7\nline8")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000920
921 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000922 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000923 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000924 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200925 'buf = sys.stdout.buffer;'
926 'buf.write(b"line2\\n");'
927 'buf.flush();'
928 'buf.write(b"line4\\n");'
929 'buf.flush();'
930 'buf.write(b"line5\\r\\n");'
931 'buf.flush();'
932 'buf.write(b"line6\\r");'
933 'buf.flush();'
934 'buf.write(b"\\nline7");'
935 'buf.flush();'
936 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200937 stderr=subprocess.PIPE,
938 stdout=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000939 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000940 self.addCleanup(p.stdout.close)
941 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000942 (stdout, stderr) = p.communicate()
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200943 self.assertEqual(stdout,
944 "line2\nline4\nline5\nline6\nline7\nline8")
945
946 def test_universal_newlines_communicate_stdin(self):
947 # universal newlines through communicate(), with only stdin
948 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300949 'import sys,os;' + SETBINARY + textwrap.dedent('''
950 s = sys.stdin.readline()
951 assert s == "line1\\n", repr(s)
952 s = sys.stdin.read()
953 assert s == "line3\\n", repr(s)
954 ''')],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200955 stdin=subprocess.PIPE,
956 universal_newlines=1)
957 (stdout, stderr) = p.communicate("line1\nline3\n")
958 self.assertEqual(p.returncode, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000959
Andrew Svetlovf3765072012-08-14 18:35:17 +0300960 def test_universal_newlines_communicate_input_none(self):
961 # Test communicate(input=None) with universal newlines.
962 #
963 # We set stdout to PIPE because, as of this writing, a different
964 # code path is tested when the number of pipes is zero or one.
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700965 p = subprocess.Popen(ZERO_RETURN_CMD,
Andrew Svetlovf3765072012-08-14 18:35:17 +0300966 stdin=subprocess.PIPE,
967 stdout=subprocess.PIPE,
968 universal_newlines=True)
969 p.communicate()
970 self.assertEqual(p.returncode, 0)
971
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300972 def test_universal_newlines_communicate_stdin_stdout_stderr(self):
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300973 # universal newlines through communicate(), with stdin, stdout, stderr
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300974 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300975 'import sys,os;' + SETBINARY + textwrap.dedent('''
976 s = sys.stdin.buffer.readline()
977 sys.stdout.buffer.write(s)
978 sys.stdout.buffer.write(b"line2\\r")
979 sys.stderr.buffer.write(b"eline2\\n")
980 s = sys.stdin.buffer.read()
981 sys.stdout.buffer.write(s)
982 sys.stdout.buffer.write(b"line4\\n")
983 sys.stdout.buffer.write(b"line5\\r\\n")
984 sys.stderr.buffer.write(b"eline6\\r")
985 sys.stderr.buffer.write(b"eline7\\r\\nz")
986 ''')],
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300987 stdin=subprocess.PIPE,
988 stderr=subprocess.PIPE,
989 stdout=subprocess.PIPE,
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300990 universal_newlines=True)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300991 self.addCleanup(p.stdout.close)
992 self.addCleanup(p.stderr.close)
993 (stdout, stderr) = p.communicate("line1\nline3\n")
994 self.assertEqual(p.returncode, 0)
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300995 self.assertEqual("line1\nline2\nline3\nline4\nline5\n", stdout)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300996 # Python debug build push something like "[42442 refs]\n"
997 # to stderr at exit of subprocess.
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300998 self.assertTrue(stderr.startswith("eline2\neline6\neline7\n"))
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300999
Andrew Svetlov82860712012-08-19 22:13:41 +03001000 def test_universal_newlines_communicate_encodings(self):
1001 # Check that universal newlines mode works for various encodings,
1002 # in particular for encodings in the UTF-16 and UTF-32 families.
1003 # See issue #15595.
1004 #
1005 # UTF-16 and UTF-32-BE are sufficient to check both with BOM and
1006 # without, and UTF-16 and UTF-32.
1007 for encoding in ['utf-16', 'utf-32-be']:
Andrew Svetlov82860712012-08-19 22:13:41 +03001008 code = ("import sys; "
1009 r"sys.stdout.buffer.write('1\r\n2\r3\n4'.encode('%s'))" %
1010 encoding)
1011 args = [sys.executable, '-c', code]
Steve Dower050acae2016-09-06 20:16:17 -07001012 # We set stdin to be non-None because, as of this writing,
1013 # a different code path is used when the number of pipes is
1014 # zero or one.
1015 popen = subprocess.Popen(args,
1016 stdin=subprocess.PIPE,
1017 stdout=subprocess.PIPE,
1018 encoding=encoding)
1019 stdout, stderr = popen.communicate(input='')
Andrew Svetlov82860712012-08-19 22:13:41 +03001020 self.assertEqual(stdout, '1\n2\n3\n4')
1021
Steve Dower050acae2016-09-06 20:16:17 -07001022 def test_communicate_errors(self):
1023 for errors, expected in [
1024 ('ignore', ''),
1025 ('replace', '\ufffd\ufffd'),
1026 ('surrogateescape', '\udc80\udc80'),
1027 ('backslashreplace', '\\x80\\x80'),
1028 ]:
1029 code = ("import sys; "
1030 r"sys.stdout.buffer.write(b'[\x80\x80]')")
1031 args = [sys.executable, '-c', code]
1032 # We set stdin to be non-None because, as of this writing,
1033 # a different code path is used when the number of pipes is
1034 # zero or one.
1035 popen = subprocess.Popen(args,
1036 stdin=subprocess.PIPE,
1037 stdout=subprocess.PIPE,
1038 encoding='utf-8',
1039 errors=errors)
1040 stdout, stderr = popen.communicate(input='')
1041 self.assertEqual(stdout, '[{}]'.format(expected))
1042
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001043 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +00001044 # Make sure we leak no resources
Victor Stinner937ee9e2018-06-26 02:11:06 +02001045 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +00001046 max_handles = 1026 # too much for most UNIX systems
1047 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +00001048 max_handles = 2050 # too much for (at least some) Windows setups
1049 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001050 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +00001051 try:
1052 for i in range(max_handles):
1053 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001054 tmpfile = os.path.join(tmpdir, support.TESTFN)
1055 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +00001056 except OSError as e:
1057 if e.errno != errno.EMFILE:
1058 raise
1059 break
1060 else:
1061 self.skipTest("failed to reach the file descriptor limit "
1062 "(tried %d)" % max_handles)
1063 # Close a couple of them (should be enough for a subprocess)
1064 for i in range(10):
1065 os.close(handles.pop())
1066 # Loop creating some subprocesses. If one of them leaks some fds,
1067 # the next loop iteration will fail by reaching the max fd limit.
1068 for i in range(15):
1069 p = subprocess.Popen([sys.executable, "-c",
1070 "import sys;"
1071 "sys.stdout.write(sys.stdin.read())"],
1072 stdin=subprocess.PIPE,
1073 stdout=subprocess.PIPE,
1074 stderr=subprocess.PIPE)
1075 data = p.communicate(b"lime")[0]
1076 self.assertEqual(data, b"lime")
1077 finally:
1078 for h in handles:
1079 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001080 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001081
1082 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001083 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
1084 '"a b c" d e')
1085 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
1086 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +00001087 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
1088 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001089 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
1090 'a\\\\\\b "de fg" h')
1091 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
1092 'a\\\\\\"b c d')
1093 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
1094 '"a\\\\b c" d e')
1095 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
1096 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001097 self.assertEqual(subprocess.list2cmdline(['ab', '']),
1098 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001099
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001100 def test_poll(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001101 p = subprocess.Popen([sys.executable, "-c",
Ross Lagerwalle7ad4192012-02-22 06:02:07 +02001102 "import os; os.read(0, 1)"],
1103 stdin=subprocess.PIPE)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001104 self.addCleanup(p.stdin.close)
1105 self.assertIsNone(p.poll())
1106 os.write(p.stdin.fileno(), b'A')
1107 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001108 # Subsequent invocations should just return the returncode
1109 self.assertEqual(p.poll(), 0)
1110
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001111 def test_wait(self):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001112 p = subprocess.Popen(ZERO_RETURN_CMD)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001113 self.assertEqual(p.wait(), 0)
1114 # Subsequent invocations should just return the returncode
1115 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +00001116
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001117 def test_wait_timeout(self):
1118 p = subprocess.Popen([sys.executable,
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001119 "-c", "import time; time.sleep(0.3)"])
Reid Kleckner2b228f02011-03-16 16:57:54 -04001120 with self.assertRaises(subprocess.TimeoutExpired) as c:
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001121 p.wait(timeout=0.0001)
1122 self.assertIn("0.0001", str(c.exception)) # For coverage of __str__.
Victor Stinner0d63bac2019-12-11 11:30:03 +01001123 self.assertEqual(p.wait(timeout=support.SHORT_TIMEOUT), 0)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001124
Peter Astrand738131d2004-11-30 21:04:45 +00001125 def test_invalid_bufsize(self):
1126 # an invalid type of the bufsize argument should raise
1127 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001128 with self.assertRaises(TypeError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001129 subprocess.Popen(ZERO_RETURN_CMD, "orange")
Peter Astrand738131d2004-11-30 21:04:45 +00001130
Guido van Rossum46a05a72007-06-07 21:56:45 +00001131 def test_bufsize_is_none(self):
1132 # bufsize=None should be the same as bufsize=0.
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001133 p = subprocess.Popen(ZERO_RETURN_CMD, None)
Guido van Rossum46a05a72007-06-07 21:56:45 +00001134 self.assertEqual(p.wait(), 0)
1135 # Again with keyword arg
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001136 p = subprocess.Popen(ZERO_RETURN_CMD, bufsize=None)
Guido van Rossum46a05a72007-06-07 21:56:45 +00001137 self.assertEqual(p.wait(), 0)
1138
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001139 def _test_bufsize_equal_one(self, line, expected, universal_newlines):
1140 # subprocess may deadlock with bufsize=1, see issue #21332
1141 with subprocess.Popen([sys.executable, "-c", "import sys;"
1142 "sys.stdout.write(sys.stdin.readline());"
1143 "sys.stdout.flush()"],
1144 stdin=subprocess.PIPE,
1145 stdout=subprocess.PIPE,
1146 stderr=subprocess.DEVNULL,
1147 bufsize=1,
1148 universal_newlines=universal_newlines) as p:
1149 p.stdin.write(line) # expect that it flushes the line in text mode
1150 os.close(p.stdin.fileno()) # close it without flushing the buffer
1151 read_line = p.stdout.readline()
Segev Finer4d385172017-08-18 16:18:13 +03001152 with support.SuppressCrashReport():
1153 try:
1154 p.stdin.close()
1155 except OSError:
1156 pass
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001157 p.stdin = None
1158 self.assertEqual(p.returncode, 0)
1159 self.assertEqual(read_line, expected)
1160
1161 def test_bufsize_equal_one_text_mode(self):
1162 # line is flushed in text mode with bufsize=1.
1163 # we should get the full line in return
1164 line = "line\n"
1165 self._test_bufsize_equal_one(line, line, universal_newlines=True)
1166
1167 def test_bufsize_equal_one_binary_mode(self):
1168 # line is not flushed in binary mode with bufsize=1.
1169 # we should get empty response
1170 line = b'line' + os.linesep.encode() # assume ascii-based locale
Alexey Izbysheva2670562018-10-20 03:22:31 +03001171 with self.assertWarnsRegex(RuntimeWarning, 'line buffering'):
1172 self._test_bufsize_equal_one(line, b'', universal_newlines=False)
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001173
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001174 def test_leaking_fds_on_error(self):
1175 # see bug #5179: Popen leaks file descriptors to PIPEs if
1176 # the child fails to execute; this will eventually exhaust
1177 # the maximum number of open fds. 1024 seems a very common
1178 # value for that limit, but Windows has 2048, so we loop
1179 # 1024 times (each call leaked two fds).
1180 for i in range(1024):
Victor Stinnerb31206a2018-01-25 19:06:05 +01001181 with self.assertRaises(NONEXISTING_ERRORS):
Victor Stinner9a83f652017-08-21 23:51:31 +02001182 subprocess.Popen(NONEXISTING_CMD,
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001183 stdout=subprocess.PIPE,
1184 stderr=subprocess.PIPE)
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001185
Victor Stinner9a83f652017-08-21 23:51:31 +02001186 def test_nonexisting_with_pipes(self):
1187 # bpo-30121: Popen with pipes must close properly pipes on error.
1188 # Previously, os.close() was called with a Windows handle which is not
1189 # a valid file descriptor.
1190 #
1191 # Run the test in a subprocess to control how the CRT reports errors
1192 # and to get stderr content.
1193 try:
1194 import msvcrt
1195 msvcrt.CrtSetReportMode
1196 except (AttributeError, ImportError):
1197 self.skipTest("need msvcrt.CrtSetReportMode")
1198
1199 code = textwrap.dedent(f"""
1200 import msvcrt
1201 import subprocess
1202
1203 cmd = {NONEXISTING_CMD!r}
1204
1205 for report_type in [msvcrt.CRT_WARN,
1206 msvcrt.CRT_ERROR,
1207 msvcrt.CRT_ASSERT]:
1208 msvcrt.CrtSetReportMode(report_type, msvcrt.CRTDBG_MODE_FILE)
1209 msvcrt.CrtSetReportFile(report_type, msvcrt.CRTDBG_FILE_STDERR)
1210
1211 try:
Zachary Ware55376462018-02-19 14:02:38 -06001212 subprocess.Popen(cmd,
Victor Stinner9a83f652017-08-21 23:51:31 +02001213 stdout=subprocess.PIPE,
1214 stderr=subprocess.PIPE)
1215 except OSError:
1216 pass
1217 """)
1218 cmd = [sys.executable, "-c", code]
1219 proc = subprocess.Popen(cmd,
1220 stderr=subprocess.PIPE,
1221 universal_newlines=True)
1222 with proc:
1223 stderr = proc.communicate()[1]
1224 self.assertEqual(stderr, "")
1225 self.assertEqual(proc.returncode, 0)
1226
Antoine Pitroua8392712013-08-30 23:38:13 +02001227 def test_double_close_on_error(self):
1228 # Issue #18851
1229 fds = []
1230 def open_fds():
1231 for i in range(20):
1232 fds.extend(os.pipe())
1233 time.sleep(0.001)
1234 t = threading.Thread(target=open_fds)
1235 t.start()
1236 try:
1237 with self.assertRaises(EnvironmentError):
Victor Stinner9a83f652017-08-21 23:51:31 +02001238 subprocess.Popen(NONEXISTING_CMD,
Antoine Pitroua8392712013-08-30 23:38:13 +02001239 stdin=subprocess.PIPE,
1240 stdout=subprocess.PIPE,
1241 stderr=subprocess.PIPE)
1242 finally:
1243 t.join()
1244 exc = None
1245 for fd in fds:
1246 # If a double close occurred, some of those fds will
1247 # already have been closed by mistake, and os.close()
1248 # here will raise.
1249 try:
1250 os.close(fd)
1251 except OSError as e:
1252 exc = e
1253 if exc is not None:
1254 raise exc
1255
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001256 def test_threadsafe_wait(self):
1257 """Issue21291: Popen.wait() needs to be threadsafe for returncode."""
1258 proc = subprocess.Popen([sys.executable, '-c',
1259 'import time; time.sleep(12)'])
1260 self.assertEqual(proc.returncode, None)
1261 results = []
1262
1263 def kill_proc_timer_thread():
1264 results.append(('thread-start-poll-result', proc.poll()))
1265 # terminate it from the thread and wait for the result.
1266 proc.kill()
1267 proc.wait()
1268 results.append(('thread-after-kill-and-wait', proc.returncode))
1269 # this wait should be a no-op given the above.
1270 proc.wait()
1271 results.append(('thread-after-second-wait', proc.returncode))
1272
1273 # This is a timing sensitive test, the failure mode is
1274 # triggered when both the main thread and this thread are in
1275 # the wait() call at once. The delay here is to allow the
1276 # main thread to most likely be blocked in its wait() call.
1277 t = threading.Timer(0.2, kill_proc_timer_thread)
1278 t.start()
1279
Victor Stinner937ee9e2018-06-26 02:11:06 +02001280 if mswindows:
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001281 expected_errorcode = 1
1282 else:
1283 # Should be -9 because of the proc.kill() from the thread.
1284 expected_errorcode = -9
1285
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001286 # Wait for the process to finish; the thread should kill it
1287 # long before it finishes on its own. Supplying a timeout
1288 # triggers a different code path for better coverage.
Victor Stinner0d63bac2019-12-11 11:30:03 +01001289 proc.wait(timeout=support.SHORT_TIMEOUT)
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001290 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001291 msg="unexpected result in wait from main thread")
1292
1293 # This should be a no-op with no change in returncode.
1294 proc.wait()
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001295 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001296 msg="unexpected result in second main wait.")
1297
1298 t.join()
1299 # Ensure that all of the thread results are as expected.
1300 # When a race condition occurs in wait(), the returncode could
1301 # be set by the wrong thread that doesn't actually have it
1302 # leading to an incorrect value.
1303 self.assertEqual([('thread-start-poll-result', None),
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001304 ('thread-after-kill-and-wait', expected_errorcode),
1305 ('thread-after-second-wait', expected_errorcode)],
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001306 results)
1307
Victor Stinnerb3693582010-05-21 20:13:12 +00001308 def test_issue8780(self):
1309 # Ensure that stdout is inherited from the parent
1310 # if stdout=PIPE is not used
1311 code = ';'.join((
1312 'import subprocess, sys',
1313 'retcode = subprocess.call('
1314 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
1315 'assert retcode == 0'))
1316 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001317 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +00001318
Tim Goldenaf5ac392010-08-06 13:03:56 +00001319 def test_handles_closed_on_exception(self):
1320 # If CreateProcess exits with an error, ensure the
1321 # duplicate output handles are released
Berker Peksag16a1f282015-09-28 13:33:14 +03001322 ifhandle, ifname = tempfile.mkstemp()
1323 ofhandle, ofname = tempfile.mkstemp()
1324 efhandle, efname = tempfile.mkstemp()
Tim Goldenaf5ac392010-08-06 13:03:56 +00001325 try:
1326 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
1327 stderr=efhandle)
1328 except OSError:
1329 os.close(ifhandle)
1330 os.remove(ifname)
1331 os.close(ofhandle)
1332 os.remove(ofname)
1333 os.close(efhandle)
1334 os.remove(efname)
1335 self.assertFalse(os.path.exists(ifname))
1336 self.assertFalse(os.path.exists(ofname))
1337 self.assertFalse(os.path.exists(efname))
1338
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001339 def test_communicate_epipe(self):
1340 # Issue 10963: communicate() should hide EPIPE
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001341 p = subprocess.Popen(ZERO_RETURN_CMD,
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001342 stdin=subprocess.PIPE,
1343 stdout=subprocess.PIPE,
1344 stderr=subprocess.PIPE)
1345 self.addCleanup(p.stdout.close)
1346 self.addCleanup(p.stderr.close)
1347 self.addCleanup(p.stdin.close)
1348 p.communicate(b"x" * 2**20)
1349
Andrey Doroschenko645005e2019-11-17 17:08:31 +03001350 def test_repr(self):
1351 # Run a command that waits for user input, to check the repr() of
1352 # a Proc object while and after the sub-process runs.
1353 code = 'import sys; input(); sys.exit(57)'
1354 cmd = [sys.executable, '-c', code]
1355 result = "<Popen: returncode: {}"
1356
1357 with subprocess.Popen(
1358 cmd, stdin=subprocess.PIPE, universal_newlines=True) as proc:
1359 self.assertIsNone(proc.returncode)
1360 self.assertTrue(
1361 repr(proc).startswith(result.format(proc.returncode)) and
1362 repr(proc).endswith('>')
1363 )
1364
1365 proc.communicate(input='exit...\n')
1366 proc.wait()
1367
1368 self.assertIsNotNone(proc.returncode)
1369 self.assertTrue(
1370 repr(proc).startswith(result.format(proc.returncode)) and
1371 repr(proc).endswith('>')
1372 )
1373
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001374 def test_communicate_epipe_only_stdin(self):
1375 # Issue 10963: communicate() should hide EPIPE
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001376 p = subprocess.Popen(ZERO_RETURN_CMD,
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001377 stdin=subprocess.PIPE)
1378 self.addCleanup(p.stdin.close)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001379 p.wait()
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001380 p.communicate(b"x" * 2**20)
1381
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001382 @unittest.skipUnless(hasattr(signal, 'SIGUSR1'),
1383 "Requires signal.SIGUSR1")
1384 @unittest.skipUnless(hasattr(os, 'kill'),
1385 "Requires os.kill")
1386 @unittest.skipUnless(hasattr(os, 'getppid'),
1387 "Requires os.getppid")
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001388 def test_communicate_eintr(self):
1389 # Issue #12493: communicate() should handle EINTR
1390 def handler(signum, frame):
1391 pass
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001392 old_handler = signal.signal(signal.SIGUSR1, handler)
1393 self.addCleanup(signal.signal, signal.SIGUSR1, old_handler)
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001394
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001395 args = [sys.executable, "-c",
1396 'import os, signal;'
1397 'os.kill(os.getppid(), signal.SIGUSR1)']
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001398 for stream in ('stdout', 'stderr'):
1399 kw = {stream: subprocess.PIPE}
1400 with subprocess.Popen(args, **kw) as process:
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001401 # communicate() will be interrupted by SIGUSR1
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001402 process.communicate()
1403
Tim Peterse718f612004-10-12 21:51:32 +00001404
Gregory P. Smith3d8e7762012-11-10 22:32:22 -08001405 # This test is Linux-ish specific for simplicity to at least have
1406 # some coverage. It is not a platform specific bug.
1407 @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
1408 "Linux specific")
1409 def test_failed_child_execute_fd_leak(self):
1410 """Test for the fork() failure fd leak reported in issue16327."""
1411 fd_directory = '/proc/%d/fd' % os.getpid()
1412 fds_before_popen = os.listdir(fd_directory)
1413 with self.assertRaises(PopenTestException):
1414 PopenExecuteChildRaises(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001415 ZERO_RETURN_CMD, stdin=subprocess.PIPE,
Gregory P. Smith3d8e7762012-11-10 22:32:22 -08001416 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1417
1418 # NOTE: This test doesn't verify that the real _execute_child
1419 # does not close the file descriptors itself on the way out
1420 # during an exception. Code inspection has confirmed that.
1421
1422 fds_after_exception = os.listdir(fd_directory)
1423 self.assertEqual(fds_before_popen, fds_after_exception)
1424
Victor Stinner937ee9e2018-06-26 02:11:06 +02001425 @unittest.skipIf(mswindows, "behavior currently not supported on Windows")
Gregory P. Smith8621bb52017-08-24 14:58:25 -07001426 def test_file_not_found_includes_filename(self):
1427 with self.assertRaises(FileNotFoundError) as c:
1428 subprocess.call(['/opt/nonexistent_binary', 'with', 'some', 'args'])
1429 self.assertEqual(c.exception.filename, '/opt/nonexistent_binary')
1430
Victor Stinner937ee9e2018-06-26 02:11:06 +02001431 @unittest.skipIf(mswindows, "behavior currently not supported on Windows")
Gregory P. Smith8621bb52017-08-24 14:58:25 -07001432 def test_file_not_found_with_bad_cwd(self):
1433 with self.assertRaises(FileNotFoundError) as c:
1434 subprocess.Popen(['exit', '0'], cwd='/some/nonexistent/directory')
1435 self.assertEqual(c.exception.filename, '/some/nonexistent/directory')
1436
Batuhan Taşkaya4dc5a9d2019-12-30 19:02:04 +03001437 def test_class_getitems(self):
1438 self.assertIs(subprocess.Popen[bytes], subprocess.Popen)
1439 self.assertIs(subprocess.CompletedProcess[str], subprocess.CompletedProcess)
Gregory P. Smith6e730002015-04-14 16:14:25 -07001440
1441class RunFuncTestCase(BaseTestCase):
1442 def run_python(self, code, **kwargs):
1443 """Run Python code in a subprocess using subprocess.run"""
1444 argv = [sys.executable, "-c", code]
1445 return subprocess.run(argv, **kwargs)
1446
1447 def test_returncode(self):
1448 # call() function with sequence argument
1449 cp = self.run_python("import sys; sys.exit(47)")
1450 self.assertEqual(cp.returncode, 47)
1451 with self.assertRaises(subprocess.CalledProcessError):
1452 cp.check_returncode()
1453
1454 def test_check(self):
1455 with self.assertRaises(subprocess.CalledProcessError) as c:
1456 self.run_python("import sys; sys.exit(47)", check=True)
1457 self.assertEqual(c.exception.returncode, 47)
1458
1459 def test_check_zero(self):
1460 # check_returncode shouldn't raise when returncode is zero
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001461 cp = subprocess.run(ZERO_RETURN_CMD, check=True)
Gregory P. Smith6e730002015-04-14 16:14:25 -07001462 self.assertEqual(cp.returncode, 0)
1463
1464 def test_timeout(self):
1465 # run() function with timeout argument; we want to test that the child
1466 # process gets killed when the timeout expires. If the child isn't
1467 # killed, this call will deadlock since subprocess.run waits for the
1468 # child.
1469 with self.assertRaises(subprocess.TimeoutExpired):
1470 self.run_python("while True: pass", timeout=0.0001)
1471
1472 def test_capture_stdout(self):
1473 # capture stdout with zero return code
1474 cp = self.run_python("print('BDFL')", stdout=subprocess.PIPE)
1475 self.assertIn(b'BDFL', cp.stdout)
1476
1477 def test_capture_stderr(self):
1478 cp = self.run_python("import sys; sys.stderr.write('BDFL')",
1479 stderr=subprocess.PIPE)
1480 self.assertIn(b'BDFL', cp.stderr)
1481
1482 def test_check_output_stdin_arg(self):
1483 # run() can be called with stdin set to a file
1484 tf = tempfile.TemporaryFile()
1485 self.addCleanup(tf.close)
1486 tf.write(b'pear')
1487 tf.seek(0)
1488 cp = self.run_python(
1489 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1490 stdin=tf, stdout=subprocess.PIPE)
1491 self.assertIn(b'PEAR', cp.stdout)
1492
1493 def test_check_output_input_arg(self):
1494 # check_output() can be called with input set to a string
1495 cp = self.run_python(
1496 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1497 input=b'pear', stdout=subprocess.PIPE)
1498 self.assertIn(b'PEAR', cp.stdout)
1499
1500 def test_check_output_stdin_with_input_arg(self):
1501 # run() refuses to accept 'stdin' with 'input'
1502 tf = tempfile.TemporaryFile()
1503 self.addCleanup(tf.close)
1504 tf.write(b'pear')
1505 tf.seek(0)
1506 with self.assertRaises(ValueError,
1507 msg="Expected ValueError when stdin and input args supplied.") as c:
1508 output = self.run_python("print('will not be run')",
1509 stdin=tf, input=b'hare')
1510 self.assertIn('stdin', c.exception.args[0])
1511 self.assertIn('input', c.exception.args[0])
1512
1513 def test_check_output_timeout(self):
1514 with self.assertRaises(subprocess.TimeoutExpired) as c:
1515 cp = self.run_python((
1516 "import sys, time\n"
1517 "sys.stdout.write('BDFL')\n"
1518 "sys.stdout.flush()\n"
1519 "time.sleep(3600)"),
1520 # Some heavily loaded buildbots (sparc Debian 3.x) require
1521 # this much time to start and print.
1522 timeout=3, stdout=subprocess.PIPE)
1523 self.assertEqual(c.exception.output, b'BDFL')
1524 # output is aliased to stdout
1525 self.assertEqual(c.exception.stdout, b'BDFL')
1526
1527 def test_run_kwargs(self):
1528 newenv = os.environ.copy()
1529 newenv["FRUIT"] = "banana"
1530 cp = self.run_python(('import sys, os;'
1531 'sys.exit(33 if os.getenv("FRUIT")=="banana" else 31)'),
1532 env=newenv)
1533 self.assertEqual(cp.returncode, 33)
1534
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +03001535 def test_run_with_pathlike_path(self):
1536 # bpo-31961: test run(pathlike_object)
1537 # the name of a command that can be run without
Min ho Kimc4cacc82019-07-31 08:16:13 +10001538 # any arguments that exit fast
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +03001539 prog = 'tree.com' if mswindows else 'ls'
1540 path = shutil.which(prog)
1541 if path is None:
1542 self.skipTest(f'{prog} required for this test')
1543 path = FakePath(path)
1544 res = subprocess.run(path, stdout=subprocess.DEVNULL)
1545 self.assertEqual(res.returncode, 0)
1546 with self.assertRaises(TypeError):
1547 subprocess.run(path, stdout=subprocess.DEVNULL, shell=True)
1548
1549 def test_run_with_bytes_path_and_arguments(self):
1550 # bpo-31961: test run([bytes_object, b'additional arguments'])
1551 path = os.fsencode(sys.executable)
1552 args = [path, '-c', b'import sys; sys.exit(57)']
1553 res = subprocess.run(args)
1554 self.assertEqual(res.returncode, 57)
1555
1556 def test_run_with_pathlike_path_and_arguments(self):
1557 # bpo-31961: test run([pathlike_object, 'additional arguments'])
1558 path = FakePath(sys.executable)
1559 args = [path, '-c', 'import sys; sys.exit(57)']
1560 res = subprocess.run(args)
1561 self.assertEqual(res.returncode, 57)
1562
Bo Baylesce0f33d2018-01-30 00:40:39 -06001563 def test_capture_output(self):
1564 cp = self.run_python(("import sys;"
1565 "sys.stdout.write('BDFL'); "
1566 "sys.stderr.write('FLUFL')"),
1567 capture_output=True)
1568 self.assertIn(b'BDFL', cp.stdout)
1569 self.assertIn(b'FLUFL', cp.stderr)
1570
1571 def test_stdout_with_capture_output_arg(self):
1572 # run() refuses to accept 'stdout' with 'capture_output'
1573 tf = tempfile.TemporaryFile()
1574 self.addCleanup(tf.close)
1575 with self.assertRaises(ValueError,
1576 msg=("Expected ValueError when stdout and capture_output "
1577 "args supplied.")) as c:
1578 output = self.run_python("print('will not be run')",
1579 capture_output=True, stdout=tf)
1580 self.assertIn('stdout', c.exception.args[0])
1581 self.assertIn('capture_output', c.exception.args[0])
1582
1583 def test_stderr_with_capture_output_arg(self):
1584 # run() refuses to accept 'stderr' with 'capture_output'
1585 tf = tempfile.TemporaryFile()
1586 self.addCleanup(tf.close)
1587 with self.assertRaises(ValueError,
1588 msg=("Expected ValueError when stderr and capture_output "
1589 "args supplied.")) as c:
1590 output = self.run_python("print('will not be run')",
1591 capture_output=True, stderr=tf)
1592 self.assertIn('stderr', c.exception.args[0])
1593 self.assertIn('capture_output', c.exception.args[0])
1594
Gregory P. Smith580d2782019-09-11 04:23:05 -05001595 # This test _might_ wind up a bit fragile on loaded build+test machines
1596 # as it depends on the timing with wide enough margins for normal situations
1597 # but does assert that it happened "soon enough" to believe the right thing
1598 # happened.
1599 @unittest.skipIf(mswindows, "requires posix like 'sleep' shell command")
1600 def test_run_with_shell_timeout_and_capture_output(self):
1601 """Output capturing after a timeout mustn't hang forever on open filehandles."""
1602 before_secs = time.monotonic()
1603 try:
1604 subprocess.run('sleep 3', shell=True, timeout=0.1,
1605 capture_output=True) # New session unspecified.
1606 except subprocess.TimeoutExpired as exc:
1607 after_secs = time.monotonic()
1608 stacks = traceback.format_exc() # assertRaises doesn't give this.
1609 else:
1610 self.fail("TimeoutExpired not raised.")
1611 self.assertLess(after_secs - before_secs, 1.5,
1612 msg="TimeoutExpired was delayed! Bad traceback:\n```\n"
1613 f"{stacks}```")
1614
Gregory P. Smith6e730002015-04-14 16:14:25 -07001615
Gregory P. Smith693aa802019-09-13 14:43:35 +01001616def _get_test_grp_name():
Victor Stinnerfaca8552019-09-25 15:52:49 +02001617 for name_group in ('staff', 'nogroup', 'grp', 'nobody', 'nfsnobody'):
Gregory P. Smith693aa802019-09-13 14:43:35 +01001618 if grp:
1619 try:
1620 grp.getgrnam(name_group)
1621 except KeyError:
1622 continue
1623 return name_group
1624 else:
1625 raise unittest.SkipTest('No identified group name to use for this test on this platform.')
1626
1627
Victor Stinner937ee9e2018-06-26 02:11:06 +02001628@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001629class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001630
Gregory P. Smith5591b022012-10-10 03:34:47 -07001631 def setUp(self):
1632 super().setUp()
1633 self._nonexistent_dir = "/_this/pa.th/does/not/exist"
1634
1635 def _get_chdir_exception(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001636 try:
Gregory P. Smith5591b022012-10-10 03:34:47 -07001637 os.chdir(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001638 except OSError as e:
1639 # This avoids hard coding the errno value or the OS perror()
1640 # string and instead capture the exception that we want to see
1641 # below for comparison.
1642 desired_exception = e
1643 else:
Martin Pantereb995702016-07-28 01:11:04 +00001644 self.fail("chdir to nonexistent directory %s succeeded." %
Gregory P. Smith5591b022012-10-10 03:34:47 -07001645 self._nonexistent_dir)
1646 return desired_exception
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001647
Gregory P. Smith5591b022012-10-10 03:34:47 -07001648 def test_exception_cwd(self):
1649 """Test error in the child raised in the parent for a bad cwd."""
1650 desired_exception = self._get_chdir_exception()
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001651 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001652 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smith5591b022012-10-10 03:34:47 -07001653 cwd=self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001654 except OSError as e:
1655 # Test that the child process chdir failure actually makes
1656 # it up to the parent process as the correct exception.
1657 self.assertEqual(desired_exception.errno, e.errno)
1658 self.assertEqual(desired_exception.strerror, e.strerror)
Zackery Spytz73870bf2018-09-11 09:54:07 -06001659 self.assertEqual(desired_exception.filename, e.filename)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001660 else:
1661 self.fail("Expected OSError: %s" % desired_exception)
1662
Gregory P. Smith5591b022012-10-10 03:34:47 -07001663 def test_exception_bad_executable(self):
1664 """Test error in the child raised in the parent for a bad executable."""
1665 desired_exception = self._get_chdir_exception()
1666 try:
1667 p = subprocess.Popen([sys.executable, "-c", ""],
1668 executable=self._nonexistent_dir)
1669 except OSError as e:
1670 # Test that the child process exec failure actually makes
1671 # it up to the parent process as the correct exception.
1672 self.assertEqual(desired_exception.errno, e.errno)
1673 self.assertEqual(desired_exception.strerror, e.strerror)
Zackery Spytz73870bf2018-09-11 09:54:07 -06001674 self.assertEqual(desired_exception.filename, e.filename)
Gregory P. Smith5591b022012-10-10 03:34:47 -07001675 else:
1676 self.fail("Expected OSError: %s" % desired_exception)
1677
1678 def test_exception_bad_args_0(self):
1679 """Test error in the child raised in the parent for a bad args[0]."""
1680 desired_exception = self._get_chdir_exception()
1681 try:
1682 p = subprocess.Popen([self._nonexistent_dir, "-c", ""])
1683 except OSError as e:
1684 # Test that the child process exec failure actually makes
1685 # it up to the parent process as the correct exception.
1686 self.assertEqual(desired_exception.errno, e.errno)
1687 self.assertEqual(desired_exception.strerror, e.strerror)
Zackery Spytz73870bf2018-09-11 09:54:07 -06001688 self.assertEqual(desired_exception.filename, e.filename)
Gregory P. Smith5591b022012-10-10 03:34:47 -07001689 else:
1690 self.fail("Expected OSError: %s" % desired_exception)
1691
Ammar Askar3fc499b2017-09-06 02:41:30 -04001692 # We mock the __del__ method for Popen in the next two tests
1693 # because it does cleanup based on the pid returned by fork_exec
1694 # along with issuing a resource warning if it still exists. Since
1695 # we don't actually spawn a process in these tests we can forego
1696 # the destructor. An alternative would be to set _child_created to
1697 # False before the destructor is called but there is no easy way
1698 # to do that
1699 class PopenNoDestructor(subprocess.Popen):
1700 def __del__(self):
1701 pass
1702
1703 @mock.patch("subprocess._posixsubprocess.fork_exec")
1704 def test_exception_errpipe_normal(self, fork_exec):
1705 """Test error passing done through errpipe_write in the good case"""
1706 def proper_error(*args):
1707 errpipe_write = args[13]
1708 # Write the hex for the error code EISDIR: 'is a directory'
1709 err_code = '{:x}'.format(errno.EISDIR).encode()
1710 os.write(errpipe_write, b"OSError:" + err_code + b":")
1711 return 0
1712
1713 fork_exec.side_effect = proper_error
1714
Victor Stinner11045c92017-10-05 06:32:53 -07001715 with mock.patch("subprocess.os.waitpid",
1716 side_effect=ChildProcessError):
1717 with self.assertRaises(IsADirectoryError):
1718 self.PopenNoDestructor(["non_existent_command"])
Ammar Askar3fc499b2017-09-06 02:41:30 -04001719
1720 @mock.patch("subprocess._posixsubprocess.fork_exec")
1721 def test_exception_errpipe_bad_data(self, fork_exec):
1722 """Test error passing done through errpipe_write where its not
1723 in the expected format"""
1724 error_data = b"\xFF\x00\xDE\xAD"
1725 def bad_error(*args):
1726 errpipe_write = args[13]
1727 # Anything can be in the pipe, no assumptions should
1728 # be made about its encoding, so we'll write some
1729 # arbitrary hex bytes to test it out
1730 os.write(errpipe_write, error_data)
1731 return 0
1732
1733 fork_exec.side_effect = bad_error
1734
Victor Stinner11045c92017-10-05 06:32:53 -07001735 with mock.patch("subprocess.os.waitpid",
1736 side_effect=ChildProcessError):
1737 with self.assertRaises(subprocess.SubprocessError) as e:
1738 self.PopenNoDestructor(["non_existent_command"])
Ammar Askar3fc499b2017-09-06 02:41:30 -04001739
1740 self.assertIn(repr(error_data), str(e.exception))
1741
Gregory P. Smith5f3d04f2018-06-05 12:00:57 -07001742 @unittest.skipIf(not os.path.exists('/proc/self/status'),
1743 "need /proc/self/status")
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001744 def test_restore_signals(self):
Gregory P. Smith5f3d04f2018-06-05 12:00:57 -07001745 # Blindly assume that cat exists on systems with /proc/self/status...
1746 default_proc_status = subprocess.check_output(
1747 ['cat', '/proc/self/status'],
1748 restore_signals=False)
1749 for line in default_proc_status.splitlines():
1750 if line.startswith(b'SigIgn'):
1751 default_sig_ign_mask = line
1752 break
1753 else:
1754 self.skipTest("SigIgn not found in /proc/self/status.")
1755 restored_proc_status = subprocess.check_output(
1756 ['cat', '/proc/self/status'],
1757 restore_signals=True)
1758 for line in restored_proc_status.splitlines():
1759 if line.startswith(b'SigIgn'):
1760 restored_sig_ign_mask = line
1761 break
1762 self.assertNotEqual(default_sig_ign_mask, restored_sig_ign_mask,
1763 msg="restore_signals=True should've unblocked "
1764 "SIGPIPE and friends.")
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001765
1766 def test_start_new_session(self):
1767 # For code coverage of calling setsid(). We don't care if we get an
1768 # EPERM error from it depending on the test execution environment, that
1769 # still indicates that it was called.
1770 try:
1771 output = subprocess.check_output(
Victor Stinner58840432019-06-14 19:31:43 +02001772 [sys.executable, "-c", "import os; print(os.getsid(0))"],
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001773 start_new_session=True)
1774 except OSError as e:
1775 if e.errno != errno.EPERM:
1776 raise
1777 else:
Victor Stinner58840432019-06-14 19:31:43 +02001778 parent_sid = os.getsid(0)
1779 child_sid = int(output)
1780 self.assertNotEqual(parent_sid, child_sid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001781
Patrick McLean2b2ead72019-09-12 10:15:44 -07001782 @unittest.skipUnless(hasattr(os, 'setreuid'), 'no setreuid on platform')
1783 def test_user(self):
1784 # For code coverage of the user parameter. We don't care if we get an
1785 # EPERM error from it depending on the test execution environment, that
1786 # still indicates that it was called.
1787
1788 uid = os.geteuid()
1789 test_users = [65534 if uid != 65534 else 65533, uid]
1790 name_uid = "nobody" if sys.platform != 'darwin' else "unknown"
1791
1792 if pwd is not None:
Victor Stinnerf7b5d412020-03-05 14:28:40 +01001793 try:
1794 pwd.getpwnam(name_uid)
1795 test_users.append(name_uid)
1796 except KeyError:
1797 # unknown user name
1798 name_uid = None
Patrick McLean2b2ead72019-09-12 10:15:44 -07001799
1800 for user in test_users:
Victor Stinnerfaca8552019-09-25 15:52:49 +02001801 # posix_spawn() may be used with close_fds=False
1802 for close_fds in (False, True):
1803 with self.subTest(user=user, close_fds=close_fds):
1804 try:
1805 output = subprocess.check_output(
1806 [sys.executable, "-c",
1807 "import os; print(os.getuid())"],
1808 user=user,
1809 close_fds=close_fds)
1810 except PermissionError: # (EACCES, EPERM)
1811 pass
1812 except OSError as e:
1813 if e.errno not in (errno.EACCES, errno.EPERM):
1814 raise
Patrick McLean2b2ead72019-09-12 10:15:44 -07001815 else:
Victor Stinnerfaca8552019-09-25 15:52:49 +02001816 if isinstance(user, str):
1817 user_uid = pwd.getpwnam(user).pw_uid
1818 else:
1819 user_uid = user
1820 child_user = int(output)
1821 self.assertEqual(child_user, user_uid)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001822
1823 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001824 subprocess.check_call(ZERO_RETURN_CMD, user=-1)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001825
Victor Stinnerf7b5d412020-03-05 14:28:40 +01001826 if pwd is None and name_uid is not None:
Patrick McLean2b2ead72019-09-12 10:15:44 -07001827 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001828 subprocess.check_call(ZERO_RETURN_CMD, user=name_uid)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001829
1830 @unittest.skipIf(hasattr(os, 'setreuid'), 'setreuid() available on platform')
1831 def test_user_error(self):
1832 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001833 subprocess.check_call(ZERO_RETURN_CMD, user=65535)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001834
1835 @unittest.skipUnless(hasattr(os, 'setregid'), 'no setregid() on platform')
1836 def test_group(self):
1837 gid = os.getegid()
1838 group_list = [65534 if gid != 65534 else 65533]
Gregory P. Smith693aa802019-09-13 14:43:35 +01001839 name_group = _get_test_grp_name()
Patrick McLean2b2ead72019-09-12 10:15:44 -07001840
1841 if grp is not None:
1842 group_list.append(name_group)
1843
1844 for group in group_list + [gid]:
Victor Stinnerfaca8552019-09-25 15:52:49 +02001845 # posix_spawn() may be used with close_fds=False
1846 for close_fds in (False, True):
1847 with self.subTest(group=group, close_fds=close_fds):
1848 try:
1849 output = subprocess.check_output(
1850 [sys.executable, "-c",
1851 "import os; print(os.getgid())"],
1852 group=group,
1853 close_fds=close_fds)
1854 except PermissionError: # (EACCES, EPERM)
1855 pass
Patrick McLean2b2ead72019-09-12 10:15:44 -07001856 else:
Victor Stinnerfaca8552019-09-25 15:52:49 +02001857 if isinstance(group, str):
1858 group_gid = grp.getgrnam(group).gr_gid
1859 else:
1860 group_gid = group
Patrick McLean2b2ead72019-09-12 10:15:44 -07001861
Victor Stinnerfaca8552019-09-25 15:52:49 +02001862 child_group = int(output)
1863 self.assertEqual(child_group, group_gid)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001864
1865 # make sure we bomb on negative values
1866 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001867 subprocess.check_call(ZERO_RETURN_CMD, group=-1)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001868
1869 if grp is None:
1870 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001871 subprocess.check_call(ZERO_RETURN_CMD, group=name_group)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001872
1873 @unittest.skipIf(hasattr(os, 'setregid'), 'setregid() available on platform')
1874 def test_group_error(self):
1875 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001876 subprocess.check_call(ZERO_RETURN_CMD, group=65535)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001877
1878 @unittest.skipUnless(hasattr(os, 'setgroups'), 'no setgroups() on platform')
1879 def test_extra_groups(self):
1880 gid = os.getegid()
1881 group_list = [65534 if gid != 65534 else 65533]
Gregory P. Smith693aa802019-09-13 14:43:35 +01001882 name_group = _get_test_grp_name()
Patrick McLean2b2ead72019-09-12 10:15:44 -07001883 perm_error = False
1884
1885 if grp is not None:
1886 group_list.append(name_group)
1887
1888 try:
1889 output = subprocess.check_output(
1890 [sys.executable, "-c",
1891 "import os, sys, json; json.dump(os.getgroups(), sys.stdout)"],
1892 extra_groups=group_list)
1893 except OSError as ex:
1894 if ex.errno != errno.EPERM:
1895 raise
1896 perm_error = True
1897
1898 else:
1899 parent_groups = os.getgroups()
1900 child_groups = json.loads(output)
1901
1902 if grp is not None:
1903 desired_gids = [grp.getgrnam(g).gr_gid if isinstance(g, str) else g
1904 for g in group_list]
1905 else:
1906 desired_gids = group_list
1907
1908 if perm_error:
1909 self.assertEqual(set(child_groups), set(parent_groups))
1910 else:
1911 self.assertEqual(set(desired_gids), set(child_groups))
1912
1913 # make sure we bomb on negative values
1914 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001915 subprocess.check_call(ZERO_RETURN_CMD, extra_groups=[-1])
Patrick McLean2b2ead72019-09-12 10:15:44 -07001916
1917 if grp is None:
1918 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001919 subprocess.check_call(ZERO_RETURN_CMD,
Patrick McLean2b2ead72019-09-12 10:15:44 -07001920 extra_groups=[name_group])
1921
1922 @unittest.skipIf(hasattr(os, 'setgroups'), 'setgroups() available on platform')
1923 def test_extra_groups_error(self):
1924 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001925 subprocess.check_call(ZERO_RETURN_CMD, extra_groups=[])
Patrick McLean2b2ead72019-09-12 10:15:44 -07001926
Gregory P. Smithf3751ef2019-10-12 13:24:56 -07001927 @unittest.skipIf(mswindows or not hasattr(os, 'umask'),
1928 'POSIX umask() is not available.')
1929 def test_umask(self):
1930 tmpdir = None
1931 try:
1932 tmpdir = tempfile.mkdtemp()
1933 name = os.path.join(tmpdir, "beans")
1934 # We set an unusual umask in the child so as a unique mode
1935 # for us to test the child's touched file for.
1936 subprocess.check_call(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001937 [sys.executable, "-c", f"open({name!r}, 'w').close()"],
Gregory P. Smithf3751ef2019-10-12 13:24:56 -07001938 umask=0o053)
1939 # Ignore execute permissions entirely in our test,
1940 # filesystems could be mounted to ignore or force that.
1941 st_mode = os.stat(name).st_mode & 0o666
1942 expected_mode = 0o624
1943 self.assertEqual(expected_mode, st_mode,
1944 msg=f'{oct(expected_mode)} != {oct(st_mode)}')
1945 finally:
1946 if tmpdir is not None:
1947 shutil.rmtree(tmpdir)
1948
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001949 def test_run_abort(self):
1950 # returncode handles signal termination
Antoine Pitrou77e904e2013-10-08 23:04:32 +02001951 with support.SuppressCrashReport():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001952 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001953 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001954 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001955 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001956
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00001957 def test_CalledProcessError_str_signal(self):
1958 err = subprocess.CalledProcessError(-int(signal.SIGABRT), "fake cmd")
1959 error_string = str(err)
1960 # We're relying on the repr() of the signal.Signals intenum to provide
1961 # the word signal, the signal name and the numeric value.
1962 self.assertIn("signal", error_string.lower())
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)b4149062016-06-03 06:19:35 +00001963 # We're not being specific about the signal name as some signals have
1964 # multiple names and which name is revealed can vary.
1965 self.assertIn("SIG", error_string)
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00001966 self.assertIn(str(signal.SIGABRT), error_string)
1967
1968 def test_CalledProcessError_str_unknown_signal(self):
1969 err = subprocess.CalledProcessError(-9876543, "fake cmd")
1970 error_string = str(err)
1971 self.assertIn("unknown signal 9876543.", error_string)
1972
1973 def test_CalledProcessError_str_non_zero(self):
1974 err = subprocess.CalledProcessError(2, "fake cmd")
1975 error_string = str(err)
1976 self.assertIn("non-zero exit status 2.", error_string)
1977
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001978 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001979 # DISCLAIMER: Setting environment variables is *not* a good use
1980 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001981 p = subprocess.Popen([sys.executable, "-c",
1982 'import sys,os;'
1983 'sys.stdout.write(os.getenv("FRUIT"))'],
1984 stdout=subprocess.PIPE,
1985 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Victor Stinner7438c612016-05-20 12:43:15 +02001986 with p:
1987 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001988
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001989 def test_preexec_exception(self):
1990 def raise_it():
1991 raise ValueError("What if two swallows carried a coconut?")
1992 try:
1993 p = subprocess.Popen([sys.executable, "-c", ""],
1994 preexec_fn=raise_it)
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001995 except subprocess.SubprocessError as e:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001996 self.assertTrue(
1997 subprocess._posixsubprocess,
1998 "Expected a ValueError from the preexec_fn")
1999 except ValueError as e:
2000 self.assertIn("coconut", e.args[0])
2001 else:
2002 self.fail("Exception raised by preexec_fn did not make it "
2003 "to the parent process.")
2004
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002005 class _TestExecuteChildPopen(subprocess.Popen):
2006 """Used to test behavior at the end of _execute_child."""
2007 def __init__(self, testcase, *args, **kwargs):
2008 self._testcase = testcase
2009 subprocess.Popen.__init__(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08002010
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002011 def _execute_child(self, *args, **kwargs):
Gregory P. Smith12489d92012-11-11 01:37:02 -08002012 try:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002013 subprocess.Popen._execute_child(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08002014 finally:
2015 # Open a bunch of file descriptors and verify that
2016 # none of them are the same as the ones the Popen
2017 # instance is using for stdin/stdout/stderr.
2018 devzero_fds = [os.open("/dev/zero", os.O_RDONLY)
2019 for _ in range(8)]
2020 try:
2021 for fd in devzero_fds:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002022 self._testcase.assertNotIn(
2023 fd, (self.stdin.fileno(), self.stdout.fileno(),
2024 self.stderr.fileno()),
Gregory P. Smith12489d92012-11-11 01:37:02 -08002025 msg="At least one fd was closed early.")
2026 finally:
Richard Oudkerk0e547b62013-06-10 16:29:19 +01002027 for fd in devzero_fds:
2028 os.close(fd)
Gregory P. Smith12489d92012-11-11 01:37:02 -08002029
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002030 @unittest.skipIf(not os.path.exists("/dev/zero"), "/dev/zero required.")
2031 def test_preexec_errpipe_does_not_double_close_pipes(self):
2032 """Issue16140: Don't double close pipes on preexec error."""
2033
2034 def raise_it():
Gregory P. Smith65ee6ec2012-11-11 10:12:40 -08002035 raise subprocess.SubprocessError(
2036 "force the _execute_child() errpipe_data path.")
Gregory P. Smith12489d92012-11-11 01:37:02 -08002037
Gregory P. Smithc2c4cb62012-11-11 01:41:49 -08002038 with self.assertRaises(subprocess.SubprocessError):
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002039 self._TestExecuteChildPopen(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002040 self, ZERO_RETURN_CMD,
Gregory P. Smith12489d92012-11-11 01:37:02 -08002041 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2042 stderr=subprocess.PIPE, preexec_fn=raise_it)
2043
Gregory P. Smith32ec9da2010-03-19 16:53:08 +00002044 def test_preexec_gc_module_failure(self):
2045 # This tests the code that disables garbage collection if the child
2046 # process will execute any Python.
2047 def raise_runtime_error():
2048 raise RuntimeError("this shouldn't escape")
2049 enabled = gc.isenabled()
2050 orig_gc_disable = gc.disable
2051 orig_gc_isenabled = gc.isenabled
2052 try:
2053 gc.disable()
2054 self.assertFalse(gc.isenabled())
2055 subprocess.call([sys.executable, '-c', ''],
2056 preexec_fn=lambda: None)
2057 self.assertFalse(gc.isenabled(),
2058 "Popen enabled gc when it shouldn't.")
2059
2060 gc.enable()
2061 self.assertTrue(gc.isenabled())
2062 subprocess.call([sys.executable, '-c', ''],
2063 preexec_fn=lambda: None)
2064 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
2065
2066 gc.disable = raise_runtime_error
2067 self.assertRaises(RuntimeError, subprocess.Popen,
2068 [sys.executable, '-c', ''],
2069 preexec_fn=lambda: None)
2070
2071 del gc.isenabled # force an AttributeError
2072 self.assertRaises(AttributeError, subprocess.Popen,
2073 [sys.executable, '-c', ''],
2074 preexec_fn=lambda: None)
2075 finally:
2076 gc.disable = orig_gc_disable
2077 gc.isenabled = orig_gc_isenabled
2078 if not enabled:
2079 gc.disable()
2080
Martin Panterf7fdbda2015-12-05 09:51:52 +00002081 @unittest.skipIf(
2082 sys.platform == 'darwin', 'setrlimit() seems to fail on OS X')
Martin Panterafdd5132015-11-30 02:21:41 +00002083 def test_preexec_fork_failure(self):
2084 # The internal code did not preserve the previous exception when
2085 # re-enabling garbage collection
2086 try:
2087 from resource import getrlimit, setrlimit, RLIMIT_NPROC
2088 except ImportError as err:
2089 self.skipTest(err) # RLIMIT_NPROC is specific to Linux and BSD
2090 limits = getrlimit(RLIMIT_NPROC)
2091 [_, hard] = limits
2092 setrlimit(RLIMIT_NPROC, (0, hard))
2093 self.addCleanup(setrlimit, RLIMIT_NPROC, limits)
Martin Panter5cf791b2015-12-11 05:40:14 +00002094 try:
Martin Panterafdd5132015-11-30 02:21:41 +00002095 subprocess.call([sys.executable, '-c', ''],
2096 preexec_fn=lambda: None)
Martin Panter5cf791b2015-12-11 05:40:14 +00002097 except BlockingIOError:
2098 # Forking should raise EAGAIN, translated to BlockingIOError
2099 pass
2100 else:
2101 self.skipTest('RLIMIT_NPROC had no effect; probably superuser')
Martin Panterafdd5132015-11-30 02:21:41 +00002102
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002103 def test_args_string(self):
2104 # args is a string
Berker Peksag16a1f282015-09-28 13:33:14 +03002105 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002106 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00002107 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02002108 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002109 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
2110 sys.executable)
2111 os.chmod(fname, 0o700)
2112 p = subprocess.Popen(fname)
2113 p.wait()
2114 os.remove(fname)
2115 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002116
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002117 def test_invalid_args(self):
2118 # invalid arguments should raise ValueError
2119 self.assertRaises(ValueError, subprocess.call,
2120 [sys.executable, "-c",
2121 "import sys; sys.exit(47)"],
2122 startupinfo=47)
2123 self.assertRaises(ValueError, subprocess.call,
2124 [sys.executable, "-c",
2125 "import sys; sys.exit(47)"],
2126 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002127
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002128 def test_shell_sequence(self):
2129 # Run command through the shell (sequence)
2130 newenv = os.environ.copy()
2131 newenv["FRUIT"] = "apple"
2132 p = subprocess.Popen(["echo $FRUIT"], shell=1,
2133 stdout=subprocess.PIPE,
2134 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02002135 with p:
2136 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002137
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002138 def test_shell_string(self):
2139 # Run command through the shell (string)
2140 newenv = os.environ.copy()
2141 newenv["FRUIT"] = "apple"
2142 p = subprocess.Popen("echo $FRUIT", shell=1,
2143 stdout=subprocess.PIPE,
2144 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02002145 with p:
2146 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +00002147
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002148 def test_call_string(self):
2149 # call() function with string argument on UNIX
Berker Peksag16a1f282015-09-28 13:33:14 +03002150 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002151 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00002152 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02002153 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002154 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
2155 sys.executable)
2156 os.chmod(fname, 0o700)
2157 rc = subprocess.call(fname)
2158 os.remove(fname)
2159 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00002160
Stefan Krah9542cc62010-07-19 14:20:53 +00002161 def test_specific_shell(self):
2162 # Issue #9265: Incorrect name passed as arg[0].
2163 shells = []
2164 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
2165 for name in ['bash', 'ksh']:
2166 sh = os.path.join(prefix, name)
2167 if os.path.isfile(sh):
2168 shells.append(sh)
2169 if not shells: # Will probably work for any shell but csh.
2170 self.skipTest("bash or ksh required for this test")
2171 sh = '/bin/sh'
2172 if os.path.isfile(sh) and not os.path.islink(sh):
2173 # Test will fail if /bin/sh is a symlink to csh.
2174 shells.append(sh)
2175 for sh in shells:
2176 p = subprocess.Popen("echo $0", executable=sh, shell=True,
2177 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02002178 with p:
2179 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
Stefan Krah9542cc62010-07-19 14:20:53 +00002180
Florent Xicluna4886d242010-03-08 13:27:26 +00002181 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00002182 # Do not inherit file handles from the parent.
2183 # It should fix failures on some platforms.
Gregory P. Smithdee04342013-08-29 13:35:27 -07002184 # Also set the SIGINT handler to the default to make sure it's not
2185 # being ignored (some tests rely on that.)
2186 old_handler = signal.signal(signal.SIGINT, signal.default_int_handler)
2187 try:
2188 p = subprocess.Popen([sys.executable, "-c", """if 1:
2189 import sys, time
2190 sys.stdout.write('x\\n')
2191 sys.stdout.flush()
2192 time.sleep(30)
2193 """],
2194 close_fds=True,
2195 stdin=subprocess.PIPE,
2196 stdout=subprocess.PIPE,
2197 stderr=subprocess.PIPE)
2198 finally:
2199 signal.signal(signal.SIGINT, old_handler)
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00002200 # Wait for the interpreter to be completely initialized before
2201 # sending any signal.
2202 p.stdout.read(1)
2203 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00002204 return p
2205
Charles-François Natali53221e32013-01-12 16:52:20 +01002206 @unittest.skipIf(sys.platform.startswith(('netbsd', 'openbsd')),
2207 "Due to known OS bug (issue #16762)")
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002208 def _kill_dead_process(self, method, *args):
2209 # Do not inherit file handles from the parent.
2210 # It should fix failures on some platforms.
2211 p = subprocess.Popen([sys.executable, "-c", """if 1:
2212 import sys, time
2213 sys.stdout.write('x\\n')
2214 sys.stdout.flush()
2215 """],
2216 close_fds=True,
2217 stdin=subprocess.PIPE,
2218 stdout=subprocess.PIPE,
2219 stderr=subprocess.PIPE)
2220 # Wait for the interpreter to be completely initialized before
2221 # sending any signal.
2222 p.stdout.read(1)
2223 # The process should end after this
2224 time.sleep(1)
2225 # This shouldn't raise even though the child is now dead
2226 getattr(p, method)(*args)
2227 p.communicate()
2228
Florent Xicluna4886d242010-03-08 13:27:26 +00002229 def test_send_signal(self):
2230 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00002231 _, stderr = p.communicate()
2232 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002233 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00002234
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002235 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002236 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00002237 _, stderr = p.communicate()
Victor Stinner6cac1132019-12-08 08:38:16 +01002238 self.assertEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002239 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00002240
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002241 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002242 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00002243 _, stderr = p.communicate()
Victor Stinner6cac1132019-12-08 08:38:16 +01002244 self.assertEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002245 self.assertEqual(p.wait(), -signal.SIGTERM)
2246
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002247 def test_send_signal_dead(self):
2248 # Sending a signal to a dead process
2249 self._kill_dead_process('send_signal', signal.SIGINT)
2250
2251 def test_kill_dead(self):
2252 # Killing a dead process
2253 self._kill_dead_process('kill')
2254
2255 def test_terminate_dead(self):
2256 # Terminating a dead process
2257 self._kill_dead_process('terminate')
2258
Victor Stinnerdaf45552013-08-28 00:53:59 +02002259 def _save_fds(self, save_fds):
2260 fds = []
2261 for fd in save_fds:
2262 inheritable = os.get_inheritable(fd)
2263 saved = os.dup(fd)
2264 fds.append((fd, saved, inheritable))
2265 return fds
2266
2267 def _restore_fds(self, fds):
2268 for fd, saved, inheritable in fds:
2269 os.dup2(saved, fd, inheritable=inheritable)
2270 os.close(saved)
2271
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002272 def check_close_std_fds(self, fds):
2273 # Issue #9905: test that subprocess pipes still work properly with
2274 # some standard fds closed
2275 stdin = 0
Victor Stinnerdaf45552013-08-28 00:53:59 +02002276 saved_fds = self._save_fds(fds)
2277 for fd, saved, inheritable in saved_fds:
2278 if fd == 0:
2279 stdin = saved
2280 break
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002281 try:
2282 for fd in fds:
2283 os.close(fd)
2284 out, err = subprocess.Popen([sys.executable, "-c",
2285 'import sys;'
2286 'sys.stdout.write("apple");'
2287 'sys.stdout.flush();'
2288 'sys.stderr.write("orange")'],
2289 stdin=stdin,
2290 stdout=subprocess.PIPE,
2291 stderr=subprocess.PIPE).communicate()
Victor Stinner6cac1132019-12-08 08:38:16 +01002292 self.assertEqual(out, b'apple')
2293 self.assertEqual(err, b'orange')
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002294 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002295 self._restore_fds(saved_fds)
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002296
2297 def test_close_fd_0(self):
2298 self.check_close_std_fds([0])
2299
2300 def test_close_fd_1(self):
2301 self.check_close_std_fds([1])
2302
2303 def test_close_fd_2(self):
2304 self.check_close_std_fds([2])
2305
2306 def test_close_fds_0_1(self):
2307 self.check_close_std_fds([0, 1])
2308
2309 def test_close_fds_0_2(self):
2310 self.check_close_std_fds([0, 2])
2311
2312 def test_close_fds_1_2(self):
2313 self.check_close_std_fds([1, 2])
2314
2315 def test_close_fds_0_1_2(self):
2316 # Issue #10806: test that subprocess pipes still work properly with
2317 # all standard fds closed.
2318 self.check_close_std_fds([0, 1, 2])
2319
Gregory P. Smith53dd8162013-12-01 16:03:24 -08002320 def test_small_errpipe_write_fd(self):
2321 """Issue #15798: Popen should work when stdio fds are available."""
2322 new_stdin = os.dup(0)
2323 new_stdout = os.dup(1)
2324 try:
2325 os.close(0)
2326 os.close(1)
2327
2328 # Side test: if errpipe_write fails to have its CLOEXEC
2329 # flag set this should cause the parent to think the exec
2330 # failed. Extremely unlikely: everyone supports CLOEXEC.
2331 subprocess.Popen([
2332 sys.executable, "-c",
2333 "print('AssertionError:0:CLOEXEC failure.')"]).wait()
2334 finally:
2335 # Restore original stdin and stdout
2336 os.dup2(new_stdin, 0)
2337 os.dup2(new_stdout, 1)
2338 os.close(new_stdin)
2339 os.close(new_stdout)
2340
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002341 def test_remapping_std_fds(self):
2342 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03002343 temps = [tempfile.mkstemp() for i in range(3)]
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002344 try:
2345 temp_fds = [fd for fd, fname in temps]
2346
2347 # unlink the files -- we won't need to reopen them
2348 for fd, fname in temps:
2349 os.unlink(fname)
2350
2351 # write some data to what will become stdin, and rewind
2352 os.write(temp_fds[1], b"STDIN")
2353 os.lseek(temp_fds[1], 0, 0)
2354
2355 # move the standard file descriptors out of the way
Victor Stinnerdaf45552013-08-28 00:53:59 +02002356 saved_fds = self._save_fds(range(3))
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002357 try:
2358 # duplicate the file objects over the standard fd's
2359 for fd, temp_fd in enumerate(temp_fds):
2360 os.dup2(temp_fd, fd)
2361
2362 # now use those files in the "wrong" order, so that subprocess
2363 # has to rearrange them in the child
2364 p = subprocess.Popen([sys.executable, "-c",
2365 'import sys; got = sys.stdin.read();'
2366 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
2367 stdin=temp_fds[1],
2368 stdout=temp_fds[2],
2369 stderr=temp_fds[0])
2370 p.wait()
2371 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002372 self._restore_fds(saved_fds)
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002373
2374 for fd in temp_fds:
2375 os.lseek(fd, 0, 0)
2376
2377 out = os.read(temp_fds[2], 1024)
Victor Stinner6cac1132019-12-08 08:38:16 +01002378 err = os.read(temp_fds[0], 1024).strip()
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002379 self.assertEqual(out, b"got STDIN")
2380 self.assertEqual(err, b"err")
2381
2382 finally:
2383 for fd in temp_fds:
2384 os.close(fd)
2385
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002386 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
2387 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03002388 temps = [tempfile.mkstemp() for i in range(3)]
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002389 temp_fds = [fd for fd, fname in temps]
2390 try:
2391 # unlink the files -- we won't need to reopen them
2392 for fd, fname in temps:
2393 os.unlink(fname)
2394
2395 # save a copy of the standard file descriptors
Victor Stinnerdaf45552013-08-28 00:53:59 +02002396 saved_fds = self._save_fds(range(3))
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002397 try:
2398 # duplicate the temp files over the standard fd's 0, 1, 2
2399 for fd, temp_fd in enumerate(temp_fds):
2400 os.dup2(temp_fd, fd)
2401
2402 # write some data to what will become stdin, and rewind
2403 os.write(stdin_no, b"STDIN")
2404 os.lseek(stdin_no, 0, 0)
2405
2406 # now use those files in the given order, so that subprocess
2407 # has to rearrange them in the child
2408 p = subprocess.Popen([sys.executable, "-c",
2409 'import sys; got = sys.stdin.read();'
2410 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
2411 stdin=stdin_no,
2412 stdout=stdout_no,
2413 stderr=stderr_no)
2414 p.wait()
2415
2416 for fd in temp_fds:
2417 os.lseek(fd, 0, 0)
2418
2419 out = os.read(stdout_no, 1024)
Victor Stinner6cac1132019-12-08 08:38:16 +01002420 err = os.read(stderr_no, 1024).strip()
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002421 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002422 self._restore_fds(saved_fds)
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002423
2424 self.assertEqual(out, b"got STDIN")
2425 self.assertEqual(err, b"err")
2426
2427 finally:
2428 for fd in temp_fds:
2429 os.close(fd)
2430
2431 # When duping fds, if there arises a situation where one of the fds is
2432 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
2433 # This tests all combinations of this.
2434 def test_swap_fds(self):
2435 self.check_swap_fds(0, 1, 2)
2436 self.check_swap_fds(0, 2, 1)
2437 self.check_swap_fds(1, 0, 2)
2438 self.check_swap_fds(1, 2, 0)
2439 self.check_swap_fds(2, 0, 1)
2440 self.check_swap_fds(2, 1, 0)
2441
Alexey Izbyshev0e7144b2018-03-26 22:49:35 +03002442 def _check_swap_std_fds_with_one_closed(self, from_fds, to_fds):
2443 saved_fds = self._save_fds(range(3))
2444 try:
2445 for from_fd in from_fds:
2446 with tempfile.TemporaryFile() as f:
2447 os.dup2(f.fileno(), from_fd)
2448
2449 fd_to_close = (set(range(3)) - set(from_fds)).pop()
2450 os.close(fd_to_close)
2451
2452 arg_names = ['stdin', 'stdout', 'stderr']
2453 kwargs = {}
2454 for from_fd, to_fd in zip(from_fds, to_fds):
2455 kwargs[arg_names[to_fd]] = from_fd
2456
2457 code = textwrap.dedent(r'''
2458 import os, sys
2459 skipped_fd = int(sys.argv[1])
2460 for fd in range(3):
2461 if fd != skipped_fd:
2462 os.write(fd, str(fd).encode('ascii'))
2463 ''')
2464
2465 skipped_fd = (set(range(3)) - set(to_fds)).pop()
2466
2467 rc = subprocess.call([sys.executable, '-c', code, str(skipped_fd)],
2468 **kwargs)
2469 self.assertEqual(rc, 0)
2470
2471 for from_fd, to_fd in zip(from_fds, to_fds):
2472 os.lseek(from_fd, 0, os.SEEK_SET)
2473 read_bytes = os.read(from_fd, 1024)
2474 read_fds = list(map(int, read_bytes.decode('ascii')))
2475 msg = textwrap.dedent(f"""
2476 When testing {from_fds} to {to_fds} redirection,
2477 parent descriptor {from_fd} got redirected
2478 to descriptor(s) {read_fds} instead of descriptor {to_fd}.
2479 """)
2480 self.assertEqual([to_fd], read_fds, msg)
2481 finally:
2482 self._restore_fds(saved_fds)
2483
2484 # Check that subprocess can remap std fds correctly even
2485 # if one of them is closed (#32844).
2486 def test_swap_std_fds_with_one_closed(self):
2487 for from_fds in itertools.combinations(range(3), 2):
2488 for to_fds in itertools.permutations(range(3), 2):
2489 self._check_swap_std_fds_with_one_closed(from_fds, to_fds)
2490
Victor Stinner13bb71c2010-04-23 21:41:56 +00002491 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00002492 def prepare():
2493 raise ValueError("surrogate:\uDCff")
2494
2495 try:
2496 subprocess.call(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002497 ZERO_RETURN_CMD,
Victor Stinner4d078042010-04-23 19:28:32 +00002498 preexec_fn=prepare)
2499 except ValueError as err:
2500 # Pure Python implementations keeps the message
2501 self.assertIsNone(subprocess._posixsubprocess)
2502 self.assertEqual(str(err), "surrogate:\uDCff")
Gregory P. Smith8d07c262012-11-10 23:53:47 -08002503 except subprocess.SubprocessError as err:
Victor Stinner4d078042010-04-23 19:28:32 +00002504 # _posixsubprocess uses a default message
2505 self.assertIsNotNone(subprocess._posixsubprocess)
2506 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
2507 else:
Gregory P. Smith8d07c262012-11-10 23:53:47 -08002508 self.fail("Expected ValueError or subprocess.SubprocessError")
Victor Stinner4d078042010-04-23 19:28:32 +00002509
Victor Stinner13bb71c2010-04-23 21:41:56 +00002510 def test_undecodable_env(self):
2511 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner5323fb02013-11-19 23:46:06 +01002512 encoded_value = value.encode("ascii", "surrogateescape")
2513
Victor Stinner13bb71c2010-04-23 21:41:56 +00002514 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00002515 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002516 env = os.environ.copy()
2517 env[key] = value
Victor Stinner5323fb02013-11-19 23:46:06 +01002518 # Use C locale to get ASCII for the locale encoding to force
Michael Felt89d79b12018-08-26 19:29:36 +02002519 # surrogate-escaping of \xFF in the child process
Victor Stinnerebc78d22010-10-14 10:38:17 +00002520 env['LC_ALL'] = 'C'
Michael Felt89d79b12018-08-26 19:29:36 +02002521 decoded_value = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00002522 stdout = subprocess.check_output(
2523 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002524 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00002525 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01002526 self.assertEqual(stdout.decode('ascii'), ascii(decoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00002527
2528 # test bytes
2529 key = key.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00002530 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002531 env = os.environ.copy()
Victor Stinner5323fb02013-11-19 23:46:06 +01002532 env[key] = encoded_value
Victor Stinner13bb71c2010-04-23 21:41:56 +00002533 stdout = subprocess.check_output(
2534 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002535 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00002536 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01002537 self.assertEqual(stdout.decode('ascii'), ascii(encoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00002538
Victor Stinnerb745a742010-05-18 17:17:23 +00002539 def test_bytes_program(self):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002540 abs_program = os.fsencode(ZERO_RETURN_CMD[0])
2541 args = list(ZERO_RETURN_CMD[1:])
2542 path, program = os.path.split(ZERO_RETURN_CMD[0])
Victor Stinnerb745a742010-05-18 17:17:23 +00002543 program = os.fsencode(program)
2544
2545 # absolute bytes path
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002546 exitcode = subprocess.call([abs_program]+args)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002547 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002548
Victor Stinner7b3b20a2011-03-03 12:54:05 +00002549 # absolute bytes path as a string
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002550 cmd = b"'%s' %s" % (abs_program, " ".join(args).encode("utf-8"))
Victor Stinner7b3b20a2011-03-03 12:54:05 +00002551 exitcode = subprocess.call(cmd, shell=True)
2552 self.assertEqual(exitcode, 0)
2553
Victor Stinnerb745a742010-05-18 17:17:23 +00002554 # bytes program, unicode PATH
2555 env = os.environ.copy()
2556 env["PATH"] = path
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002557 exitcode = subprocess.call([program]+args, env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002558 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002559
2560 # bytes program, bytes PATH
2561 envb = os.environb.copy()
2562 envb[b"PATH"] = os.fsencode(path)
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002563 exitcode = subprocess.call([program]+args, env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002564 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002565
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002566 def test_pipe_cloexec(self):
2567 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
2568 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2569
2570 p1 = subprocess.Popen([sys.executable, sleeper],
2571 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2572 stderr=subprocess.PIPE, close_fds=False)
2573
2574 self.addCleanup(p1.communicate, b'')
2575
2576 p2 = subprocess.Popen([sys.executable, fd_status],
2577 stdout=subprocess.PIPE, close_fds=False)
2578
2579 output, error = p2.communicate()
2580 result_fds = set(map(int, output.split(b',')))
2581 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
2582 p1.stderr.fileno()])
2583
2584 self.assertFalse(result_fds & unwanted_fds,
2585 "Expected no fds from %r to be open in child, "
2586 "found %r" %
2587 (unwanted_fds, result_fds & unwanted_fds))
2588
2589 def test_pipe_cloexec_real_tools(self):
2590 qcat = support.findfile("qcat.py", subdir="subprocessdata")
2591 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
2592
2593 subdata = b'zxcvbn'
2594 data = subdata * 4 + b'\n'
2595
2596 p1 = subprocess.Popen([sys.executable, qcat],
2597 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2598 close_fds=False)
2599
2600 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
2601 stdin=p1.stdout, stdout=subprocess.PIPE,
2602 close_fds=False)
2603
2604 self.addCleanup(p1.wait)
2605 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08002606 def kill_p1():
2607 try:
2608 p1.terminate()
2609 except ProcessLookupError:
2610 pass
2611 def kill_p2():
2612 try:
2613 p2.terminate()
2614 except ProcessLookupError:
2615 pass
2616 self.addCleanup(kill_p1)
2617 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002618
2619 p1.stdin.write(data)
2620 p1.stdin.close()
2621
2622 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
2623
2624 self.assertTrue(readfiles, "The child hung")
2625 self.assertEqual(p2.stdout.read(), data)
2626
Victor Stinnerfaa8c132011-01-03 16:36:00 +00002627 p1.stdout.close()
2628 p2.stdout.close()
2629
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002630 def test_close_fds(self):
2631 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2632
2633 fds = os.pipe()
2634 self.addCleanup(os.close, fds[0])
2635 self.addCleanup(os.close, fds[1])
2636
2637 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002638 # add a bunch more fds
2639 for _ in range(9):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002640 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002641 self.addCleanup(os.close, fd)
2642 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002643
Victor Stinnerdaf45552013-08-28 00:53:59 +02002644 for fd in open_fds:
2645 os.set_inheritable(fd, True)
2646
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002647 p = subprocess.Popen([sys.executable, fd_status],
2648 stdout=subprocess.PIPE, close_fds=False)
2649 output, ignored = p.communicate()
2650 remaining_fds = set(map(int, output.split(b',')))
2651
2652 self.assertEqual(remaining_fds & open_fds, open_fds,
2653 "Some fds were closed")
2654
2655 p = subprocess.Popen([sys.executable, fd_status],
2656 stdout=subprocess.PIPE, close_fds=True)
2657 output, ignored = p.communicate()
2658 remaining_fds = set(map(int, output.split(b',')))
2659
2660 self.assertFalse(remaining_fds & open_fds,
2661 "Some fds were left open")
2662 self.assertIn(1, remaining_fds, "Subprocess failed")
2663
Gregory P. Smith8facece2012-01-21 14:01:08 -08002664 # Keep some of the fd's we opened open in the subprocess.
2665 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
2666 fds_to_keep = set(open_fds.pop() for _ in range(8))
2667 p = subprocess.Popen([sys.executable, fd_status],
2668 stdout=subprocess.PIPE, close_fds=True,
izbyshev2d8f0632017-12-19 03:26:49 +07002669 pass_fds=fds_to_keep)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002670 output, ignored = p.communicate()
2671 remaining_fds = set(map(int, output.split(b',')))
2672
izbyshev2d8f0632017-12-19 03:26:49 +07002673 self.assertFalse((remaining_fds - fds_to_keep) & open_fds,
Gregory P. Smith8facece2012-01-21 14:01:08 -08002674 "Some fds not in pass_fds were left open")
2675 self.assertIn(1, remaining_fds, "Subprocess failed")
2676
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002677
Gregory P. Smithd04f6992014-06-01 15:27:28 -07002678 @unittest.skipIf(sys.platform.startswith("freebsd") and
2679 os.stat("/dev").st_dev == os.stat("/dev/fd").st_dev,
2680 "Requires fdescfs mounted on /dev/fd on FreeBSD.")
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002681 def test_close_fds_when_max_fd_is_lowered(self):
2682 """Confirm that issue21618 is fixed (may fail under valgrind)."""
2683 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2684
Gregory P. Smith634aa682014-06-15 17:51:04 -07002685 # This launches the meat of the test in a child process to
2686 # avoid messing with the larger unittest processes maximum
2687 # number of file descriptors.
2688 # This process launches:
2689 # +--> Process that lowers its RLIMIT_NOFILE aftr setting up
2690 # a bunch of high open fds above the new lower rlimit.
2691 # Those are reported via stdout before launching a new
2692 # process with close_fds=False to run the actual test:
2693 # +--> The TEST: This one launches a fd_status.py
2694 # subprocess with close_fds=True so we can find out if
2695 # any of the fds above the lowered rlimit are still open.
2696 p = subprocess.Popen([sys.executable, '-c', textwrap.dedent(
2697 '''
2698 import os, resource, subprocess, sys, textwrap
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002699 open_fds = set()
2700 # Add a bunch more fds to pass down.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002701 for _ in range(40):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002702 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002703 open_fds.add(fd)
2704
2705 # Leave a two pairs of low ones available for use by the
2706 # internal child error pipe and the stdout pipe.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002707 # We also leave 10 more open as some Python buildbots run into
2708 # "too many open files" errors during the test if we do not.
2709 for fd in sorted(open_fds)[:14]:
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002710 os.close(fd)
2711 open_fds.remove(fd)
2712
2713 for fd in open_fds:
Gregory P. Smith634aa682014-06-15 17:51:04 -07002714 #self.addCleanup(os.close, fd)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002715 os.set_inheritable(fd, True)
2716
2717 max_fd_open = max(open_fds)
2718
Gregory P. Smith634aa682014-06-15 17:51:04 -07002719 # Communicate the open_fds to the parent unittest.TestCase process.
2720 print(','.join(map(str, sorted(open_fds))))
2721 sys.stdout.flush()
2722
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002723 rlim_cur, rlim_max = resource.getrlimit(resource.RLIMIT_NOFILE)
2724 try:
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002725 # 29 is lower than the highest fds we are leaving open.
2726 resource.setrlimit(resource.RLIMIT_NOFILE, (29, rlim_max))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002727 # Launch a new Python interpreter with our low fd rlim_cur that
2728 # inherits open fds above that limit. It then uses subprocess
2729 # with close_fds=True to get a report of open fds in the child.
2730 # An explicit list of fds to check is passed to fd_status.py as
2731 # letting fd_status rely on its default logic would miss the
2732 # fds above rlim_cur as it normally only checks up to that limit.
Gregory P. Smith634aa682014-06-15 17:51:04 -07002733 subprocess.Popen(
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002734 [sys.executable, '-c',
2735 textwrap.dedent("""
2736 import subprocess, sys
Gregory P. Smith634aa682014-06-15 17:51:04 -07002737 subprocess.Popen([sys.executable, %r] +
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002738 [str(x) for x in range({max_fd})],
Gregory P. Smithffd529c2014-06-01 13:46:54 -07002739 close_fds=True).wait()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002740 """.format(max_fd=max_fd_open+1))],
2741 close_fds=False).wait()
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002742 finally:
2743 resource.setrlimit(resource.RLIMIT_NOFILE, (rlim_cur, rlim_max))
Gregory P. Smith634aa682014-06-15 17:51:04 -07002744 ''' % fd_status)], stdout=subprocess.PIPE)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002745
2746 output, unused_stderr = p.communicate()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002747 output_lines = output.splitlines()
2748 self.assertEqual(len(output_lines), 2,
Gregory P. Smith9204e092014-06-15 20:16:01 -07002749 msg="expected exactly two lines of output:\n%r" % output)
Gregory P. Smith634aa682014-06-15 17:51:04 -07002750 opened_fds = set(map(int, output_lines[0].strip().split(b',')))
2751 remaining_fds = set(map(int, output_lines[1].strip().split(b',')))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002752
Gregory P. Smith634aa682014-06-15 17:51:04 -07002753 self.assertFalse(remaining_fds & opened_fds,
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002754 msg="Some fds were left open.")
2755
2756
Victor Stinner88701e22011-06-01 13:13:04 +02002757 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
2758 # descriptor of a pipe closed in the parent process is valid in the
2759 # child process according to fstat(), but the mode of the file
2760 # descriptor is invalid, and read or write raise an error.
2761 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002762 def test_pass_fds(self):
2763 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2764
2765 open_fds = set()
2766
2767 for x in range(5):
2768 fds = os.pipe()
2769 self.addCleanup(os.close, fds[0])
2770 self.addCleanup(os.close, fds[1])
Victor Stinnerdaf45552013-08-28 00:53:59 +02002771 os.set_inheritable(fds[0], True)
2772 os.set_inheritable(fds[1], True)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002773 open_fds.update(fds)
2774
2775 for fd in open_fds:
2776 p = subprocess.Popen([sys.executable, fd_status],
2777 stdout=subprocess.PIPE, close_fds=True,
2778 pass_fds=(fd, ))
2779 output, ignored = p.communicate()
2780
2781 remaining_fds = set(map(int, output.split(b',')))
2782 to_be_closed = open_fds - {fd}
2783
2784 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
2785 self.assertFalse(remaining_fds & to_be_closed,
2786 "fd to be closed passed")
2787
2788 # pass_fds overrides close_fds with a warning.
2789 with self.assertWarns(RuntimeWarning) as context:
2790 self.assertFalse(subprocess.call(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002791 ZERO_RETURN_CMD,
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002792 close_fds=False, pass_fds=(fd, )))
2793 self.assertIn('overriding close_fds', str(context.warning))
2794
Victor Stinnerdaf45552013-08-28 00:53:59 +02002795 def test_pass_fds_inheritable(self):
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002796 script = support.findfile("fd_status.py", subdir="subprocessdata")
Victor Stinnerdaf45552013-08-28 00:53:59 +02002797
2798 inheritable, non_inheritable = os.pipe()
2799 self.addCleanup(os.close, inheritable)
2800 self.addCleanup(os.close, non_inheritable)
2801 os.set_inheritable(inheritable, True)
2802 os.set_inheritable(non_inheritable, False)
2803 pass_fds = (inheritable, non_inheritable)
2804 args = [sys.executable, script]
2805 args += list(map(str, pass_fds))
2806
2807 p = subprocess.Popen(args,
2808 stdout=subprocess.PIPE, close_fds=True,
2809 pass_fds=pass_fds)
2810 output, ignored = p.communicate()
2811 fds = set(map(int, output.split(b',')))
2812
2813 # the inheritable file descriptor must be inherited, so its inheritable
2814 # flag must be set in the child process after fork() and before exec()
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002815 self.assertEqual(fds, set(pass_fds), "output=%a" % output)
Victor Stinnerdaf45552013-08-28 00:53:59 +02002816
2817 # inheritable flag must not be changed in the parent process
2818 self.assertEqual(os.get_inheritable(inheritable), True)
2819 self.assertEqual(os.get_inheritable(non_inheritable), False)
2820
Gregory P. Smithce344102018-09-10 17:46:22 -07002821
2822 # bpo-32270: Ensure that descriptors specified in pass_fds
2823 # are inherited even if they are used in redirections.
2824 # Contributed by @izbyshev.
2825 def test_pass_fds_redirected(self):
2826 """Regression test for https://bugs.python.org/issue32270."""
2827 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2828 pass_fds = []
2829 for _ in range(2):
2830 fd = os.open(os.devnull, os.O_RDWR)
2831 self.addCleanup(os.close, fd)
2832 pass_fds.append(fd)
2833
2834 stdout_r, stdout_w = os.pipe()
2835 self.addCleanup(os.close, stdout_r)
2836 self.addCleanup(os.close, stdout_w)
2837 pass_fds.insert(1, stdout_w)
2838
2839 with subprocess.Popen([sys.executable, fd_status],
2840 stdin=pass_fds[0],
2841 stdout=pass_fds[1],
2842 stderr=pass_fds[2],
2843 close_fds=True,
2844 pass_fds=pass_fds):
2845 output = os.read(stdout_r, 1024)
2846 fds = {int(num) for num in output.split(b',')}
2847
2848 self.assertEqual(fds, {0, 1, 2} | frozenset(pass_fds), f"output={output!a}")
2849
2850
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002851 def test_stdout_stdin_are_single_inout_fd(self):
2852 with io.open(os.devnull, "r+") as inout:
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002853 p = subprocess.Popen(ZERO_RETURN_CMD,
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002854 stdout=inout, stdin=inout)
2855 p.wait()
2856
2857 def test_stdout_stderr_are_single_inout_fd(self):
2858 with io.open(os.devnull, "r+") as inout:
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002859 p = subprocess.Popen(ZERO_RETURN_CMD,
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002860 stdout=inout, stderr=inout)
2861 p.wait()
2862
2863 def test_stderr_stdin_are_single_inout_fd(self):
2864 with io.open(os.devnull, "r+") as inout:
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002865 p = subprocess.Popen(ZERO_RETURN_CMD,
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002866 stderr=inout, stdin=inout)
2867 p.wait()
2868
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002869 def test_wait_when_sigchild_ignored(self):
2870 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
2871 sigchild_ignore = support.findfile("sigchild_ignore.py",
2872 subdir="subprocessdata")
2873 p = subprocess.Popen([sys.executable, sigchild_ignore],
2874 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
2875 stdout, stderr = p.communicate()
2876 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00002877 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00002878 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002879
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002880 def test_select_unbuffered(self):
2881 # Issue #11459: bufsize=0 should really set the pipes as
2882 # unbuffered (and therefore let select() work properly).
2883 select = support.import_module("select")
2884 p = subprocess.Popen([sys.executable, "-c",
2885 'import sys;'
2886 'sys.stdout.write("apple")'],
2887 stdout=subprocess.PIPE,
2888 bufsize=0)
2889 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02002890 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002891 try:
2892 self.assertEqual(f.read(4), b"appl")
2893 self.assertIn(f, select.select([f], [], [], 0.0)[0])
2894 finally:
2895 p.wait()
2896
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002897 def test_zombie_fast_process_del(self):
2898 # Issue #12650: on Unix, if Popen.__del__() was called before the
2899 # process exited, it wouldn't be added to subprocess._active, and would
2900 # remain a zombie.
2901 # spawn a Popen, and delete its reference before it exits
2902 p = subprocess.Popen([sys.executable, "-c",
2903 'import sys, time;'
2904 'time.sleep(0.2)'],
2905 stdout=subprocess.PIPE,
2906 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002907 self.addCleanup(p.stdout.close)
2908 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002909 ident = id(p)
2910 pid = p.pid
Victor Stinner5a48e212016-05-20 12:11:15 +02002911 with support.check_warnings(('', ResourceWarning)):
2912 p = None
2913
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +03002914 if mswindows:
2915 # subprocess._active is not used on Windows and is set to None.
2916 self.assertIsNone(subprocess._active)
2917 else:
2918 # check that p is in the active processes list
2919 self.assertIn(ident, [id(o) for o in subprocess._active])
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002920
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002921 def test_leak_fast_process_del_killed(self):
2922 # Issue #12650: on Unix, if Popen.__del__() was called before the
2923 # process exited, and the process got killed by a signal, it would never
2924 # be removed from subprocess._active, which triggered a FD and memory
2925 # leak.
2926 # spawn a Popen, delete its reference and kill it
2927 p = subprocess.Popen([sys.executable, "-c",
2928 'import time;'
2929 'time.sleep(3)'],
2930 stdout=subprocess.PIPE,
2931 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002932 self.addCleanup(p.stdout.close)
2933 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002934 ident = id(p)
2935 pid = p.pid
Victor Stinner5a48e212016-05-20 12:11:15 +02002936 with support.check_warnings(('', ResourceWarning)):
2937 p = None
2938
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002939 os.kill(pid, signal.SIGKILL)
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +03002940 if mswindows:
2941 # subprocess._active is not used on Windows and is set to None.
2942 self.assertIsNone(subprocess._active)
2943 else:
2944 # check that p is in the active processes list
2945 self.assertIn(ident, [id(o) for o in subprocess._active])
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002946
2947 # let some time for the process to exit, and create a new Popen: this
2948 # should trigger the wait() of p
2949 time.sleep(0.2)
Victor Stinnerb31206a2018-01-25 19:06:05 +01002950 with self.assertRaises(OSError):
Victor Stinner9a83f652017-08-21 23:51:31 +02002951 with subprocess.Popen(NONEXISTING_CMD,
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002952 stdout=subprocess.PIPE,
2953 stderr=subprocess.PIPE) as proc:
2954 pass
2955 # p should have been wait()ed on, and removed from the _active list
2956 self.assertRaises(OSError, os.waitpid, pid, 0)
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +03002957 if mswindows:
2958 # subprocess._active is not used on Windows and is set to None.
2959 self.assertIsNone(subprocess._active)
2960 else:
2961 self.assertNotIn(ident, [id(o) for o in subprocess._active])
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002962
Charles-François Natali249cdc32013-08-25 18:24:45 +02002963 def test_close_fds_after_preexec(self):
2964 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2965
2966 # this FD is used as dup2() target by preexec_fn, and should be closed
2967 # in the child process
2968 fd = os.dup(1)
2969 self.addCleanup(os.close, fd)
2970
2971 p = subprocess.Popen([sys.executable, fd_status],
2972 stdout=subprocess.PIPE, close_fds=True,
2973 preexec_fn=lambda: os.dup2(1, fd))
2974 output, ignored = p.communicate()
2975
2976 remaining_fds = set(map(int, output.split(b',')))
2977
2978 self.assertNotIn(fd, remaining_fds)
2979
Victor Stinner8f437aa2014-10-05 17:25:19 +02002980 @support.cpython_only
2981 def test_fork_exec(self):
2982 # Issue #22290: fork_exec() must not crash on memory allocation failure
2983 # or other errors
2984 import _posixsubprocess
2985 gc_enabled = gc.isenabled()
2986 try:
2987 # Use a preexec function and enable the garbage collector
2988 # to force fork_exec() to re-enable the garbage collector
2989 # on error.
2990 func = lambda: None
2991 gc.enable()
2992
Victor Stinner8f437aa2014-10-05 17:25:19 +02002993 for args, exe_list, cwd, env_list in (
2994 (123, [b"exe"], None, [b"env"]),
2995 ([b"arg"], 123, None, [b"env"]),
2996 ([b"arg"], [b"exe"], 123, [b"env"]),
2997 ([b"arg"], [b"exe"], None, 123),
2998 ):
Patrick McLean2b2ead72019-09-12 10:15:44 -07002999 with self.assertRaises(TypeError) as err:
Victor Stinner8f437aa2014-10-05 17:25:19 +02003000 _posixsubprocess.fork_exec(
3001 args, exe_list,
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03003002 True, (), cwd, env_list,
Victor Stinner8f437aa2014-10-05 17:25:19 +02003003 -1, -1, -1, -1,
3004 1, 2, 3, 4,
Patrick McLean2b2ead72019-09-12 10:15:44 -07003005 True, True,
Gregory P. Smithf3751ef2019-10-12 13:24:56 -07003006 False, [], 0, -1,
Patrick McLean2b2ead72019-09-12 10:15:44 -07003007 func)
3008 # Attempt to prevent
3009 # "TypeError: fork_exec() takes exactly N arguments (M given)"
3010 # from passing the test. More refactoring to have us start
3011 # with a valid *args list, confirm a good call with that works
3012 # before mutating it in various ways to ensure that bad calls
3013 # with individual arg type errors raise a typeerror would be
3014 # ideal. Saving that for a future PR...
3015 self.assertNotIn('takes exactly', str(err.exception))
Victor Stinner8f437aa2014-10-05 17:25:19 +02003016 finally:
3017 if not gc_enabled:
3018 gc.disable()
3019
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08003020 @support.cpython_only
3021 def test_fork_exec_sorted_fd_sanity_check(self):
3022 # Issue #23564: sanity check the fork_exec() fds_to_keep sanity check.
3023 import _posixsubprocess
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03003024 class BadInt:
3025 first = True
3026 def __init__(self, value):
3027 self.value = value
3028 def __int__(self):
3029 if self.first:
3030 self.first = False
3031 return self.value
3032 raise ValueError
3033
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08003034 gc_enabled = gc.isenabled()
3035 try:
3036 gc.enable()
3037
3038 for fds_to_keep in (
3039 (-1, 2, 3, 4, 5), # Negative number.
3040 ('str', 4), # Not an int.
3041 (18, 23, 42, 2**63), # Out of range.
3042 (5, 4), # Not sorted.
3043 (6, 7, 7, 8), # Duplicate.
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03003044 (BadInt(1), BadInt(2)),
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08003045 ):
3046 with self.assertRaises(
3047 ValueError,
3048 msg='fds_to_keep={}'.format(fds_to_keep)) as c:
3049 _posixsubprocess.fork_exec(
3050 [b"false"], [b"false"],
3051 True, fds_to_keep, None, [b"env"],
3052 -1, -1, -1, -1,
3053 1, 2, 3, 4,
Patrick McLean2b2ead72019-09-12 10:15:44 -07003054 True, True,
Gregory P. Smithf3751ef2019-10-12 13:24:56 -07003055 None, None, None, -1,
Patrick McLean2b2ead72019-09-12 10:15:44 -07003056 None)
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08003057 self.assertIn('fds_to_keep', str(c.exception))
3058 finally:
3059 if not gc_enabled:
3060 gc.disable()
Victor Stinner8f437aa2014-10-05 17:25:19 +02003061
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)2daf8e72016-06-05 02:57:47 +00003062 def test_communicate_BrokenPipeError_stdin_close(self):
3063 # By not setting stdout or stderr or a timeout we force the fast path
3064 # that just calls _stdin_write() internally due to our mock.
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003065 proc = subprocess.Popen(ZERO_RETURN_CMD)
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)2daf8e72016-06-05 02:57:47 +00003066 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
3067 mock_proc_stdin.close.side_effect = BrokenPipeError
3068 proc.communicate() # Should swallow BrokenPipeError from close.
3069 mock_proc_stdin.close.assert_called_with()
3070
3071 def test_communicate_BrokenPipeError_stdin_write(self):
3072 # By not setting stdout or stderr or a timeout we force the fast path
3073 # that just calls _stdin_write() internally due to our mock.
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003074 proc = subprocess.Popen(ZERO_RETURN_CMD)
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)2daf8e72016-06-05 02:57:47 +00003075 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
3076 mock_proc_stdin.write.side_effect = BrokenPipeError
3077 proc.communicate(b'stuff') # Should swallow the BrokenPipeError.
3078 mock_proc_stdin.write.assert_called_once_with(b'stuff')
3079 mock_proc_stdin.close.assert_called_once_with()
3080
3081 def test_communicate_BrokenPipeError_stdin_flush(self):
3082 # Setting stdin and stdout forces the ._communicate() code path.
3083 # python -h exits faster than python -c pass (but spams stdout).
3084 proc = subprocess.Popen([sys.executable, '-h'],
3085 stdin=subprocess.PIPE,
3086 stdout=subprocess.PIPE)
3087 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin, \
3088 open(os.devnull, 'wb') as dev_null:
3089 mock_proc_stdin.flush.side_effect = BrokenPipeError
3090 # because _communicate registers a selector using proc.stdin...
3091 mock_proc_stdin.fileno.return_value = dev_null.fileno()
3092 # _communicate() should swallow BrokenPipeError from flush.
3093 proc.communicate(b'stuff')
3094 mock_proc_stdin.flush.assert_called_once_with()
3095
3096 def test_communicate_BrokenPipeError_stdin_close_with_timeout(self):
3097 # Setting stdin and stdout forces the ._communicate() code path.
3098 # python -h exits faster than python -c pass (but spams stdout).
3099 proc = subprocess.Popen([sys.executable, '-h'],
3100 stdin=subprocess.PIPE,
3101 stdout=subprocess.PIPE)
3102 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
3103 mock_proc_stdin.close.side_effect = BrokenPipeError
3104 # _communicate() should swallow BrokenPipeError from close.
3105 proc.communicate(timeout=999)
3106 mock_proc_stdin.close.assert_called_once_with()
3107
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003108 @unittest.skipUnless(_testcapi is not None
3109 and hasattr(_testcapi, 'W_STOPCODE'),
3110 'need _testcapi.W_STOPCODE')
3111 def test_stopped(self):
Gregory P. Smith50e16e32017-01-22 17:28:38 -08003112 """Test wait() behavior when waitpid returns WIFSTOPPED; issue29335."""
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003113 args = ZERO_RETURN_CMD
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003114 proc = subprocess.Popen(args)
Victor Stinnercdee3f12017-06-26 17:23:03 +02003115
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003116 # Wait until the real process completes to avoid zombie process
Victor Stinner278c1e12020-03-31 20:08:12 +02003117 support.wait_process(proc.pid, exitcode=0)
Victor Stinnercdee3f12017-06-26 17:23:03 +02003118
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003119 status = _testcapi.W_STOPCODE(3)
Victor Stinner278c1e12020-03-31 20:08:12 +02003120 with mock.patch('subprocess.os.waitpid', return_value=(proc.pid, status)):
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003121 returncode = proc.wait()
Victor Stinnercdee3f12017-06-26 17:23:03 +02003122
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003123 self.assertEqual(returncode, -3)
Gregory P. Smith50e16e32017-01-22 17:28:38 -08003124
Victor Stinnere85a3052020-01-15 17:38:55 +01003125 def test_send_signal_race(self):
3126 # bpo-38630: send_signal() must poll the process exit status to reduce
3127 # the risk of sending the signal to the wrong process.
3128 proc = subprocess.Popen(ZERO_RETURN_CMD)
3129
3130 # wait until the process completes without using the Popen APIs.
Victor Stinner278c1e12020-03-31 20:08:12 +02003131 support.wait_process(proc.pid, exitcode=0)
Victor Stinnere85a3052020-01-15 17:38:55 +01003132
3133 # returncode is still None but the process completed.
3134 self.assertIsNone(proc.returncode)
3135
3136 with mock.patch("os.kill") as mock_kill:
3137 proc.send_signal(signal.SIGTERM)
3138
3139 # send_signal() didn't call os.kill() since the process already
3140 # completed.
3141 mock_kill.assert_not_called()
3142
3143 # Don't check the returncode value: the test reads the exit status,
3144 # so Popen failed to read it and uses a default returncode instead.
3145 self.assertIsNotNone(proc.returncode)
3146
Alex Rebertd3ae95e2020-01-22 18:28:31 -05003147 def test_communicate_repeated_call_after_stdout_close(self):
3148 proc = subprocess.Popen([sys.executable, '-c',
3149 'import os, time; os.close(1), time.sleep(2)'],
3150 stdout=subprocess.PIPE)
3151 while True:
3152 try:
3153 proc.communicate(timeout=0.1)
3154 return
3155 except subprocess.TimeoutExpired:
3156 pass
3157
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003158
Victor Stinner937ee9e2018-06-26 02:11:06 +02003159@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00003160class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00003161
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003162 def test_startupinfo(self):
3163 # startupinfo argument
3164 # We uses hardcoded constants, because we do not want to
3165 # depend on win32all.
3166 STARTF_USESHOWWINDOW = 1
3167 SW_MAXIMIZE = 3
3168 startupinfo = subprocess.STARTUPINFO()
3169 startupinfo.dwFlags = STARTF_USESHOWWINDOW
3170 startupinfo.wShowWindow = SW_MAXIMIZE
3171 # Since Python is a console process, it won't be affected
3172 # by wShowWindow, but the argument should be silently
3173 # ignored
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003174 subprocess.call(ZERO_RETURN_CMD,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003175 startupinfo=startupinfo)
3176
Subhendu Ghoshae160bb2017-02-25 20:29:05 +05303177 def test_startupinfo_keywords(self):
3178 # startupinfo argument
3179 # We use hardcoded constants, because we do not want to
3180 # depend on win32all.
3181 STARTF_USERSHOWWINDOW = 1
3182 SW_MAXIMIZE = 3
3183 startupinfo = subprocess.STARTUPINFO(
3184 dwFlags=STARTF_USERSHOWWINDOW,
3185 wShowWindow=SW_MAXIMIZE
3186 )
3187 # Since Python is a console process, it won't be affected
3188 # by wShowWindow, but the argument should be silently
3189 # ignored
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003190 subprocess.call(ZERO_RETURN_CMD,
Subhendu Ghoshae160bb2017-02-25 20:29:05 +05303191 startupinfo=startupinfo)
3192
Victor Stinner483422f2018-07-05 22:54:17 +02003193 def test_startupinfo_copy(self):
3194 # bpo-34044: Popen must not modify input STARTUPINFO structure
3195 startupinfo = subprocess.STARTUPINFO()
3196 startupinfo.dwFlags = subprocess.STARTF_USESHOWWINDOW
3197 startupinfo.wShowWindow = subprocess.SW_HIDE
3198
3199 # Call Popen() twice with the same startupinfo object to make sure
3200 # that it's not modified
3201 for _ in range(2):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003202 cmd = ZERO_RETURN_CMD
Victor Stinner483422f2018-07-05 22:54:17 +02003203 with open(os.devnull, 'w') as null:
3204 proc = subprocess.Popen(cmd,
3205 stdout=null,
3206 stderr=subprocess.STDOUT,
3207 startupinfo=startupinfo)
3208 with proc:
3209 proc.communicate()
3210 self.assertEqual(proc.returncode, 0)
3211
3212 self.assertEqual(startupinfo.dwFlags,
3213 subprocess.STARTF_USESHOWWINDOW)
3214 self.assertIsNone(startupinfo.hStdInput)
3215 self.assertIsNone(startupinfo.hStdOutput)
3216 self.assertIsNone(startupinfo.hStdError)
3217 self.assertEqual(startupinfo.wShowWindow, subprocess.SW_HIDE)
3218 self.assertEqual(startupinfo.lpAttributeList, {"handle_list": []})
3219
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003220 def test_creationflags(self):
3221 # creationflags argument
3222 CREATE_NEW_CONSOLE = 16
3223 sys.stderr.write(" a DOS box should flash briefly ...\n")
3224 subprocess.call(sys.executable +
3225 ' -c "import time; time.sleep(0.25)"',
3226 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003227
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003228 def test_invalid_args(self):
3229 # invalid arguments should raise ValueError
3230 self.assertRaises(ValueError, subprocess.call,
3231 [sys.executable, "-c",
3232 "import sys; sys.exit(47)"],
3233 preexec_fn=lambda: 1)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003234
Oren Milman0b3a87e2017-09-14 22:30:28 +03003235 @support.cpython_only
3236 def test_issue31471(self):
3237 # There shouldn't be an assertion failure in Popen() in case the env
3238 # argument has a bad keys() method.
3239 class BadEnv(dict):
3240 keys = None
3241 with self.assertRaises(TypeError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003242 subprocess.Popen(ZERO_RETURN_CMD, env=BadEnv())
Oren Milman0b3a87e2017-09-14 22:30:28 +03003243
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003244 def test_close_fds(self):
3245 # close file descriptors
3246 rc = subprocess.call([sys.executable, "-c",
3247 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003248 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003249 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003250
Segev Finerb2a60832017-12-18 11:28:19 +02003251 def test_close_fds_with_stdio(self):
3252 import msvcrt
3253
3254 fds = os.pipe()
3255 self.addCleanup(os.close, fds[0])
3256 self.addCleanup(os.close, fds[1])
3257
3258 handles = []
3259 for fd in fds:
3260 os.set_inheritable(fd, True)
3261 handles.append(msvcrt.get_osfhandle(fd))
3262
3263 p = subprocess.Popen([sys.executable, "-c",
3264 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3265 stdout=subprocess.PIPE, close_fds=False)
3266 stdout, stderr = p.communicate()
3267 self.assertEqual(p.returncode, 0)
3268 int(stdout.strip()) # Check that stdout is an integer
3269
3270 p = subprocess.Popen([sys.executable, "-c",
3271 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3272 stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
3273 stdout, stderr = p.communicate()
3274 self.assertEqual(p.returncode, 1)
3275 self.assertIn(b"OSError", stderr)
3276
3277 # The same as the previous call, but with an empty handle_list
3278 handle_list = []
3279 startupinfo = subprocess.STARTUPINFO()
3280 startupinfo.lpAttributeList = {"handle_list": handle_list}
3281 p = subprocess.Popen([sys.executable, "-c",
3282 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3283 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
3284 startupinfo=startupinfo, close_fds=True)
3285 stdout, stderr = p.communicate()
3286 self.assertEqual(p.returncode, 1)
3287 self.assertIn(b"OSError", stderr)
3288
3289 # Check for a warning due to using handle_list and close_fds=False
3290 with support.check_warnings((".*overriding close_fds", RuntimeWarning)):
3291 startupinfo = subprocess.STARTUPINFO()
3292 startupinfo.lpAttributeList = {"handle_list": handles[:]}
3293 p = subprocess.Popen([sys.executable, "-c",
3294 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3295 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
3296 startupinfo=startupinfo, close_fds=False)
3297 stdout, stderr = p.communicate()
3298 self.assertEqual(p.returncode, 0)
3299
3300 def test_empty_attribute_list(self):
3301 startupinfo = subprocess.STARTUPINFO()
3302 startupinfo.lpAttributeList = {}
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003303 subprocess.call(ZERO_RETURN_CMD,
Segev Finerb2a60832017-12-18 11:28:19 +02003304 startupinfo=startupinfo)
3305
3306 def test_empty_handle_list(self):
3307 startupinfo = subprocess.STARTUPINFO()
3308 startupinfo.lpAttributeList = {"handle_list": []}
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003309 subprocess.call(ZERO_RETURN_CMD,
Segev Finerb2a60832017-12-18 11:28:19 +02003310 startupinfo=startupinfo)
3311
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003312 def test_shell_sequence(self):
3313 # Run command through the shell (sequence)
3314 newenv = os.environ.copy()
3315 newenv["FRUIT"] = "physalis"
3316 p = subprocess.Popen(["set"], shell=1,
3317 stdout=subprocess.PIPE,
3318 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02003319 with p:
3320 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00003321
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003322 def test_shell_string(self):
3323 # Run command through the shell (string)
3324 newenv = os.environ.copy()
3325 newenv["FRUIT"] = "physalis"
3326 p = subprocess.Popen("set", shell=1,
3327 stdout=subprocess.PIPE,
3328 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02003329 with p:
3330 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003331
Steve Dower050acae2016-09-06 20:16:17 -07003332 def test_shell_encodings(self):
3333 # Run command through the shell (string)
3334 for enc in ['ansi', 'oem']:
3335 newenv = os.environ.copy()
3336 newenv["FRUIT"] = "physalis"
3337 p = subprocess.Popen("set", shell=1,
3338 stdout=subprocess.PIPE,
3339 env=newenv,
3340 encoding=enc)
3341 with p:
3342 self.assertIn("physalis", p.stdout.read(), enc)
3343
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003344 def test_call_string(self):
3345 # call() function with string argument on Windows
3346 rc = subprocess.call(sys.executable +
3347 ' -c "import sys; sys.exit(47)"')
3348 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003349
Florent Xicluna4886d242010-03-08 13:27:26 +00003350 def _kill_process(self, method, *args):
3351 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00003352 p = subprocess.Popen([sys.executable, "-c", """if 1:
3353 import sys, time
3354 sys.stdout.write('x\\n')
3355 sys.stdout.flush()
3356 time.sleep(30)
3357 """],
3358 stdin=subprocess.PIPE,
3359 stdout=subprocess.PIPE,
3360 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02003361 with p:
3362 # Wait for the interpreter to be completely initialized before
3363 # sending any signal.
3364 p.stdout.read(1)
3365 getattr(p, method)(*args)
3366 _, stderr = p.communicate()
Victor Stinner6cac1132019-12-08 08:38:16 +01003367 self.assertEqual(stderr, b'')
Victor Stinner7438c612016-05-20 12:43:15 +02003368 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00003369 self.assertNotEqual(returncode, 0)
3370
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003371 def _kill_dead_process(self, method, *args):
3372 p = subprocess.Popen([sys.executable, "-c", """if 1:
3373 import sys, time
3374 sys.stdout.write('x\\n')
3375 sys.stdout.flush()
3376 sys.exit(42)
3377 """],
3378 stdin=subprocess.PIPE,
3379 stdout=subprocess.PIPE,
3380 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02003381 with p:
3382 # Wait for the interpreter to be completely initialized before
3383 # sending any signal.
3384 p.stdout.read(1)
3385 # The process should end after this
3386 time.sleep(1)
3387 # This shouldn't raise even though the child is now dead
3388 getattr(p, method)(*args)
3389 _, stderr = p.communicate()
Victor Stinner6cac1132019-12-08 08:38:16 +01003390 self.assertEqual(stderr, b'')
Victor Stinner7438c612016-05-20 12:43:15 +02003391 rc = p.wait()
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003392 self.assertEqual(rc, 42)
3393
Florent Xicluna4886d242010-03-08 13:27:26 +00003394 def test_send_signal(self):
3395 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00003396
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003397 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00003398 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00003399
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003400 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00003401 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00003402
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003403 def test_send_signal_dead(self):
3404 self._kill_dead_process('send_signal', signal.SIGTERM)
3405
3406 def test_kill_dead(self):
3407 self._kill_dead_process('kill')
3408
3409 def test_terminate_dead(self):
3410 self._kill_dead_process('terminate')
3411
Martin Panter23172bd2016-04-16 11:28:10 +00003412class MiscTests(unittest.TestCase):
Gregory P. Smithf4d644f2018-01-29 21:27:39 -08003413
3414 class RecordingPopen(subprocess.Popen):
3415 """A Popen that saves a reference to each instance for testing."""
3416 instances_created = []
3417
3418 def __init__(self, *args, **kwargs):
3419 super().__init__(*args, **kwargs)
3420 self.instances_created.append(self)
3421
3422 @mock.patch.object(subprocess.Popen, "_communicate")
3423 def _test_keyboardinterrupt_no_kill(self, popener, mock__communicate,
3424 **kwargs):
3425 """Fake a SIGINT happening during Popen._communicate() and ._wait().
3426
3427 This avoids the need to actually try and get test environments to send
3428 and receive signals reliably across platforms. The net effect of a ^C
3429 happening during a blocking subprocess execution which we want to clean
3430 up from is a KeyboardInterrupt coming out of communicate() or wait().
3431 """
3432
3433 mock__communicate.side_effect = KeyboardInterrupt
3434 try:
3435 with mock.patch.object(subprocess.Popen, "_wait") as mock__wait:
3436 # We patch out _wait() as no signal was involved so the
3437 # child process isn't actually going to exit rapidly.
3438 mock__wait.side_effect = KeyboardInterrupt
3439 with mock.patch.object(subprocess, "Popen",
3440 self.RecordingPopen):
3441 with self.assertRaises(KeyboardInterrupt):
3442 popener([sys.executable, "-c",
3443 "import time\ntime.sleep(9)\nimport sys\n"
3444 "sys.stderr.write('\\n!runaway child!\\n')"],
3445 stdout=subprocess.DEVNULL, **kwargs)
3446 for call in mock__wait.call_args_list[1:]:
3447 self.assertNotEqual(
3448 call, mock.call(timeout=None),
3449 "no open-ended wait() after the first allowed: "
3450 f"{mock__wait.call_args_list}")
3451 sigint_calls = []
3452 for call in mock__wait.call_args_list:
3453 if call == mock.call(timeout=0.25): # from Popen.__init__
3454 sigint_calls.append(call)
3455 self.assertLessEqual(mock__wait.call_count, 2,
3456 msg=mock__wait.call_args_list)
3457 self.assertEqual(len(sigint_calls), 1,
3458 msg=mock__wait.call_args_list)
3459 finally:
3460 # cleanup the forgotten (due to our mocks) child process
3461 process = self.RecordingPopen.instances_created.pop()
3462 process.kill()
3463 process.wait()
3464 self.assertEqual([], self.RecordingPopen.instances_created)
3465
3466 def test_call_keyboardinterrupt_no_kill(self):
3467 self._test_keyboardinterrupt_no_kill(subprocess.call, timeout=6.282)
3468
3469 def test_run_keyboardinterrupt_no_kill(self):
3470 self._test_keyboardinterrupt_no_kill(subprocess.run, timeout=6.282)
3471
3472 def test_context_manager_keyboardinterrupt_no_kill(self):
3473 def popen_via_context_manager(*args, **kwargs):
3474 with subprocess.Popen(*args, **kwargs) as unused_process:
3475 raise KeyboardInterrupt # Test how __exit__ handles ^C.
3476 self._test_keyboardinterrupt_no_kill(popen_via_context_manager)
3477
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003478 def test_getoutput(self):
3479 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
3480 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
3481 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00003482
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003483 # we use mkdtemp in the next line to create an empty directory
3484 # under our exclusive control; from that, we can invent a pathname
3485 # that we _know_ won't exist. This is guaranteed to fail.
3486 dir = None
3487 try:
3488 dir = tempfile.mkdtemp()
3489 name = os.path.join(dir, "foo")
Tim Goldene0041752013-11-03 12:53:17 +00003490 status, output = subprocess.getstatusoutput(
Victor Stinner937ee9e2018-06-26 02:11:06 +02003491 ("type " if mswindows else "cat ") + name)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003492 self.assertNotEqual(status, 0)
3493 finally:
3494 if dir is not None:
3495 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00003496
Gregory P. Smithace55862015-04-07 15:57:54 -07003497 def test__all__(self):
3498 """Ensure that __all__ is populated properly."""
Patrick McLean2b2ead72019-09-12 10:15:44 -07003499 intentionally_excluded = {"list2cmdline", "Handle", "pwd", "grp"}
Gregory P. Smithace55862015-04-07 15:57:54 -07003500 exported = set(subprocess.__all__)
3501 possible_exports = set()
3502 import types
3503 for name, value in subprocess.__dict__.items():
3504 if name.startswith('_'):
3505 continue
3506 if isinstance(value, (types.ModuleType,)):
3507 continue
3508 possible_exports.add(name)
3509 self.assertEqual(exported, possible_exports - intentionally_excluded)
3510
3511
Martin Panter23172bd2016-04-16 11:28:10 +00003512@unittest.skipUnless(hasattr(selectors, 'PollSelector'),
3513 "Test needs selectors.PollSelector")
3514class ProcessTestCaseNoPoll(ProcessTestCase):
3515 def setUp(self):
3516 self.orig_selector = subprocess._PopenSelector
3517 subprocess._PopenSelector = selectors.SelectSelector
3518 ProcessTestCase.setUp(self)
3519
3520 def tearDown(self):
3521 subprocess._PopenSelector = self.orig_selector
3522 ProcessTestCase.tearDown(self)
3523
Gregory P. Smithd06fa472009-07-04 02:46:54 +00003524
Victor Stinner937ee9e2018-06-26 02:11:06 +02003525@unittest.skipUnless(mswindows, "Windows-specific tests")
Tim Golden126c2962010-08-11 14:20:40 +00003526class CommandsWithSpaces (BaseTestCase):
3527
3528 def setUp(self):
3529 super().setUp()
Berker Peksag16a1f282015-09-28 13:33:14 +03003530 f, fname = tempfile.mkstemp(".py", "te st")
Tim Golden126c2962010-08-11 14:20:40 +00003531 self.fname = fname.lower ()
3532 os.write(f, b"import sys;"
3533 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
3534 )
3535 os.close(f)
3536
3537 def tearDown(self):
3538 os.remove(self.fname)
3539 super().tearDown()
3540
3541 def with_spaces(self, *args, **kwargs):
3542 kwargs['stdout'] = subprocess.PIPE
3543 p = subprocess.Popen(*args, **kwargs)
Victor Stinner7438c612016-05-20 12:43:15 +02003544 with p:
3545 self.assertEqual(
3546 p.stdout.read ().decode("mbcs"),
3547 "2 [%r, 'ab cd']" % self.fname
3548 )
Tim Golden126c2962010-08-11 14:20:40 +00003549
3550 def test_shell_string_with_spaces(self):
3551 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00003552 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
3553 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00003554
3555 def test_shell_sequence_with_spaces(self):
3556 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00003557 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00003558
3559 def test_noshell_string_with_spaces(self):
3560 # call() function with string argument with spaces on Windows
3561 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
3562 "ab cd"))
3563
3564 def test_noshell_sequence_with_spaces(self):
3565 # call() function with sequence argument with spaces on Windows
3566 self.with_spaces([sys.executable, self.fname, "ab cd"])
3567
Brian Curtin79cdb662010-12-03 02:46:02 +00003568
Georg Brandla86b2622012-02-20 21:34:57 +01003569class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00003570
3571 def test_pipe(self):
3572 with subprocess.Popen([sys.executable, "-c",
3573 "import sys;"
3574 "sys.stdout.write('stdout');"
3575 "sys.stderr.write('stderr');"],
3576 stdout=subprocess.PIPE,
3577 stderr=subprocess.PIPE) as proc:
3578 self.assertEqual(proc.stdout.read(), b"stdout")
Victor Stinner6cac1132019-12-08 08:38:16 +01003579 self.assertEqual(proc.stderr.read(), b"stderr")
Brian Curtin79cdb662010-12-03 02:46:02 +00003580
3581 self.assertTrue(proc.stdout.closed)
3582 self.assertTrue(proc.stderr.closed)
3583
3584 def test_returncode(self):
3585 with subprocess.Popen([sys.executable, "-c",
3586 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07003587 pass
3588 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00003589 self.assertEqual(proc.returncode, 100)
3590
3591 def test_communicate_stdin(self):
3592 with subprocess.Popen([sys.executable, "-c",
3593 "import sys;"
3594 "sys.exit(sys.stdin.read() == 'context')"],
3595 stdin=subprocess.PIPE) as proc:
3596 proc.communicate(b"context")
3597 self.assertEqual(proc.returncode, 1)
3598
3599 def test_invalid_args(self):
Victor Stinnerb31206a2018-01-25 19:06:05 +01003600 with self.assertRaises(NONEXISTING_ERRORS):
Victor Stinner9a83f652017-08-21 23:51:31 +02003601 with subprocess.Popen(NONEXISTING_CMD,
Brian Curtin79cdb662010-12-03 02:46:02 +00003602 stdout=subprocess.PIPE,
3603 stderr=subprocess.PIPE) as proc:
3604 pass
3605
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003606 def test_broken_pipe_cleanup(self):
3607 """Broken pipe error should not prevent wait() (Issue 21619)"""
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003608 proc = subprocess.Popen(ZERO_RETURN_CMD,
Victor Stinner20f4bd42015-03-05 02:38:41 +01003609 stdin=subprocess.PIPE,
Victor Stinner20f4bd42015-03-05 02:38:41 +01003610 bufsize=support.PIPE_MAX_SIZE*2)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003611 proc = proc.__enter__()
3612 # Prepare to send enough data to overflow any OS pipe buffering and
3613 # guarantee a broken pipe error. Data is held in BufferedWriter
3614 # buffer until closed.
3615 proc.stdin.write(b'x' * support.PIPE_MAX_SIZE)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003616 self.assertIsNone(proc.returncode)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003617 # EPIPE expected under POSIX; EINVAL under Windows
Serhiy Storchakacf265fd2015-02-28 13:27:54 +02003618 self.assertRaises(OSError, proc.__exit__, None, None, None)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003619 self.assertEqual(proc.returncode, 0)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003620 self.assertTrue(proc.stdin.closed)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003621
Brian Curtin79cdb662010-12-03 02:46:02 +00003622
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003623if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04003624 unittest.main()