blob: 9fc4434649dbcede78a71411fa1e578b539174ad [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
Hai Shi0c4f0f32020-06-30 21:46:31 +08004from test.support import import_helper
5from test.support import os_helper
6from test.support import warnings_helper
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00007import subprocess
8import sys
9import signal
Gregory P. Smith112bb3a2011-03-15 14:55:17 -040010import io
Alexey Izbyshev0e7144b2018-03-26 22:49:35 +030011import itertools
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000012import os
Gregory P. Smitha59c59f2010-03-01 00:17:40 +000013import errno
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000014import tempfile
15import time
Gregory P. Smith580d2782019-09-11 04:23:05 -050016import traceback
Guido van Rossum48b069a2020-04-07 09:50:06 -070017import types
Charles-François Natali3a4586a2013-11-08 19:56:59 +010018import selectors
Ezio Melotti184bdfb2010-02-18 09:37:05 +000019import sysconfig
Gregory P. Smith51ee2702010-12-13 07:59:39 +000020import select
Gregory P. Smith81ce6852011-03-15 02:04:11 -040021import shutil
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020022import threading
Benjamin Petersonb870aa12011-12-10 12:44:25 -050023import gc
Andrew Svetlov47ec25d2012-08-19 16:25:37 +030024import textwrap
Patrick McLean2b2ead72019-09-12 10:15:44 -070025import json
Hai Shi0c4f0f32020-06-30 21:46:31 +080026from test.support.os_helper import FakePath
Benjamin Peterson964561b2011-12-10 12:31:42 -050027
28try:
Victor Stinner7b7c6dc2017-08-10 12:37:39 +020029 import _testcapi
30except ImportError:
31 _testcapi = None
32
Patrick McLean2b2ead72019-09-12 10:15:44 -070033try:
34 import pwd
35except ImportError:
36 pwd = None
37try:
38 import grp
39except ImportError:
40 grp = None
Victor Stinner8f4ef3b2019-07-01 18:28:25 +020041
Ruben Vorderman23c0fb82020-10-20 01:30:02 +020042try:
43 import fcntl
44except:
45 fcntl = None
46
Steve Dower22d06982016-09-06 19:38:15 -070047if support.PGO:
48 raise unittest.SkipTest("test is not helpful for PGO")
49
Victor Stinner937ee9e2018-06-26 02:11:06 +020050mswindows = (sys.platform == "win32")
51
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000052#
53# Depends on the following external programs: Python
54#
55
Victor Stinner937ee9e2018-06-26 02:11:06 +020056if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000057 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
58 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000059else:
60 SETBINARY = ''
61
Victor Stinner9a83f652017-08-21 23:51:31 +020062NONEXISTING_CMD = ('nonexisting_i_hope',)
Victor Stinnerb31206a2018-01-25 19:06:05 +010063# Ignore errors that indicate the command was not found
64NONEXISTING_ERRORS = (FileNotFoundError, NotADirectoryError, PermissionError)
Victor Stinner9a83f652017-08-21 23:51:31 +020065
Gregory P. Smith67b93f82019-10-12 16:35:53 -070066ZERO_RETURN_CMD = (sys.executable, '-c', 'pass')
67
68
69def setUpModule():
70 shell_true = shutil.which('true')
Pablo Galindo46113e02019-10-13 02:40:24 +010071 if shell_true is None:
72 return
Gregory P. Smith67b93f82019-10-12 16:35:53 -070073 if (os.access(shell_true, os.X_OK) and
74 subprocess.run([shell_true]).returncode == 0):
75 global ZERO_RETURN_CMD
76 ZERO_RETURN_CMD = (shell_true,) # Faster than Python startup.
77
Florent Xiclunab1e94e82010-02-27 22:12:37 +000078
Florent Xiclunac049d872010-03-27 22:47:23 +000079class BaseTestCase(unittest.TestCase):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000080 def setUp(self):
81 # Try to minimize the number of children we have so this test
82 # doesn't crash on some buildbots (Alphas in particular).
Florent Xiclunab1e94e82010-02-27 22:12:37 +000083 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000084
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000085 def tearDown(self):
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +030086 if not mswindows:
87 # subprocess._active is not used on Windows and is set to None.
88 for inst in subprocess._active:
89 inst.wait()
90 subprocess._cleanup()
91 self.assertFalse(
92 subprocess._active, "subprocess._active not empty"
93 )
Victor Stinnercc42c122017-07-28 18:00:22 +020094 self.doCleanups()
95 support.reap_children()
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000096
Florent Xiclunac049d872010-03-27 22:47:23 +000097
Gregory P. Smith3d8e7762012-11-10 22:32:22 -080098class PopenTestException(Exception):
99 pass
100
101
102class PopenExecuteChildRaises(subprocess.Popen):
103 """Popen subclass for testing cleanup of subprocess.PIPE filehandles when
104 _execute_child fails.
105 """
106 def _execute_child(self, *args, **kwargs):
107 raise PopenTestException("Forced Exception for Test")
108
109
Florent Xiclunac049d872010-03-27 22:47:23 +0000110class ProcessTestCase(BaseTestCase):
111
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700112 def test_io_buffered_by_default(self):
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700113 p = subprocess.Popen(ZERO_RETURN_CMD,
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700114 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
115 stderr=subprocess.PIPE)
116 try:
117 self.assertIsInstance(p.stdin, io.BufferedIOBase)
118 self.assertIsInstance(p.stdout, io.BufferedIOBase)
119 self.assertIsInstance(p.stderr, io.BufferedIOBase)
120 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -0700121 p.stdin.close()
122 p.stdout.close()
123 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700124 p.wait()
125
126 def test_io_unbuffered_works(self):
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700127 p = subprocess.Popen(ZERO_RETURN_CMD,
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700128 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
129 stderr=subprocess.PIPE, bufsize=0)
130 try:
131 self.assertIsInstance(p.stdin, io.RawIOBase)
132 self.assertIsInstance(p.stdout, io.RawIOBase)
133 self.assertIsInstance(p.stderr, io.RawIOBase)
134 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -0700135 p.stdin.close()
136 p.stdout.close()
137 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700138 p.wait()
139
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000140 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000141 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +0000142 rc = subprocess.call([sys.executable, "-c",
143 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000144 self.assertEqual(rc, 47)
145
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400146 def test_call_timeout(self):
147 # call() function with timeout argument; we want to test that the child
148 # process gets killed when the timeout expires. If the child isn't
149 # killed, this call will deadlock since subprocess.call waits for the
150 # child.
151 self.assertRaises(subprocess.TimeoutExpired, subprocess.call,
152 [sys.executable, "-c", "while True: pass"],
153 timeout=0.1)
154
Peter Astrand454f7672005-01-01 09:36:35 +0000155 def test_check_call_zero(self):
156 # check_call() function with zero return code
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700157 rc = subprocess.check_call(ZERO_RETURN_CMD)
Peter Astrand454f7672005-01-01 09:36:35 +0000158 self.assertEqual(rc, 0)
159
160 def test_check_call_nonzero(self):
161 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000162 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +0000163 subprocess.check_call([sys.executable, "-c",
164 "import sys; sys.exit(47)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000165 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +0000166
Georg Brandlf9734072008-12-07 15:30:06 +0000167 def test_check_output(self):
168 # check_output() function with zero return code
169 output = subprocess.check_output(
170 [sys.executable, "-c", "print('BDFL')"])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000171 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000172
173 def test_check_output_nonzero(self):
174 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000175 with self.assertRaises(subprocess.CalledProcessError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000176 subprocess.check_output(
177 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000178 self.assertEqual(c.exception.returncode, 5)
Georg Brandlf9734072008-12-07 15:30:06 +0000179
180 def test_check_output_stderr(self):
181 # check_output() function stderr redirected to stdout
182 output = subprocess.check_output(
183 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
184 stderr=subprocess.STDOUT)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000185 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000186
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300187 def test_check_output_stdin_arg(self):
188 # check_output() can be called with stdin set to a file
189 tf = tempfile.TemporaryFile()
190 self.addCleanup(tf.close)
191 tf.write(b'pear')
192 tf.seek(0)
193 output = subprocess.check_output(
194 [sys.executable, "-c",
195 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
196 stdin=tf)
197 self.assertIn(b'PEAR', output)
198
199 def test_check_output_input_arg(self):
200 # check_output() can be called with input set to a string
201 output = subprocess.check_output(
202 [sys.executable, "-c",
203 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
204 input=b'pear')
205 self.assertIn(b'PEAR', output)
206
Georg Brandlf9734072008-12-07 15:30:06 +0000207 def test_check_output_stdout_arg(self):
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300208 # check_output() refuses to accept 'stdout' argument
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000209 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000210 output = subprocess.check_output(
211 [sys.executable, "-c", "print('will not be run')"],
212 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +0000213 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000214 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +0000215
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300216 def test_check_output_stdin_with_input_arg(self):
217 # check_output() refuses to accept 'stdin' with 'input'
218 tf = tempfile.TemporaryFile()
219 self.addCleanup(tf.close)
220 tf.write(b'pear')
221 tf.seek(0)
222 with self.assertRaises(ValueError) as c:
223 output = subprocess.check_output(
224 [sys.executable, "-c", "print('will not be run')"],
225 stdin=tf, input=b'hare')
226 self.fail("Expected ValueError when stdin and input args supplied.")
227 self.assertIn('stdin', c.exception.args[0])
228 self.assertIn('input', c.exception.args[0])
229
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400230 def test_check_output_timeout(self):
231 # check_output() function with timeout arg
232 with self.assertRaises(subprocess.TimeoutExpired) as c:
233 output = subprocess.check_output(
234 [sys.executable, "-c",
Victor Stinner149b1c72011-06-06 23:43:02 +0200235 "import sys, time\n"
236 "sys.stdout.write('BDFL')\n"
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400237 "sys.stdout.flush()\n"
Victor Stinner149b1c72011-06-06 23:43:02 +0200238 "time.sleep(3600)"],
Reid Klecknerda9ac722011-03-16 17:08:21 -0400239 # Some heavily loaded buildbots (sparc Debian 3.x) require
240 # this much time to start and print.
241 timeout=3)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400242 self.fail("Expected TimeoutExpired.")
243 self.assertEqual(c.exception.output, b'BDFL')
244
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000245 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000246 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000247 newenv = os.environ.copy()
248 newenv["FRUIT"] = "banana"
249 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000250 'import sys, os;'
251 'sys.exit(os.getenv("FRUIT")=="banana")'],
252 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000253 self.assertEqual(rc, 1)
254
Victor Stinner87b9bc32011-06-01 00:57:47 +0200255 def test_invalid_args(self):
256 # Popen() called with invalid arguments should raise TypeError
257 # but Popen.__del__ should not complain (issue #12085)
258 with support.captured_stderr() as s:
259 self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1)
260 argcount = subprocess.Popen.__init__.__code__.co_argcount
261 too_many_args = [0] * (argcount + 1)
262 self.assertRaises(TypeError, subprocess.Popen, *too_many_args)
263 self.assertEqual(s.getvalue(), '')
264
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000265 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000266 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000267 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000268 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000269 self.addCleanup(p.stdout.close)
270 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000271 p.wait()
272 self.assertEqual(p.stdin, None)
273
274 def test_stdout_none(self):
Ezio Melotti42a541b2013-03-11 05:53:34 +0200275 # .stdout is None when not redirected, and the child's stdout will
276 # be inherited from the parent. In order to test this we run a
277 # subprocess in a subprocess:
278 # this_test
279 # \-- subprocess created by this test (parent)
280 # \-- subprocess created by the parent subprocess (child)
281 # The parent doesn't specify stdout, so the child will use the
282 # parent's stdout. This test checks that the message printed by the
283 # child goes to the parent stdout. The parent also checks that the
284 # child's stdout is None. See #11963.
285 code = ('import sys; from subprocess import Popen, PIPE;'
286 'p = Popen([sys.executable, "-c", "print(\'test_stdout_none\')"],'
287 ' stdin=PIPE, stderr=PIPE);'
288 'p.wait(); assert p.stdout is None;')
289 p = subprocess.Popen([sys.executable, "-c", code],
290 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
291 self.addCleanup(p.stdout.close)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000292 self.addCleanup(p.stderr.close)
Ezio Melotti42a541b2013-03-11 05:53:34 +0200293 out, err = p.communicate()
294 self.assertEqual(p.returncode, 0, err)
295 self.assertEqual(out.rstrip(), b'test_stdout_none')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000296
297 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000298 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000299 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000300 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000301 self.addCleanup(p.stdout.close)
302 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000303 p.wait()
304 self.assertEqual(p.stderr, None)
305
Chris Jerdonek776cb192012-10-08 15:56:43 -0700306 def _assert_python(self, pre_args, **kwargs):
307 # We include sys.exit() to prevent the test runner from hanging
308 # whenever python is found.
309 args = pre_args + ["import sys; sys.exit(47)"]
310 p = subprocess.Popen(args, **kwargs)
311 p.wait()
312 self.assertEqual(47, p.returncode)
313
314 def test_executable(self):
315 # Check that the executable argument works.
Chris Jerdonek86b0fb22012-10-09 13:17:49 -0700316 #
317 # On Unix (non-Mac and non-Windows), Python looks at args[0] to
318 # determine where its standard library is, so we need the directory
319 # of args[0] to be valid for the Popen() call to Python to succeed.
320 # See also issue #16170 and issue #7774.
321 doesnotexist = os.path.join(os.path.dirname(sys.executable),
322 "doesnotexist")
323 self._assert_python([doesnotexist, "-c"], executable=sys.executable)
Chris Jerdonek776cb192012-10-08 15:56:43 -0700324
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +0300325 def test_bytes_executable(self):
326 doesnotexist = os.path.join(os.path.dirname(sys.executable),
327 "doesnotexist")
328 self._assert_python([doesnotexist, "-c"],
329 executable=os.fsencode(sys.executable))
330
331 def test_pathlike_executable(self):
332 doesnotexist = os.path.join(os.path.dirname(sys.executable),
333 "doesnotexist")
334 self._assert_python([doesnotexist, "-c"],
335 executable=FakePath(sys.executable))
336
Chris Jerdonek776cb192012-10-08 15:56:43 -0700337 def test_executable_takes_precedence(self):
338 # Check that the executable argument takes precedence over args[0].
339 #
340 # Verify first that the call succeeds without the executable arg.
341 pre_args = [sys.executable, "-c"]
342 self._assert_python(pre_args)
Victor Stinnerb31206a2018-01-25 19:06:05 +0100343 self.assertRaises(NONEXISTING_ERRORS,
Xavier de Gaye38c8b7d2016-11-14 17:14:42 +0100344 self._assert_python, pre_args,
Victor Stinnerb31206a2018-01-25 19:06:05 +0100345 executable=NONEXISTING_CMD[0])
Chris Jerdonek776cb192012-10-08 15:56:43 -0700346
Victor Stinner937ee9e2018-06-26 02:11:06 +0200347 @unittest.skipIf(mswindows, "executable argument replaces shell")
Chris Jerdonek776cb192012-10-08 15:56:43 -0700348 def test_executable_replaces_shell(self):
349 # Check that the executable argument replaces the default shell
350 # when shell=True.
351 self._assert_python([], executable=sys.executable, shell=True)
352
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +0300353 @unittest.skipIf(mswindows, "executable argument replaces shell")
354 def test_bytes_executable_replaces_shell(self):
355 self._assert_python([], executable=os.fsencode(sys.executable),
356 shell=True)
357
358 @unittest.skipIf(mswindows, "executable argument replaces shell")
359 def test_pathlike_executable_replaces_shell(self):
360 self._assert_python([], executable=FakePath(sys.executable),
361 shell=True)
362
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700363 # For use in the test_cwd* tests below.
364 def _normalize_cwd(self, cwd):
365 # Normalize an expected cwd (for Tru64 support).
366 # We can't use os.path.realpath since it doesn't expand Tru64 {memb}
367 # strings. See bug #1063571.
Hai Shi0c4f0f32020-06-30 21:46:31 +0800368 with os_helper.change_cwd(cwd):
Serhiy Storchaka2a23adf2015-09-06 14:13:25 +0300369 return os.getcwd()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700370
371 # For use in the test_cwd* tests below.
372 def _split_python_path(self):
373 # Return normalized (python_dir, python_base).
374 python_path = os.path.realpath(sys.executable)
375 return os.path.split(python_path)
376
377 # For use in the test_cwd* tests below.
378 def _assert_cwd(self, expected_cwd, python_arg, **kwargs):
379 # Invoke Python via Popen, and assert that (1) the call succeeds,
380 # and that (2) the current working directory of the child process
381 # matches *expected_cwd*.
382 p = subprocess.Popen([python_arg, "-c",
383 "import os, sys; "
Serhiy Storchakab1a87302020-07-26 10:21:39 +0300384 "buf = sys.stdout.buffer; "
385 "buf.write(os.getcwd().encode()); "
386 "buf.flush(); "
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700387 "sys.exit(47)"],
388 stdout=subprocess.PIPE,
389 **kwargs)
390 self.addCleanup(p.stdout.close)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000391 p.wait()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700392 self.assertEqual(47, p.returncode)
393 normcase = os.path.normcase
394 self.assertEqual(normcase(expected_cwd),
Serhiy Storchakab1a87302020-07-26 10:21:39 +0300395 normcase(p.stdout.read().decode()))
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700396
397 def test_cwd(self):
398 # Check that cwd changes the cwd for the child process.
399 temp_dir = tempfile.gettempdir()
400 temp_dir = self._normalize_cwd(temp_dir)
401 self._assert_cwd(temp_dir, sys.executable, cwd=temp_dir)
402
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +0300403 def test_cwd_with_bytes(self):
404 temp_dir = tempfile.gettempdir()
405 temp_dir = self._normalize_cwd(temp_dir)
406 self._assert_cwd(temp_dir, sys.executable, cwd=os.fsencode(temp_dir))
407
Sayan Chowdhuryd5c11f72017-02-26 22:36:10 +0530408 def test_cwd_with_pathlike(self):
409 temp_dir = tempfile.gettempdir()
410 temp_dir = self._normalize_cwd(temp_dir)
Serhiy Storchakab21d1552018-03-02 11:53:51 +0200411 self._assert_cwd(temp_dir, sys.executable, cwd=FakePath(temp_dir))
Sayan Chowdhuryd5c11f72017-02-26 22:36:10 +0530412
Victor Stinner937ee9e2018-06-26 02:11:06 +0200413 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700414 def test_cwd_with_relative_arg(self):
415 # Check that Popen looks for args[0] relative to cwd if args[0]
416 # is relative.
417 python_dir, python_base = self._split_python_path()
418 rel_python = os.path.join(os.curdir, python_base)
Hai Shi0c4f0f32020-06-30 21:46:31 +0800419 with os_helper.temp_cwd() as wrong_dir:
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700420 # Before calling with the correct cwd, confirm that the call fails
421 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700422 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700423 [rel_python])
Chris Jerdonek28714c82012-09-30 02:15:37 -0700424 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700425 [rel_python], cwd=wrong_dir)
426 python_dir = self._normalize_cwd(python_dir)
427 self._assert_cwd(python_dir, rel_python, cwd=python_dir)
428
Victor Stinner937ee9e2018-06-26 02:11:06 +0200429 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700430 def test_cwd_with_relative_executable(self):
431 # Check that Popen looks for executable relative to cwd if executable
432 # is relative (and that executable takes precedence over args[0]).
433 python_dir, python_base = self._split_python_path()
434 rel_python = os.path.join(os.curdir, python_base)
435 doesntexist = "somethingyoudonthave"
Hai Shi0c4f0f32020-06-30 21:46:31 +0800436 with os_helper.temp_cwd() as wrong_dir:
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700437 # Before calling with the correct cwd, confirm that the call fails
438 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700439 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700440 [doesntexist], executable=rel_python)
Chris Jerdonek28714c82012-09-30 02:15:37 -0700441 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700442 [doesntexist], executable=rel_python,
443 cwd=wrong_dir)
444 python_dir = self._normalize_cwd(python_dir)
445 self._assert_cwd(python_dir, doesntexist, executable=rel_python,
446 cwd=python_dir)
447
448 def test_cwd_with_absolute_arg(self):
449 # Check that Popen can find the executable when the cwd is wrong
450 # if args[0] is an absolute path.
451 python_dir, python_base = self._split_python_path()
452 abs_python = os.path.join(python_dir, python_base)
453 rel_python = os.path.join(os.curdir, python_base)
Hai Shi0c4f0f32020-06-30 21:46:31 +0800454 with os_helper.temp_dir() as wrong_dir:
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700455 # Before calling with an absolute path, confirm that using a
456 # relative path fails.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700457 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700458 [rel_python], cwd=wrong_dir)
459 wrong_dir = self._normalize_cwd(wrong_dir)
460 self._assert_cwd(wrong_dir, abs_python, cwd=wrong_dir)
461
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100462 @unittest.skipIf(sys.base_prefix != sys.prefix,
463 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000464 def test_executable_with_cwd(self):
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700465 python_dir, python_base = self._split_python_path()
466 python_dir = self._normalize_cwd(python_dir)
467 self._assert_cwd(python_dir, "somethingyoudonthave",
468 executable=sys.executable, cwd=python_dir)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000469
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100470 @unittest.skipIf(sys.base_prefix != sys.prefix,
471 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000472 @unittest.skipIf(sysconfig.is_python_build(),
473 "need an installed Python. See #7774")
474 def test_executable_without_cwd(self):
475 # For a normal installation, it should work without 'cwd'
476 # argument. For test runs in the build directory, see #7774.
Ned Deilye92dfbf2013-08-02 18:02:21 -0700477 self._assert_cwd(os.getcwd(), "somethingyoudonthave",
478 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000479
480 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000481 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000482 p = subprocess.Popen([sys.executable, "-c",
483 'import sys; sys.exit(sys.stdin.read() == "pear")'],
484 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000485 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000486 p.stdin.close()
487 p.wait()
488 self.assertEqual(p.returncode, 1)
489
490 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000491 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000492 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000493 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000494 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000495 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000496 os.lseek(d, 0, 0)
497 p = subprocess.Popen([sys.executable, "-c",
498 'import sys; sys.exit(sys.stdin.read() == "pear")'],
499 stdin=d)
500 p.wait()
501 self.assertEqual(p.returncode, 1)
502
503 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000504 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000505 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000506 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000507 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000508 tf.seek(0)
509 p = subprocess.Popen([sys.executable, "-c",
510 'import sys; sys.exit(sys.stdin.read() == "pear")'],
511 stdin=tf)
512 p.wait()
513 self.assertEqual(p.returncode, 1)
514
515 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000516 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000517 p = subprocess.Popen([sys.executable, "-c",
518 'import sys; sys.stdout.write("orange")'],
519 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +0200520 with p:
521 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000522
523 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000524 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000525 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000526 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000527 d = tf.fileno()
528 p = subprocess.Popen([sys.executable, "-c",
529 'import sys; sys.stdout.write("orange")'],
530 stdout=d)
531 p.wait()
532 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000533 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000534
535 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000536 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000537 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000538 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000539 p = subprocess.Popen([sys.executable, "-c",
540 'import sys; sys.stdout.write("orange")'],
541 stdout=tf)
542 p.wait()
543 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000544 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000545
546 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000547 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000548 p = subprocess.Popen([sys.executable, "-c",
549 'import sys; sys.stderr.write("strawberry")'],
550 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +0200551 with p:
Victor Stinner6cac1132019-12-08 08:38:16 +0100552 self.assertEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000553
554 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000555 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000556 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000557 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000558 d = tf.fileno()
559 p = subprocess.Popen([sys.executable, "-c",
560 'import sys; sys.stderr.write("strawberry")'],
561 stderr=d)
562 p.wait()
563 os.lseek(d, 0, 0)
Victor Stinner6cac1132019-12-08 08:38:16 +0100564 self.assertEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000565
566 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000567 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000568 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000569 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000570 p = subprocess.Popen([sys.executable, "-c",
571 'import sys; sys.stderr.write("strawberry")'],
572 stderr=tf)
573 p.wait()
574 tf.seek(0)
Victor Stinner6cac1132019-12-08 08:38:16 +0100575 self.assertEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000576
Martin Panterc7635892016-05-13 01:54:44 +0000577 def test_stderr_redirect_with_no_stdout_redirect(self):
578 # test stderr=STDOUT while stdout=None (not set)
579
580 # - grandchild prints to stderr
581 # - child redirects grandchild's stderr to its stdout
582 # - the parent should get grandchild's stderr in child's stdout
583 p = subprocess.Popen([sys.executable, "-c",
584 'import sys, subprocess;'
585 'rc = subprocess.call([sys.executable, "-c",'
586 ' "import sys;"'
587 ' "sys.stderr.write(\'42\')"],'
588 ' stderr=subprocess.STDOUT);'
589 'sys.exit(rc)'],
590 stdout=subprocess.PIPE,
591 stderr=subprocess.PIPE)
592 stdout, stderr = p.communicate()
593 #NOTE: stdout should get stderr from grandchild
Victor Stinner6cac1132019-12-08 08:38:16 +0100594 self.assertEqual(stdout, b'42')
595 self.assertEqual(stderr, b'') # should be empty
Martin Panterc7635892016-05-13 01:54:44 +0000596 self.assertEqual(p.returncode, 0)
597
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000598 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000599 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000600 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000601 'import sys;'
602 'sys.stdout.write("apple");'
603 'sys.stdout.flush();'
604 'sys.stderr.write("orange")'],
605 stdout=subprocess.PIPE,
606 stderr=subprocess.STDOUT)
Victor Stinner7438c612016-05-20 12:43:15 +0200607 with p:
Victor Stinner6cac1132019-12-08 08:38:16 +0100608 self.assertEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000609
610 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000611 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000612 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000613 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000614 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000615 'import sys;'
616 'sys.stdout.write("apple");'
617 'sys.stdout.flush();'
618 'sys.stderr.write("orange")'],
619 stdout=tf,
620 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000621 p.wait()
622 tf.seek(0)
Victor Stinner6cac1132019-12-08 08:38:16 +0100623 self.assertEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000624
Thomas Wouters89f507f2006-12-13 04:49:30 +0000625 def test_stdout_filedes_of_stdout(self):
626 # stdout is set to 1 (#1531862).
Ezio Melotti42a541b2013-03-11 05:53:34 +0200627 # To avoid printing the text on stdout, we do something similar to
628 # test_stdout_none (see above). The parent subprocess calls the child
629 # subprocess passing stdout=1, and this test uses stdout=PIPE in
630 # order to capture and check the output of the parent. See #11963.
631 code = ('import sys, subprocess; '
632 'rc = subprocess.call([sys.executable, "-c", '
633 ' "import os, sys; sys.exit(os.write(sys.stdout.fileno(), '
634 'b\'test with stdout=1\'))"], stdout=1); '
635 'assert rc == 18')
636 p = subprocess.Popen([sys.executable, "-c", code],
637 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
638 self.addCleanup(p.stdout.close)
639 self.addCleanup(p.stderr.close)
640 out, err = p.communicate()
641 self.assertEqual(p.returncode, 0, err)
642 self.assertEqual(out.rstrip(), b'test with stdout=1')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000643
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200644 def test_stdout_devnull(self):
645 p = subprocess.Popen([sys.executable, "-c",
646 'for i in range(10240):'
647 'print("x" * 1024)'],
648 stdout=subprocess.DEVNULL)
649 p.wait()
650 self.assertEqual(p.stdout, None)
651
652 def test_stderr_devnull(self):
653 p = subprocess.Popen([sys.executable, "-c",
654 'import sys\n'
655 'for i in range(10240):'
656 'sys.stderr.write("x" * 1024)'],
657 stderr=subprocess.DEVNULL)
658 p.wait()
659 self.assertEqual(p.stderr, None)
660
661 def test_stdin_devnull(self):
662 p = subprocess.Popen([sys.executable, "-c",
663 'import sys;'
664 'sys.stdin.read(1)'],
665 stdin=subprocess.DEVNULL)
666 p.wait()
667 self.assertEqual(p.stdin, None)
668
Gregory P. Smith786addd2020-10-20 17:37:20 -0700669 @unittest.skipUnless(fcntl and hasattr(fcntl, 'F_GETPIPE_SZ'),
670 'fcntl.F_GETPIPE_SZ required for test.')
Ruben Vorderman23c0fb82020-10-20 01:30:02 +0200671 def test_pipesizes(self):
Gregory P. Smith786addd2020-10-20 17:37:20 -0700672 test_pipe_r, test_pipe_w = os.pipe()
673 try:
674 # Get the default pipesize with F_GETPIPE_SZ
675 pipesize_default = fcntl.fcntl(test_pipe_w, fcntl.F_GETPIPE_SZ)
676 finally:
677 os.close(test_pipe_r)
678 os.close(test_pipe_w)
679 pipesize = pipesize_default // 2
680 if pipesize < 512: # the POSIX minimum
681 raise unittest.SkitTest(
682 'default pipesize too small to perform test.')
683 p = subprocess.Popen(
684 [sys.executable, "-c",
685 'import sys; sys.stdin.read(); sys.stdout.write("out"); '
686 'sys.stderr.write("error!")'],
687 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
688 stderr=subprocess.PIPE, pipesize=pipesize)
689 try:
Ruben Vorderman23c0fb82020-10-20 01:30:02 +0200690 for fifo in [p.stdin, p.stdout, p.stderr]:
691 self.assertEqual(
Gregory P. Smith786addd2020-10-20 17:37:20 -0700692 fcntl.fcntl(fifo.fileno(), fcntl.F_GETPIPE_SZ),
693 pipesize)
694 # Windows pipe size can be acquired via GetNamedPipeInfoFunction
695 # https://docs.microsoft.com/en-us/windows/win32/api/namedpipeapi/nf-namedpipeapi-getnamedpipeinfo
696 # However, this function is not yet in _winapi.
697 p.stdin.write(b"pear")
698 p.stdin.close()
699 finally:
700 p.kill()
701 p.wait()
702
703 @unittest.skipUnless(fcntl and hasattr(fcntl, 'F_GETPIPE_SZ'),
704 'fcntl.F_GETPIPE_SZ required for test.')
705 def test_pipesize_default(self):
706 p = subprocess.Popen(
707 [sys.executable, "-c",
708 'import sys; sys.stdin.read(); sys.stdout.write("out"); '
709 'sys.stderr.write("error!")'],
710 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
711 stderr=subprocess.PIPE, pipesize=-1)
712 try:
713 fp_r, fp_w = os.pipe()
714 try:
715 default_pipesize = fcntl.fcntl(fp_w, fcntl.F_GETPIPE_SZ)
716 for fifo in [p.stdin, p.stdout, p.stderr]:
717 self.assertEqual(
718 fcntl.fcntl(fifo.fileno(), fcntl.F_GETPIPE_SZ),
719 default_pipesize)
720 finally:
721 os.close(fp_r)
722 os.close(fp_w)
723 # On other platforms we cannot test the pipe size (yet). But above
724 # code using pipesize=-1 should not crash.
725 p.stdin.close()
726 finally:
727 p.kill()
728 p.wait()
Ruben Vorderman23c0fb82020-10-20 01:30:02 +0200729
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000730 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000731 newenv = os.environ.copy()
732 newenv["FRUIT"] = "orange"
Victor Stinnerf1512a22011-06-21 17:18:38 +0200733 with subprocess.Popen([sys.executable, "-c",
734 'import sys,os;'
735 'sys.stdout.write(os.getenv("FRUIT"))'],
736 stdout=subprocess.PIPE,
737 env=newenv) as p:
738 stdout, stderr = p.communicate()
739 self.assertEqual(stdout, b"orange")
740
Victor Stinner62d51182011-06-23 01:02:25 +0200741 # Windows requires at least the SYSTEMROOT environment variable to start
742 # Python
743 @unittest.skipIf(sys.platform == 'win32',
744 'cannot test an empty env on Windows')
Gregory P. Smithb3512482017-05-30 14:40:37 -0700745 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') == 1,
746 'The Python shared library cannot be loaded '
747 'with an empty environment.')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200748 def test_empty_env(self):
Gregory P. Smithb3512482017-05-30 14:40:37 -0700749 """Verify that env={} is as empty as possible."""
750
Gregory P. Smith85aba232017-05-30 16:21:47 -0700751 def is_env_var_to_ignore(n):
Gregory P. Smithb3512482017-05-30 14:40:37 -0700752 """Determine if an environment variable is under our control."""
753 # This excludes some __CF_* and VERSIONER_* keys MacOS insists
754 # on adding even when the environment in exec is empty.
755 # Gentoo sandboxes also force LD_PRELOAD and SANDBOX_* to exist.
Gregory P. Smith85aba232017-05-30 16:21:47 -0700756 return ('VERSIONER' in n or '__CF' in n or # MacOS
Nick Coghlan6ea41862017-06-11 13:16:15 +1000757 n == 'LD_PRELOAD' or n.startswith('SANDBOX') or # Gentoo
758 n == 'LC_CTYPE') # Locale coercion triggered
Gregory P. Smithb3512482017-05-30 14:40:37 -0700759
Victor Stinnerf1512a22011-06-21 17:18:38 +0200760 with subprocess.Popen([sys.executable, "-c",
Gregory P. Smithb3512482017-05-30 14:40:37 -0700761 'import os; print(list(os.environ.keys()))'],
762 stdout=subprocess.PIPE, env={}) as p:
Victor Stinnerf1512a22011-06-21 17:18:38 +0200763 stdout, stderr = p.communicate()
Gregory P. Smithb3512482017-05-30 14:40:37 -0700764 child_env_names = eval(stdout.strip())
765 self.assertIsInstance(child_env_names, list)
766 child_env_names = [k for k in child_env_names
767 if not is_env_var_to_ignore(k)]
768 self.assertEqual(child_env_names, [])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000769
Serhiy Storchakad174d242017-06-23 19:39:27 +0300770 def test_invalid_cmd(self):
771 # null character in the command name
772 cmd = sys.executable + '\0'
773 with self.assertRaises(ValueError):
774 subprocess.Popen([cmd, "-c", "pass"])
775
776 # null character in the command argument
777 with self.assertRaises(ValueError):
778 subprocess.Popen([sys.executable, "-c", "pass#\0"])
779
780 def test_invalid_env(self):
Ville Skyttä49b27342017-08-03 09:00:59 +0300781 # null character in the environment variable name
Serhiy Storchakad174d242017-06-23 19:39:27 +0300782 newenv = os.environ.copy()
783 newenv["FRUIT\0VEGETABLE"] = "cabbage"
784 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700785 subprocess.Popen(ZERO_RETURN_CMD, env=newenv)
Serhiy Storchakad174d242017-06-23 19:39:27 +0300786
Ville Skyttä49b27342017-08-03 09:00:59 +0300787 # null character in the environment variable value
Serhiy Storchakad174d242017-06-23 19:39:27 +0300788 newenv = os.environ.copy()
789 newenv["FRUIT"] = "orange\0VEGETABLE=cabbage"
790 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700791 subprocess.Popen(ZERO_RETURN_CMD, env=newenv)
Serhiy Storchakad174d242017-06-23 19:39:27 +0300792
Ville Skyttä49b27342017-08-03 09:00:59 +0300793 # equal character in the environment variable name
Serhiy Storchakad174d242017-06-23 19:39:27 +0300794 newenv = os.environ.copy()
795 newenv["FRUIT=ORANGE"] = "lemon"
796 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700797 subprocess.Popen(ZERO_RETURN_CMD, env=newenv)
Serhiy Storchakad174d242017-06-23 19:39:27 +0300798
Ville Skyttä49b27342017-08-03 09:00:59 +0300799 # equal character in the environment variable value
Serhiy Storchakad174d242017-06-23 19:39:27 +0300800 newenv = os.environ.copy()
801 newenv["FRUIT"] = "orange=lemon"
802 with subprocess.Popen([sys.executable, "-c",
803 'import sys, os;'
804 'sys.stdout.write(os.getenv("FRUIT"))'],
805 stdout=subprocess.PIPE,
806 env=newenv) as p:
807 stdout, stderr = p.communicate()
808 self.assertEqual(stdout, b"orange=lemon")
809
Peter Astrandcbac93c2005-03-03 20:24:28 +0000810 def test_communicate_stdin(self):
811 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000812 'import sys;'
813 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000814 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000815 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000816 self.assertEqual(p.returncode, 1)
817
818 def test_communicate_stdout(self):
819 p = subprocess.Popen([sys.executable, "-c",
820 'import sys; sys.stdout.write("pineapple")'],
821 stdout=subprocess.PIPE)
822 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000823 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000824 self.assertEqual(stderr, None)
825
826 def test_communicate_stderr(self):
827 p = subprocess.Popen([sys.executable, "-c",
828 'import sys; sys.stderr.write("pineapple")'],
829 stderr=subprocess.PIPE)
830 (stdout, stderr) = p.communicate()
831 self.assertEqual(stdout, None)
Victor Stinner6cac1132019-12-08 08:38:16 +0100832 self.assertEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000833
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000834 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000835 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000836 'import sys,os;'
837 'sys.stderr.write("pineapple");'
838 'sys.stdout.write(sys.stdin.read())'],
839 stdin=subprocess.PIPE,
840 stdout=subprocess.PIPE,
841 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000842 self.addCleanup(p.stdout.close)
843 self.addCleanup(p.stderr.close)
844 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000845 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000846 self.assertEqual(stdout, b"banana")
Victor Stinner6cac1132019-12-08 08:38:16 +0100847 self.assertEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000848
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400849 def test_communicate_timeout(self):
850 p = subprocess.Popen([sys.executable, "-c",
851 'import sys,os,time;'
852 'sys.stderr.write("pineapple\\n");'
853 'time.sleep(1);'
854 'sys.stderr.write("pear\\n");'
855 'sys.stdout.write(sys.stdin.read())'],
856 universal_newlines=True,
857 stdin=subprocess.PIPE,
858 stdout=subprocess.PIPE,
859 stderr=subprocess.PIPE)
860 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
861 timeout=0.3)
862 # Make sure we can keep waiting for it, and that we get the whole output
863 # after it completes.
864 (stdout, stderr) = p.communicate()
865 self.assertEqual(stdout, "banana")
Victor Stinner6cac1132019-12-08 08:38:16 +0100866 self.assertEqual(stderr.encode(), b"pineapple\npear\n")
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400867
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700868 def test_communicate_timeout_large_output(self):
Ross Lagerwall003c7a32012-02-12 09:02:01 +0200869 # Test an expiring timeout while the child is outputting lots of data.
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400870 p = subprocess.Popen([sys.executable, "-c",
871 'import sys,os,time;'
872 'sys.stdout.write("a" * (64 * 1024));'
873 'time.sleep(0.2);'
874 'sys.stdout.write("a" * (64 * 1024));'
875 'time.sleep(0.2);'
876 'sys.stdout.write("a" * (64 * 1024));'
877 'time.sleep(0.2);'
878 'sys.stdout.write("a" * (64 * 1024));'],
879 stdout=subprocess.PIPE)
880 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
881 (stdout, _) = p.communicate()
882 self.assertEqual(len(stdout), 4 * 64 * 1024)
883
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000884 # Test for the fd leak reported in http://bugs.python.org/issue2791.
885 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000886 for stdin_pipe in (False, True):
887 for stdout_pipe in (False, True):
888 for stderr_pipe in (False, True):
889 options = {}
890 if stdin_pipe:
891 options['stdin'] = subprocess.PIPE
892 if stdout_pipe:
893 options['stdout'] = subprocess.PIPE
894 if stderr_pipe:
895 options['stderr'] = subprocess.PIPE
896 if not options:
897 continue
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700898 p = subprocess.Popen(ZERO_RETURN_CMD, **options)
Victor Stinner667d4b52010-12-25 22:40:32 +0000899 p.communicate()
900 if p.stdin is not None:
901 self.assertTrue(p.stdin.closed)
902 if p.stdout is not None:
903 self.assertTrue(p.stdout.closed)
904 if p.stderr is not None:
905 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000906
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000907 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000908 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000909 p = subprocess.Popen([sys.executable, "-c",
910 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000911 (stdout, stderr) = p.communicate()
912 self.assertEqual(stdout, None)
913 self.assertEqual(stderr, None)
914
915 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000916 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000917 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000918 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000919 x, y = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000920 os.close(x)
921 os.close(y)
922 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000923 'import sys,os;'
924 'sys.stdout.write(sys.stdin.read(47));'
Charles-François Natali2d517212011-05-29 16:36:44 +0200925 'sys.stderr.write("x" * %d);'
926 'sys.stdout.write(sys.stdin.read())' %
927 support.PIPE_MAX_SIZE],
Guido van Rossum98297ee2007-11-06 21:34:58 +0000928 stdin=subprocess.PIPE,
929 stdout=subprocess.PIPE,
930 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000931 self.addCleanup(p.stdout.close)
932 self.addCleanup(p.stderr.close)
933 self.addCleanup(p.stdin.close)
Charles-François Natali2d517212011-05-29 16:36:44 +0200934 string_to_write = b"a" * support.PIPE_MAX_SIZE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000935 (stdout, stderr) = p.communicate(string_to_write)
936 self.assertEqual(stdout, string_to_write)
937
938 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000939 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000940 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000941 'import sys,os;'
942 'sys.stdout.write(sys.stdin.read())'],
943 stdin=subprocess.PIPE,
944 stdout=subprocess.PIPE,
945 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000946 self.addCleanup(p.stdout.close)
947 self.addCleanup(p.stderr.close)
948 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000949 p.stdin.write(b"banana")
950 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000951 self.assertEqual(stdout, b"bananasplit")
Victor Stinner6cac1132019-12-08 08:38:16 +0100952 self.assertEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000953
andyclegg7fed7bd2017-10-23 03:01:19 +0100954 def test_universal_newlines_and_text(self):
955 args = [
956 sys.executable, "-c",
957 'import sys,os;' + SETBINARY +
958 'buf = sys.stdout.buffer;'
959 'buf.write(sys.stdin.readline().encode());'
960 'buf.flush();'
961 'buf.write(b"line2\\n");'
962 'buf.flush();'
963 'buf.write(sys.stdin.read().encode());'
964 'buf.flush();'
965 'buf.write(b"line4\\n");'
966 'buf.flush();'
967 'buf.write(b"line5\\r\\n");'
968 'buf.flush();'
969 'buf.write(b"line6\\r");'
970 'buf.flush();'
971 'buf.write(b"\\nline7");'
972 'buf.flush();'
973 'buf.write(b"\\nline8");']
974
975 for extra_kwarg in ('universal_newlines', 'text'):
976 p = subprocess.Popen(args, **{'stdin': subprocess.PIPE,
977 'stdout': subprocess.PIPE,
978 extra_kwarg: True})
979 with p:
980 p.stdin.write("line1\n")
981 p.stdin.flush()
982 self.assertEqual(p.stdout.readline(), "line1\n")
983 p.stdin.write("line3\n")
984 p.stdin.close()
985 self.addCleanup(p.stdout.close)
986 self.assertEqual(p.stdout.readline(),
987 "line2\n")
988 self.assertEqual(p.stdout.read(6),
989 "line3\n")
990 self.assertEqual(p.stdout.read(),
991 "line4\nline5\nline6\nline7\nline8")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000992
993 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000994 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000995 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000996 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200997 'buf = sys.stdout.buffer;'
998 'buf.write(b"line2\\n");'
999 'buf.flush();'
1000 'buf.write(b"line4\\n");'
1001 'buf.flush();'
1002 'buf.write(b"line5\\r\\n");'
1003 'buf.flush();'
1004 'buf.write(b"line6\\r");'
1005 'buf.flush();'
1006 'buf.write(b"\\nline7");'
1007 'buf.flush();'
1008 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +02001009 stderr=subprocess.PIPE,
1010 stdout=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +00001011 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +00001012 self.addCleanup(p.stdout.close)
1013 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001014 (stdout, stderr) = p.communicate()
Antoine Pitrouab85ff32011-07-23 22:03:45 +02001015 self.assertEqual(stdout,
1016 "line2\nline4\nline5\nline6\nline7\nline8")
1017
1018 def test_universal_newlines_communicate_stdin(self):
1019 # universal newlines through communicate(), with only stdin
1020 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +03001021 'import sys,os;' + SETBINARY + textwrap.dedent('''
1022 s = sys.stdin.readline()
1023 assert s == "line1\\n", repr(s)
1024 s = sys.stdin.read()
1025 assert s == "line3\\n", repr(s)
1026 ''')],
Antoine Pitrouab85ff32011-07-23 22:03:45 +02001027 stdin=subprocess.PIPE,
1028 universal_newlines=1)
1029 (stdout, stderr) = p.communicate("line1\nline3\n")
1030 self.assertEqual(p.returncode, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001031
Andrew Svetlovf3765072012-08-14 18:35:17 +03001032 def test_universal_newlines_communicate_input_none(self):
1033 # Test communicate(input=None) with universal newlines.
1034 #
1035 # We set stdout to PIPE because, as of this writing, a different
1036 # code path is tested when the number of pipes is zero or one.
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001037 p = subprocess.Popen(ZERO_RETURN_CMD,
Andrew Svetlovf3765072012-08-14 18:35:17 +03001038 stdin=subprocess.PIPE,
1039 stdout=subprocess.PIPE,
1040 universal_newlines=True)
1041 p.communicate()
1042 self.assertEqual(p.returncode, 0)
1043
Andrew Svetlov5395d2f2012-08-15 22:46:43 +03001044 def test_universal_newlines_communicate_stdin_stdout_stderr(self):
Andrew Svetlov47ec25d2012-08-19 16:25:37 +03001045 # universal newlines through communicate(), with stdin, stdout, stderr
Andrew Svetlov5395d2f2012-08-15 22:46:43 +03001046 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +03001047 'import sys,os;' + SETBINARY + textwrap.dedent('''
1048 s = sys.stdin.buffer.readline()
1049 sys.stdout.buffer.write(s)
1050 sys.stdout.buffer.write(b"line2\\r")
1051 sys.stderr.buffer.write(b"eline2\\n")
1052 s = sys.stdin.buffer.read()
1053 sys.stdout.buffer.write(s)
1054 sys.stdout.buffer.write(b"line4\\n")
1055 sys.stdout.buffer.write(b"line5\\r\\n")
1056 sys.stderr.buffer.write(b"eline6\\r")
1057 sys.stderr.buffer.write(b"eline7\\r\\nz")
1058 ''')],
Andrew Svetlov5395d2f2012-08-15 22:46:43 +03001059 stdin=subprocess.PIPE,
1060 stderr=subprocess.PIPE,
1061 stdout=subprocess.PIPE,
Andrew Svetlov47ec25d2012-08-19 16:25:37 +03001062 universal_newlines=True)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +03001063 self.addCleanup(p.stdout.close)
1064 self.addCleanup(p.stderr.close)
1065 (stdout, stderr) = p.communicate("line1\nline3\n")
1066 self.assertEqual(p.returncode, 0)
Andrew Svetlov943c5b32012-08-16 20:17:47 +03001067 self.assertEqual("line1\nline2\nline3\nline4\nline5\n", stdout)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +03001068 # Python debug build push something like "[42442 refs]\n"
1069 # to stderr at exit of subprocess.
Andrew Svetlov943c5b32012-08-16 20:17:47 +03001070 self.assertTrue(stderr.startswith("eline2\neline6\neline7\n"))
Andrew Svetlov5395d2f2012-08-15 22:46:43 +03001071
Andrew Svetlov82860712012-08-19 22:13:41 +03001072 def test_universal_newlines_communicate_encodings(self):
1073 # Check that universal newlines mode works for various encodings,
1074 # in particular for encodings in the UTF-16 and UTF-32 families.
1075 # See issue #15595.
1076 #
1077 # UTF-16 and UTF-32-BE are sufficient to check both with BOM and
1078 # without, and UTF-16 and UTF-32.
1079 for encoding in ['utf-16', 'utf-32-be']:
Andrew Svetlov82860712012-08-19 22:13:41 +03001080 code = ("import sys; "
1081 r"sys.stdout.buffer.write('1\r\n2\r3\n4'.encode('%s'))" %
1082 encoding)
1083 args = [sys.executable, '-c', code]
Steve Dower050acae2016-09-06 20:16:17 -07001084 # We set stdin to be non-None because, as of this writing,
1085 # a different code path is used when the number of pipes is
1086 # zero or one.
1087 popen = subprocess.Popen(args,
1088 stdin=subprocess.PIPE,
1089 stdout=subprocess.PIPE,
1090 encoding=encoding)
1091 stdout, stderr = popen.communicate(input='')
Andrew Svetlov82860712012-08-19 22:13:41 +03001092 self.assertEqual(stdout, '1\n2\n3\n4')
1093
Steve Dower050acae2016-09-06 20:16:17 -07001094 def test_communicate_errors(self):
1095 for errors, expected in [
1096 ('ignore', ''),
1097 ('replace', '\ufffd\ufffd'),
1098 ('surrogateescape', '\udc80\udc80'),
1099 ('backslashreplace', '\\x80\\x80'),
1100 ]:
1101 code = ("import sys; "
1102 r"sys.stdout.buffer.write(b'[\x80\x80]')")
1103 args = [sys.executable, '-c', code]
1104 # We set stdin to be non-None because, as of this writing,
1105 # a different code path is used when the number of pipes is
1106 # zero or one.
1107 popen = subprocess.Popen(args,
1108 stdin=subprocess.PIPE,
1109 stdout=subprocess.PIPE,
1110 encoding='utf-8',
1111 errors=errors)
1112 stdout, stderr = popen.communicate(input='')
1113 self.assertEqual(stdout, '[{}]'.format(expected))
1114
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001115 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +00001116 # Make sure we leak no resources
Victor Stinner937ee9e2018-06-26 02:11:06 +02001117 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +00001118 max_handles = 1026 # too much for most UNIX systems
1119 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +00001120 max_handles = 2050 # too much for (at least some) Windows setups
1121 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001122 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +00001123 try:
1124 for i in range(max_handles):
1125 try:
Hai Shi0c4f0f32020-06-30 21:46:31 +08001126 tmpfile = os.path.join(tmpdir, os_helper.TESTFN)
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001127 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +00001128 except OSError as e:
1129 if e.errno != errno.EMFILE:
1130 raise
1131 break
1132 else:
1133 self.skipTest("failed to reach the file descriptor limit "
1134 "(tried %d)" % max_handles)
1135 # Close a couple of them (should be enough for a subprocess)
1136 for i in range(10):
1137 os.close(handles.pop())
1138 # Loop creating some subprocesses. If one of them leaks some fds,
1139 # the next loop iteration will fail by reaching the max fd limit.
1140 for i in range(15):
1141 p = subprocess.Popen([sys.executable, "-c",
1142 "import sys;"
1143 "sys.stdout.write(sys.stdin.read())"],
1144 stdin=subprocess.PIPE,
1145 stdout=subprocess.PIPE,
1146 stderr=subprocess.PIPE)
1147 data = p.communicate(b"lime")[0]
1148 self.assertEqual(data, b"lime")
1149 finally:
1150 for h in handles:
1151 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001152 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001153
1154 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001155 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
1156 '"a b c" d e')
1157 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
1158 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +00001159 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
1160 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001161 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
1162 'a\\\\\\b "de fg" h')
1163 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
1164 'a\\\\\\"b c d')
1165 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
1166 '"a\\\\b c" d e')
1167 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
1168 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001169 self.assertEqual(subprocess.list2cmdline(['ab', '']),
1170 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001171
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001172 def test_poll(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001173 p = subprocess.Popen([sys.executable, "-c",
Ross Lagerwalle7ad4192012-02-22 06:02:07 +02001174 "import os; os.read(0, 1)"],
1175 stdin=subprocess.PIPE)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001176 self.addCleanup(p.stdin.close)
1177 self.assertIsNone(p.poll())
1178 os.write(p.stdin.fileno(), b'A')
1179 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001180 # Subsequent invocations should just return the returncode
1181 self.assertEqual(p.poll(), 0)
1182
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001183 def test_wait(self):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001184 p = subprocess.Popen(ZERO_RETURN_CMD)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001185 self.assertEqual(p.wait(), 0)
1186 # Subsequent invocations should just return the returncode
1187 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +00001188
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001189 def test_wait_timeout(self):
1190 p = subprocess.Popen([sys.executable,
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001191 "-c", "import time; time.sleep(0.3)"])
Reid Kleckner2b228f02011-03-16 16:57:54 -04001192 with self.assertRaises(subprocess.TimeoutExpired) as c:
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001193 p.wait(timeout=0.0001)
1194 self.assertIn("0.0001", str(c.exception)) # For coverage of __str__.
Victor Stinner0d63bac2019-12-11 11:30:03 +01001195 self.assertEqual(p.wait(timeout=support.SHORT_TIMEOUT), 0)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001196
Peter Astrand738131d2004-11-30 21:04:45 +00001197 def test_invalid_bufsize(self):
1198 # an invalid type of the bufsize argument should raise
1199 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001200 with self.assertRaises(TypeError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001201 subprocess.Popen(ZERO_RETURN_CMD, "orange")
Peter Astrand738131d2004-11-30 21:04:45 +00001202
Guido van Rossum46a05a72007-06-07 21:56:45 +00001203 def test_bufsize_is_none(self):
1204 # bufsize=None should be the same as bufsize=0.
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001205 p = subprocess.Popen(ZERO_RETURN_CMD, None)
Guido van Rossum46a05a72007-06-07 21:56:45 +00001206 self.assertEqual(p.wait(), 0)
1207 # Again with keyword arg
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001208 p = subprocess.Popen(ZERO_RETURN_CMD, bufsize=None)
Guido van Rossum46a05a72007-06-07 21:56:45 +00001209 self.assertEqual(p.wait(), 0)
1210
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001211 def _test_bufsize_equal_one(self, line, expected, universal_newlines):
1212 # subprocess may deadlock with bufsize=1, see issue #21332
1213 with subprocess.Popen([sys.executable, "-c", "import sys;"
1214 "sys.stdout.write(sys.stdin.readline());"
1215 "sys.stdout.flush()"],
1216 stdin=subprocess.PIPE,
1217 stdout=subprocess.PIPE,
1218 stderr=subprocess.DEVNULL,
1219 bufsize=1,
1220 universal_newlines=universal_newlines) as p:
1221 p.stdin.write(line) # expect that it flushes the line in text mode
1222 os.close(p.stdin.fileno()) # close it without flushing the buffer
1223 read_line = p.stdout.readline()
Segev Finer4d385172017-08-18 16:18:13 +03001224 with support.SuppressCrashReport():
1225 try:
1226 p.stdin.close()
1227 except OSError:
1228 pass
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001229 p.stdin = None
1230 self.assertEqual(p.returncode, 0)
1231 self.assertEqual(read_line, expected)
1232
1233 def test_bufsize_equal_one_text_mode(self):
1234 # line is flushed in text mode with bufsize=1.
1235 # we should get the full line in return
1236 line = "line\n"
1237 self._test_bufsize_equal_one(line, line, universal_newlines=True)
1238
1239 def test_bufsize_equal_one_binary_mode(self):
1240 # line is not flushed in binary mode with bufsize=1.
1241 # we should get empty response
1242 line = b'line' + os.linesep.encode() # assume ascii-based locale
Alexey Izbysheva2670562018-10-20 03:22:31 +03001243 with self.assertWarnsRegex(RuntimeWarning, 'line buffering'):
1244 self._test_bufsize_equal_one(line, b'', universal_newlines=False)
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001245
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001246 def test_leaking_fds_on_error(self):
1247 # see bug #5179: Popen leaks file descriptors to PIPEs if
1248 # the child fails to execute; this will eventually exhaust
1249 # the maximum number of open fds. 1024 seems a very common
1250 # value for that limit, but Windows has 2048, so we loop
1251 # 1024 times (each call leaked two fds).
1252 for i in range(1024):
Victor Stinnerb31206a2018-01-25 19:06:05 +01001253 with self.assertRaises(NONEXISTING_ERRORS):
Victor Stinner9a83f652017-08-21 23:51:31 +02001254 subprocess.Popen(NONEXISTING_CMD,
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001255 stdout=subprocess.PIPE,
1256 stderr=subprocess.PIPE)
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001257
Victor Stinner9a83f652017-08-21 23:51:31 +02001258 def test_nonexisting_with_pipes(self):
1259 # bpo-30121: Popen with pipes must close properly pipes on error.
1260 # Previously, os.close() was called with a Windows handle which is not
1261 # a valid file descriptor.
1262 #
1263 # Run the test in a subprocess to control how the CRT reports errors
1264 # and to get stderr content.
1265 try:
1266 import msvcrt
1267 msvcrt.CrtSetReportMode
1268 except (AttributeError, ImportError):
1269 self.skipTest("need msvcrt.CrtSetReportMode")
1270
1271 code = textwrap.dedent(f"""
1272 import msvcrt
1273 import subprocess
1274
1275 cmd = {NONEXISTING_CMD!r}
1276
1277 for report_type in [msvcrt.CRT_WARN,
1278 msvcrt.CRT_ERROR,
1279 msvcrt.CRT_ASSERT]:
1280 msvcrt.CrtSetReportMode(report_type, msvcrt.CRTDBG_MODE_FILE)
1281 msvcrt.CrtSetReportFile(report_type, msvcrt.CRTDBG_FILE_STDERR)
1282
1283 try:
Zachary Ware55376462018-02-19 14:02:38 -06001284 subprocess.Popen(cmd,
Victor Stinner9a83f652017-08-21 23:51:31 +02001285 stdout=subprocess.PIPE,
1286 stderr=subprocess.PIPE)
1287 except OSError:
1288 pass
1289 """)
1290 cmd = [sys.executable, "-c", code]
1291 proc = subprocess.Popen(cmd,
1292 stderr=subprocess.PIPE,
1293 universal_newlines=True)
1294 with proc:
1295 stderr = proc.communicate()[1]
1296 self.assertEqual(stderr, "")
1297 self.assertEqual(proc.returncode, 0)
1298
Antoine Pitroua8392712013-08-30 23:38:13 +02001299 def test_double_close_on_error(self):
1300 # Issue #18851
1301 fds = []
1302 def open_fds():
1303 for i in range(20):
1304 fds.extend(os.pipe())
1305 time.sleep(0.001)
1306 t = threading.Thread(target=open_fds)
1307 t.start()
1308 try:
1309 with self.assertRaises(EnvironmentError):
Victor Stinner9a83f652017-08-21 23:51:31 +02001310 subprocess.Popen(NONEXISTING_CMD,
Antoine Pitroua8392712013-08-30 23:38:13 +02001311 stdin=subprocess.PIPE,
1312 stdout=subprocess.PIPE,
1313 stderr=subprocess.PIPE)
1314 finally:
1315 t.join()
1316 exc = None
1317 for fd in fds:
1318 # If a double close occurred, some of those fds will
1319 # already have been closed by mistake, and os.close()
1320 # here will raise.
1321 try:
1322 os.close(fd)
1323 except OSError as e:
1324 exc = e
1325 if exc is not None:
1326 raise exc
1327
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001328 def test_threadsafe_wait(self):
1329 """Issue21291: Popen.wait() needs to be threadsafe for returncode."""
1330 proc = subprocess.Popen([sys.executable, '-c',
1331 'import time; time.sleep(12)'])
1332 self.assertEqual(proc.returncode, None)
1333 results = []
1334
1335 def kill_proc_timer_thread():
1336 results.append(('thread-start-poll-result', proc.poll()))
1337 # terminate it from the thread and wait for the result.
1338 proc.kill()
1339 proc.wait()
1340 results.append(('thread-after-kill-and-wait', proc.returncode))
1341 # this wait should be a no-op given the above.
1342 proc.wait()
1343 results.append(('thread-after-second-wait', proc.returncode))
1344
1345 # This is a timing sensitive test, the failure mode is
1346 # triggered when both the main thread and this thread are in
1347 # the wait() call at once. The delay here is to allow the
1348 # main thread to most likely be blocked in its wait() call.
1349 t = threading.Timer(0.2, kill_proc_timer_thread)
1350 t.start()
1351
Victor Stinner937ee9e2018-06-26 02:11:06 +02001352 if mswindows:
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001353 expected_errorcode = 1
1354 else:
1355 # Should be -9 because of the proc.kill() from the thread.
1356 expected_errorcode = -9
1357
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001358 # Wait for the process to finish; the thread should kill it
1359 # long before it finishes on its own. Supplying a timeout
1360 # triggers a different code path for better coverage.
Victor Stinner0d63bac2019-12-11 11:30:03 +01001361 proc.wait(timeout=support.SHORT_TIMEOUT)
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001362 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001363 msg="unexpected result in wait from main thread")
1364
1365 # This should be a no-op with no change in returncode.
1366 proc.wait()
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001367 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001368 msg="unexpected result in second main wait.")
1369
1370 t.join()
1371 # Ensure that all of the thread results are as expected.
1372 # When a race condition occurs in wait(), the returncode could
1373 # be set by the wrong thread that doesn't actually have it
1374 # leading to an incorrect value.
1375 self.assertEqual([('thread-start-poll-result', None),
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001376 ('thread-after-kill-and-wait', expected_errorcode),
1377 ('thread-after-second-wait', expected_errorcode)],
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001378 results)
1379
Victor Stinnerb3693582010-05-21 20:13:12 +00001380 def test_issue8780(self):
1381 # Ensure that stdout is inherited from the parent
1382 # if stdout=PIPE is not used
1383 code = ';'.join((
1384 'import subprocess, sys',
1385 'retcode = subprocess.call('
1386 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
1387 'assert retcode == 0'))
1388 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001389 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +00001390
Tim Goldenaf5ac392010-08-06 13:03:56 +00001391 def test_handles_closed_on_exception(self):
1392 # If CreateProcess exits with an error, ensure the
1393 # duplicate output handles are released
Berker Peksag16a1f282015-09-28 13:33:14 +03001394 ifhandle, ifname = tempfile.mkstemp()
1395 ofhandle, ofname = tempfile.mkstemp()
1396 efhandle, efname = tempfile.mkstemp()
Tim Goldenaf5ac392010-08-06 13:03:56 +00001397 try:
1398 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
1399 stderr=efhandle)
1400 except OSError:
1401 os.close(ifhandle)
1402 os.remove(ifname)
1403 os.close(ofhandle)
1404 os.remove(ofname)
1405 os.close(efhandle)
1406 os.remove(efname)
1407 self.assertFalse(os.path.exists(ifname))
1408 self.assertFalse(os.path.exists(ofname))
1409 self.assertFalse(os.path.exists(efname))
1410
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001411 def test_communicate_epipe(self):
1412 # Issue 10963: communicate() should hide EPIPE
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001413 p = subprocess.Popen(ZERO_RETURN_CMD,
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001414 stdin=subprocess.PIPE,
1415 stdout=subprocess.PIPE,
1416 stderr=subprocess.PIPE)
1417 self.addCleanup(p.stdout.close)
1418 self.addCleanup(p.stderr.close)
1419 self.addCleanup(p.stdin.close)
1420 p.communicate(b"x" * 2**20)
1421
Andrey Doroschenko645005e2019-11-17 17:08:31 +03001422 def test_repr(self):
1423 # Run a command that waits for user input, to check the repr() of
1424 # a Proc object while and after the sub-process runs.
1425 code = 'import sys; input(); sys.exit(57)'
1426 cmd = [sys.executable, '-c', code]
1427 result = "<Popen: returncode: {}"
1428
1429 with subprocess.Popen(
1430 cmd, stdin=subprocess.PIPE, universal_newlines=True) as proc:
1431 self.assertIsNone(proc.returncode)
1432 self.assertTrue(
1433 repr(proc).startswith(result.format(proc.returncode)) and
1434 repr(proc).endswith('>')
1435 )
1436
1437 proc.communicate(input='exit...\n')
1438 proc.wait()
1439
1440 self.assertIsNotNone(proc.returncode)
1441 self.assertTrue(
1442 repr(proc).startswith(result.format(proc.returncode)) and
1443 repr(proc).endswith('>')
1444 )
1445
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001446 def test_communicate_epipe_only_stdin(self):
1447 # Issue 10963: communicate() should hide EPIPE
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001448 p = subprocess.Popen(ZERO_RETURN_CMD,
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001449 stdin=subprocess.PIPE)
1450 self.addCleanup(p.stdin.close)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001451 p.wait()
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001452 p.communicate(b"x" * 2**20)
1453
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001454 @unittest.skipUnless(hasattr(signal, 'SIGUSR1'),
1455 "Requires signal.SIGUSR1")
1456 @unittest.skipUnless(hasattr(os, 'kill'),
1457 "Requires os.kill")
1458 @unittest.skipUnless(hasattr(os, 'getppid'),
1459 "Requires os.getppid")
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001460 def test_communicate_eintr(self):
1461 # Issue #12493: communicate() should handle EINTR
1462 def handler(signum, frame):
1463 pass
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001464 old_handler = signal.signal(signal.SIGUSR1, handler)
1465 self.addCleanup(signal.signal, signal.SIGUSR1, old_handler)
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001466
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001467 args = [sys.executable, "-c",
1468 'import os, signal;'
1469 'os.kill(os.getppid(), signal.SIGUSR1)']
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001470 for stream in ('stdout', 'stderr'):
1471 kw = {stream: subprocess.PIPE}
1472 with subprocess.Popen(args, **kw) as process:
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001473 # communicate() will be interrupted by SIGUSR1
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001474 process.communicate()
1475
Tim Peterse718f612004-10-12 21:51:32 +00001476
Gregory P. Smith3d8e7762012-11-10 22:32:22 -08001477 # This test is Linux-ish specific for simplicity to at least have
1478 # some coverage. It is not a platform specific bug.
1479 @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
1480 "Linux specific")
1481 def test_failed_child_execute_fd_leak(self):
1482 """Test for the fork() failure fd leak reported in issue16327."""
1483 fd_directory = '/proc/%d/fd' % os.getpid()
1484 fds_before_popen = os.listdir(fd_directory)
1485 with self.assertRaises(PopenTestException):
1486 PopenExecuteChildRaises(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001487 ZERO_RETURN_CMD, stdin=subprocess.PIPE,
Gregory P. Smith3d8e7762012-11-10 22:32:22 -08001488 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1489
1490 # NOTE: This test doesn't verify that the real _execute_child
1491 # does not close the file descriptors itself on the way out
1492 # during an exception. Code inspection has confirmed that.
1493
1494 fds_after_exception = os.listdir(fd_directory)
1495 self.assertEqual(fds_before_popen, fds_after_exception)
1496
Victor Stinner937ee9e2018-06-26 02:11:06 +02001497 @unittest.skipIf(mswindows, "behavior currently not supported on Windows")
Gregory P. Smith8621bb52017-08-24 14:58:25 -07001498 def test_file_not_found_includes_filename(self):
1499 with self.assertRaises(FileNotFoundError) as c:
1500 subprocess.call(['/opt/nonexistent_binary', 'with', 'some', 'args'])
1501 self.assertEqual(c.exception.filename, '/opt/nonexistent_binary')
1502
Victor Stinner937ee9e2018-06-26 02:11:06 +02001503 @unittest.skipIf(mswindows, "behavior currently not supported on Windows")
Gregory P. Smith8621bb52017-08-24 14:58:25 -07001504 def test_file_not_found_with_bad_cwd(self):
1505 with self.assertRaises(FileNotFoundError) as c:
1506 subprocess.Popen(['exit', '0'], cwd='/some/nonexistent/directory')
1507 self.assertEqual(c.exception.filename, '/some/nonexistent/directory')
1508
Batuhan Taşkaya4dc5a9d2019-12-30 19:02:04 +03001509 def test_class_getitems(self):
Guido van Rossum48b069a2020-04-07 09:50:06 -07001510 self.assertIsInstance(subprocess.Popen[bytes], types.GenericAlias)
1511 self.assertIsInstance(subprocess.CompletedProcess[str], types.GenericAlias)
Gregory P. Smith6e730002015-04-14 16:14:25 -07001512
1513class RunFuncTestCase(BaseTestCase):
1514 def run_python(self, code, **kwargs):
1515 """Run Python code in a subprocess using subprocess.run"""
1516 argv = [sys.executable, "-c", code]
1517 return subprocess.run(argv, **kwargs)
1518
1519 def test_returncode(self):
1520 # call() function with sequence argument
1521 cp = self.run_python("import sys; sys.exit(47)")
1522 self.assertEqual(cp.returncode, 47)
1523 with self.assertRaises(subprocess.CalledProcessError):
1524 cp.check_returncode()
1525
1526 def test_check(self):
1527 with self.assertRaises(subprocess.CalledProcessError) as c:
1528 self.run_python("import sys; sys.exit(47)", check=True)
1529 self.assertEqual(c.exception.returncode, 47)
1530
1531 def test_check_zero(self):
1532 # check_returncode shouldn't raise when returncode is zero
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001533 cp = subprocess.run(ZERO_RETURN_CMD, check=True)
Gregory P. Smith6e730002015-04-14 16:14:25 -07001534 self.assertEqual(cp.returncode, 0)
1535
1536 def test_timeout(self):
1537 # run() function with timeout argument; we want to test that the child
1538 # process gets killed when the timeout expires. If the child isn't
1539 # killed, this call will deadlock since subprocess.run waits for the
1540 # child.
1541 with self.assertRaises(subprocess.TimeoutExpired):
1542 self.run_python("while True: pass", timeout=0.0001)
1543
1544 def test_capture_stdout(self):
1545 # capture stdout with zero return code
1546 cp = self.run_python("print('BDFL')", stdout=subprocess.PIPE)
1547 self.assertIn(b'BDFL', cp.stdout)
1548
1549 def test_capture_stderr(self):
1550 cp = self.run_python("import sys; sys.stderr.write('BDFL')",
1551 stderr=subprocess.PIPE)
1552 self.assertIn(b'BDFL', cp.stderr)
1553
1554 def test_check_output_stdin_arg(self):
1555 # run() can be called with stdin set to a file
1556 tf = tempfile.TemporaryFile()
1557 self.addCleanup(tf.close)
1558 tf.write(b'pear')
1559 tf.seek(0)
1560 cp = self.run_python(
1561 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1562 stdin=tf, stdout=subprocess.PIPE)
1563 self.assertIn(b'PEAR', cp.stdout)
1564
1565 def test_check_output_input_arg(self):
1566 # check_output() can be called with input set to a string
1567 cp = self.run_python(
1568 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1569 input=b'pear', stdout=subprocess.PIPE)
1570 self.assertIn(b'PEAR', cp.stdout)
1571
1572 def test_check_output_stdin_with_input_arg(self):
1573 # run() refuses to accept 'stdin' with 'input'
1574 tf = tempfile.TemporaryFile()
1575 self.addCleanup(tf.close)
1576 tf.write(b'pear')
1577 tf.seek(0)
1578 with self.assertRaises(ValueError,
1579 msg="Expected ValueError when stdin and input args supplied.") as c:
1580 output = self.run_python("print('will not be run')",
1581 stdin=tf, input=b'hare')
1582 self.assertIn('stdin', c.exception.args[0])
1583 self.assertIn('input', c.exception.args[0])
1584
1585 def test_check_output_timeout(self):
1586 with self.assertRaises(subprocess.TimeoutExpired) as c:
1587 cp = self.run_python((
1588 "import sys, time\n"
1589 "sys.stdout.write('BDFL')\n"
1590 "sys.stdout.flush()\n"
1591 "time.sleep(3600)"),
1592 # Some heavily loaded buildbots (sparc Debian 3.x) require
1593 # this much time to start and print.
1594 timeout=3, stdout=subprocess.PIPE)
1595 self.assertEqual(c.exception.output, b'BDFL')
1596 # output is aliased to stdout
1597 self.assertEqual(c.exception.stdout, b'BDFL')
1598
1599 def test_run_kwargs(self):
1600 newenv = os.environ.copy()
1601 newenv["FRUIT"] = "banana"
1602 cp = self.run_python(('import sys, os;'
1603 'sys.exit(33 if os.getenv("FRUIT")=="banana" else 31)'),
1604 env=newenv)
1605 self.assertEqual(cp.returncode, 33)
1606
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +03001607 def test_run_with_pathlike_path(self):
1608 # bpo-31961: test run(pathlike_object)
1609 # the name of a command that can be run without
Min ho Kimc4cacc82019-07-31 08:16:13 +10001610 # any arguments that exit fast
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +03001611 prog = 'tree.com' if mswindows else 'ls'
1612 path = shutil.which(prog)
1613 if path is None:
1614 self.skipTest(f'{prog} required for this test')
1615 path = FakePath(path)
1616 res = subprocess.run(path, stdout=subprocess.DEVNULL)
1617 self.assertEqual(res.returncode, 0)
1618 with self.assertRaises(TypeError):
1619 subprocess.run(path, stdout=subprocess.DEVNULL, shell=True)
1620
1621 def test_run_with_bytes_path_and_arguments(self):
1622 # bpo-31961: test run([bytes_object, b'additional arguments'])
1623 path = os.fsencode(sys.executable)
1624 args = [path, '-c', b'import sys; sys.exit(57)']
1625 res = subprocess.run(args)
1626 self.assertEqual(res.returncode, 57)
1627
1628 def test_run_with_pathlike_path_and_arguments(self):
1629 # bpo-31961: test run([pathlike_object, 'additional arguments'])
1630 path = FakePath(sys.executable)
1631 args = [path, '-c', 'import sys; sys.exit(57)']
1632 res = subprocess.run(args)
1633 self.assertEqual(res.returncode, 57)
1634
Bo Baylesce0f33d2018-01-30 00:40:39 -06001635 def test_capture_output(self):
1636 cp = self.run_python(("import sys;"
1637 "sys.stdout.write('BDFL'); "
1638 "sys.stderr.write('FLUFL')"),
1639 capture_output=True)
1640 self.assertIn(b'BDFL', cp.stdout)
1641 self.assertIn(b'FLUFL', cp.stderr)
1642
1643 def test_stdout_with_capture_output_arg(self):
1644 # run() refuses to accept 'stdout' with 'capture_output'
1645 tf = tempfile.TemporaryFile()
1646 self.addCleanup(tf.close)
1647 with self.assertRaises(ValueError,
1648 msg=("Expected ValueError when stdout and capture_output "
1649 "args supplied.")) as c:
1650 output = self.run_python("print('will not be run')",
1651 capture_output=True, stdout=tf)
1652 self.assertIn('stdout', c.exception.args[0])
1653 self.assertIn('capture_output', c.exception.args[0])
1654
1655 def test_stderr_with_capture_output_arg(self):
1656 # run() refuses to accept 'stderr' with 'capture_output'
1657 tf = tempfile.TemporaryFile()
1658 self.addCleanup(tf.close)
1659 with self.assertRaises(ValueError,
1660 msg=("Expected ValueError when stderr and capture_output "
1661 "args supplied.")) as c:
1662 output = self.run_python("print('will not be run')",
1663 capture_output=True, stderr=tf)
1664 self.assertIn('stderr', c.exception.args[0])
1665 self.assertIn('capture_output', c.exception.args[0])
1666
Gregory P. Smith580d2782019-09-11 04:23:05 -05001667 # This test _might_ wind up a bit fragile on loaded build+test machines
1668 # as it depends on the timing with wide enough margins for normal situations
1669 # but does assert that it happened "soon enough" to believe the right thing
1670 # happened.
1671 @unittest.skipIf(mswindows, "requires posix like 'sleep' shell command")
1672 def test_run_with_shell_timeout_and_capture_output(self):
1673 """Output capturing after a timeout mustn't hang forever on open filehandles."""
1674 before_secs = time.monotonic()
1675 try:
1676 subprocess.run('sleep 3', shell=True, timeout=0.1,
1677 capture_output=True) # New session unspecified.
1678 except subprocess.TimeoutExpired as exc:
1679 after_secs = time.monotonic()
1680 stacks = traceback.format_exc() # assertRaises doesn't give this.
1681 else:
1682 self.fail("TimeoutExpired not raised.")
1683 self.assertLess(after_secs - before_secs, 1.5,
1684 msg="TimeoutExpired was delayed! Bad traceback:\n```\n"
1685 f"{stacks}```")
1686
Gregory P. Smith6e730002015-04-14 16:14:25 -07001687
Gregory P. Smith693aa802019-09-13 14:43:35 +01001688def _get_test_grp_name():
Victor Stinnerfaca8552019-09-25 15:52:49 +02001689 for name_group in ('staff', 'nogroup', 'grp', 'nobody', 'nfsnobody'):
Gregory P. Smith693aa802019-09-13 14:43:35 +01001690 if grp:
1691 try:
1692 grp.getgrnam(name_group)
1693 except KeyError:
1694 continue
1695 return name_group
1696 else:
1697 raise unittest.SkipTest('No identified group name to use for this test on this platform.')
1698
1699
Victor Stinner937ee9e2018-06-26 02:11:06 +02001700@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001701class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001702
Gregory P. Smith5591b022012-10-10 03:34:47 -07001703 def setUp(self):
1704 super().setUp()
1705 self._nonexistent_dir = "/_this/pa.th/does/not/exist"
1706
1707 def _get_chdir_exception(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001708 try:
Gregory P. Smith5591b022012-10-10 03:34:47 -07001709 os.chdir(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001710 except OSError as e:
1711 # This avoids hard coding the errno value or the OS perror()
1712 # string and instead capture the exception that we want to see
1713 # below for comparison.
1714 desired_exception = e
1715 else:
Martin Pantereb995702016-07-28 01:11:04 +00001716 self.fail("chdir to nonexistent directory %s succeeded." %
Gregory P. Smith5591b022012-10-10 03:34:47 -07001717 self._nonexistent_dir)
1718 return desired_exception
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001719
Gregory P. Smith5591b022012-10-10 03:34:47 -07001720 def test_exception_cwd(self):
1721 """Test error in the child raised in the parent for a bad cwd."""
1722 desired_exception = self._get_chdir_exception()
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001723 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001724 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smith5591b022012-10-10 03:34:47 -07001725 cwd=self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001726 except OSError as e:
1727 # Test that the child process chdir failure actually makes
1728 # it up to the parent process as the correct exception.
1729 self.assertEqual(desired_exception.errno, e.errno)
1730 self.assertEqual(desired_exception.strerror, e.strerror)
Zackery Spytz73870bf2018-09-11 09:54:07 -06001731 self.assertEqual(desired_exception.filename, e.filename)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001732 else:
1733 self.fail("Expected OSError: %s" % desired_exception)
1734
Gregory P. Smith5591b022012-10-10 03:34:47 -07001735 def test_exception_bad_executable(self):
1736 """Test error in the child raised in the parent for a bad executable."""
1737 desired_exception = self._get_chdir_exception()
1738 try:
1739 p = subprocess.Popen([sys.executable, "-c", ""],
1740 executable=self._nonexistent_dir)
1741 except OSError as e:
1742 # Test that the child process exec failure actually makes
1743 # it up to the parent process as the correct exception.
1744 self.assertEqual(desired_exception.errno, e.errno)
1745 self.assertEqual(desired_exception.strerror, e.strerror)
Zackery Spytz73870bf2018-09-11 09:54:07 -06001746 self.assertEqual(desired_exception.filename, e.filename)
Gregory P. Smith5591b022012-10-10 03:34:47 -07001747 else:
1748 self.fail("Expected OSError: %s" % desired_exception)
1749
1750 def test_exception_bad_args_0(self):
1751 """Test error in the child raised in the parent for a bad args[0]."""
1752 desired_exception = self._get_chdir_exception()
1753 try:
1754 p = subprocess.Popen([self._nonexistent_dir, "-c", ""])
1755 except OSError as e:
1756 # Test that the child process exec failure actually makes
1757 # it up to the parent process as the correct exception.
1758 self.assertEqual(desired_exception.errno, e.errno)
1759 self.assertEqual(desired_exception.strerror, e.strerror)
Zackery Spytz73870bf2018-09-11 09:54:07 -06001760 self.assertEqual(desired_exception.filename, e.filename)
Gregory P. Smith5591b022012-10-10 03:34:47 -07001761 else:
1762 self.fail("Expected OSError: %s" % desired_exception)
1763
Ammar Askar3fc499b2017-09-06 02:41:30 -04001764 # We mock the __del__ method for Popen in the next two tests
1765 # because it does cleanup based on the pid returned by fork_exec
1766 # along with issuing a resource warning if it still exists. Since
1767 # we don't actually spawn a process in these tests we can forego
1768 # the destructor. An alternative would be to set _child_created to
1769 # False before the destructor is called but there is no easy way
1770 # to do that
1771 class PopenNoDestructor(subprocess.Popen):
1772 def __del__(self):
1773 pass
1774
1775 @mock.patch("subprocess._posixsubprocess.fork_exec")
1776 def test_exception_errpipe_normal(self, fork_exec):
1777 """Test error passing done through errpipe_write in the good case"""
1778 def proper_error(*args):
1779 errpipe_write = args[13]
1780 # Write the hex for the error code EISDIR: 'is a directory'
1781 err_code = '{:x}'.format(errno.EISDIR).encode()
1782 os.write(errpipe_write, b"OSError:" + err_code + b":")
1783 return 0
1784
1785 fork_exec.side_effect = proper_error
1786
Victor Stinner11045c92017-10-05 06:32:53 -07001787 with mock.patch("subprocess.os.waitpid",
1788 side_effect=ChildProcessError):
1789 with self.assertRaises(IsADirectoryError):
1790 self.PopenNoDestructor(["non_existent_command"])
Ammar Askar3fc499b2017-09-06 02:41:30 -04001791
1792 @mock.patch("subprocess._posixsubprocess.fork_exec")
1793 def test_exception_errpipe_bad_data(self, fork_exec):
1794 """Test error passing done through errpipe_write where its not
1795 in the expected format"""
1796 error_data = b"\xFF\x00\xDE\xAD"
1797 def bad_error(*args):
1798 errpipe_write = args[13]
1799 # Anything can be in the pipe, no assumptions should
1800 # be made about its encoding, so we'll write some
1801 # arbitrary hex bytes to test it out
1802 os.write(errpipe_write, error_data)
1803 return 0
1804
1805 fork_exec.side_effect = bad_error
1806
Victor Stinner11045c92017-10-05 06:32:53 -07001807 with mock.patch("subprocess.os.waitpid",
1808 side_effect=ChildProcessError):
1809 with self.assertRaises(subprocess.SubprocessError) as e:
1810 self.PopenNoDestructor(["non_existent_command"])
Ammar Askar3fc499b2017-09-06 02:41:30 -04001811
1812 self.assertIn(repr(error_data), str(e.exception))
1813
Gregory P. Smith5f3d04f2018-06-05 12:00:57 -07001814 @unittest.skipIf(not os.path.exists('/proc/self/status'),
1815 "need /proc/self/status")
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001816 def test_restore_signals(self):
Gregory P. Smith5f3d04f2018-06-05 12:00:57 -07001817 # Blindly assume that cat exists on systems with /proc/self/status...
1818 default_proc_status = subprocess.check_output(
1819 ['cat', '/proc/self/status'],
1820 restore_signals=False)
1821 for line in default_proc_status.splitlines():
1822 if line.startswith(b'SigIgn'):
1823 default_sig_ign_mask = line
1824 break
1825 else:
1826 self.skipTest("SigIgn not found in /proc/self/status.")
1827 restored_proc_status = subprocess.check_output(
1828 ['cat', '/proc/self/status'],
1829 restore_signals=True)
1830 for line in restored_proc_status.splitlines():
1831 if line.startswith(b'SigIgn'):
1832 restored_sig_ign_mask = line
1833 break
1834 self.assertNotEqual(default_sig_ign_mask, restored_sig_ign_mask,
1835 msg="restore_signals=True should've unblocked "
1836 "SIGPIPE and friends.")
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001837
1838 def test_start_new_session(self):
1839 # For code coverage of calling setsid(). We don't care if we get an
1840 # EPERM error from it depending on the test execution environment, that
1841 # still indicates that it was called.
1842 try:
1843 output = subprocess.check_output(
Victor Stinner58840432019-06-14 19:31:43 +02001844 [sys.executable, "-c", "import os; print(os.getsid(0))"],
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001845 start_new_session=True)
1846 except OSError as e:
1847 if e.errno != errno.EPERM:
1848 raise
1849 else:
Victor Stinner58840432019-06-14 19:31:43 +02001850 parent_sid = os.getsid(0)
1851 child_sid = int(output)
1852 self.assertNotEqual(parent_sid, child_sid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001853
Patrick McLean2b2ead72019-09-12 10:15:44 -07001854 @unittest.skipUnless(hasattr(os, 'setreuid'), 'no setreuid on platform')
1855 def test_user(self):
1856 # For code coverage of the user parameter. We don't care if we get an
1857 # EPERM error from it depending on the test execution environment, that
1858 # still indicates that it was called.
1859
1860 uid = os.geteuid()
1861 test_users = [65534 if uid != 65534 else 65533, uid]
1862 name_uid = "nobody" if sys.platform != 'darwin' else "unknown"
1863
1864 if pwd is not None:
Victor Stinnerf7b5d412020-03-05 14:28:40 +01001865 try:
1866 pwd.getpwnam(name_uid)
1867 test_users.append(name_uid)
1868 except KeyError:
1869 # unknown user name
1870 name_uid = None
Patrick McLean2b2ead72019-09-12 10:15:44 -07001871
1872 for user in test_users:
Victor Stinnerfaca8552019-09-25 15:52:49 +02001873 # posix_spawn() may be used with close_fds=False
1874 for close_fds in (False, True):
1875 with self.subTest(user=user, close_fds=close_fds):
1876 try:
1877 output = subprocess.check_output(
1878 [sys.executable, "-c",
1879 "import os; print(os.getuid())"],
1880 user=user,
1881 close_fds=close_fds)
1882 except PermissionError: # (EACCES, EPERM)
1883 pass
1884 except OSError as e:
1885 if e.errno not in (errno.EACCES, errno.EPERM):
1886 raise
Patrick McLean2b2ead72019-09-12 10:15:44 -07001887 else:
Victor Stinnerfaca8552019-09-25 15:52:49 +02001888 if isinstance(user, str):
1889 user_uid = pwd.getpwnam(user).pw_uid
1890 else:
1891 user_uid = user
1892 child_user = int(output)
1893 self.assertEqual(child_user, user_uid)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001894
1895 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001896 subprocess.check_call(ZERO_RETURN_CMD, user=-1)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001897
Victor Stinnerf7b5d412020-03-05 14:28:40 +01001898 if pwd is None and name_uid is not None:
Patrick McLean2b2ead72019-09-12 10:15:44 -07001899 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001900 subprocess.check_call(ZERO_RETURN_CMD, user=name_uid)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001901
1902 @unittest.skipIf(hasattr(os, 'setreuid'), 'setreuid() available on platform')
1903 def test_user_error(self):
1904 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001905 subprocess.check_call(ZERO_RETURN_CMD, user=65535)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001906
1907 @unittest.skipUnless(hasattr(os, 'setregid'), 'no setregid() on platform')
1908 def test_group(self):
1909 gid = os.getegid()
1910 group_list = [65534 if gid != 65534 else 65533]
Gregory P. Smith693aa802019-09-13 14:43:35 +01001911 name_group = _get_test_grp_name()
Patrick McLean2b2ead72019-09-12 10:15:44 -07001912
1913 if grp is not None:
1914 group_list.append(name_group)
1915
1916 for group in group_list + [gid]:
Victor Stinnerfaca8552019-09-25 15:52:49 +02001917 # posix_spawn() may be used with close_fds=False
1918 for close_fds in (False, True):
1919 with self.subTest(group=group, close_fds=close_fds):
1920 try:
1921 output = subprocess.check_output(
1922 [sys.executable, "-c",
1923 "import os; print(os.getgid())"],
1924 group=group,
1925 close_fds=close_fds)
1926 except PermissionError: # (EACCES, EPERM)
1927 pass
Patrick McLean2b2ead72019-09-12 10:15:44 -07001928 else:
Victor Stinnerfaca8552019-09-25 15:52:49 +02001929 if isinstance(group, str):
1930 group_gid = grp.getgrnam(group).gr_gid
1931 else:
1932 group_gid = group
Patrick McLean2b2ead72019-09-12 10:15:44 -07001933
Victor Stinnerfaca8552019-09-25 15:52:49 +02001934 child_group = int(output)
1935 self.assertEqual(child_group, group_gid)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001936
1937 # make sure we bomb on negative values
1938 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001939 subprocess.check_call(ZERO_RETURN_CMD, group=-1)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001940
1941 if grp is None:
1942 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001943 subprocess.check_call(ZERO_RETURN_CMD, group=name_group)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001944
1945 @unittest.skipIf(hasattr(os, 'setregid'), 'setregid() available on platform')
1946 def test_group_error(self):
1947 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001948 subprocess.check_call(ZERO_RETURN_CMD, group=65535)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001949
1950 @unittest.skipUnless(hasattr(os, 'setgroups'), 'no setgroups() on platform')
1951 def test_extra_groups(self):
1952 gid = os.getegid()
1953 group_list = [65534 if gid != 65534 else 65533]
Gregory P. Smith693aa802019-09-13 14:43:35 +01001954 name_group = _get_test_grp_name()
Patrick McLean2b2ead72019-09-12 10:15:44 -07001955 perm_error = False
1956
1957 if grp is not None:
1958 group_list.append(name_group)
1959
1960 try:
1961 output = subprocess.check_output(
1962 [sys.executable, "-c",
1963 "import os, sys, json; json.dump(os.getgroups(), sys.stdout)"],
1964 extra_groups=group_list)
1965 except OSError as ex:
1966 if ex.errno != errno.EPERM:
1967 raise
1968 perm_error = True
1969
1970 else:
1971 parent_groups = os.getgroups()
1972 child_groups = json.loads(output)
1973
1974 if grp is not None:
1975 desired_gids = [grp.getgrnam(g).gr_gid if isinstance(g, str) else g
1976 for g in group_list]
1977 else:
1978 desired_gids = group_list
1979
1980 if perm_error:
1981 self.assertEqual(set(child_groups), set(parent_groups))
1982 else:
1983 self.assertEqual(set(desired_gids), set(child_groups))
1984
1985 # make sure we bomb on negative values
1986 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001987 subprocess.check_call(ZERO_RETURN_CMD, extra_groups=[-1])
Patrick McLean2b2ead72019-09-12 10:15:44 -07001988
1989 if grp is None:
1990 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001991 subprocess.check_call(ZERO_RETURN_CMD,
Patrick McLean2b2ead72019-09-12 10:15:44 -07001992 extra_groups=[name_group])
1993
1994 @unittest.skipIf(hasattr(os, 'setgroups'), 'setgroups() available on platform')
1995 def test_extra_groups_error(self):
1996 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001997 subprocess.check_call(ZERO_RETURN_CMD, extra_groups=[])
Patrick McLean2b2ead72019-09-12 10:15:44 -07001998
Gregory P. Smithf3751ef2019-10-12 13:24:56 -07001999 @unittest.skipIf(mswindows or not hasattr(os, 'umask'),
2000 'POSIX umask() is not available.')
2001 def test_umask(self):
2002 tmpdir = None
2003 try:
2004 tmpdir = tempfile.mkdtemp()
2005 name = os.path.join(tmpdir, "beans")
2006 # We set an unusual umask in the child so as a unique mode
2007 # for us to test the child's touched file for.
2008 subprocess.check_call(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002009 [sys.executable, "-c", f"open({name!r}, 'w').close()"],
Gregory P. Smithf3751ef2019-10-12 13:24:56 -07002010 umask=0o053)
2011 # Ignore execute permissions entirely in our test,
2012 # filesystems could be mounted to ignore or force that.
2013 st_mode = os.stat(name).st_mode & 0o666
2014 expected_mode = 0o624
2015 self.assertEqual(expected_mode, st_mode,
2016 msg=f'{oct(expected_mode)} != {oct(st_mode)}')
2017 finally:
2018 if tmpdir is not None:
2019 shutil.rmtree(tmpdir)
2020
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002021 def test_run_abort(self):
2022 # returncode handles signal termination
Antoine Pitrou77e904e2013-10-08 23:04:32 +02002023 with support.SuppressCrashReport():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002024 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002025 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002026 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002027 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002028
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00002029 def test_CalledProcessError_str_signal(self):
2030 err = subprocess.CalledProcessError(-int(signal.SIGABRT), "fake cmd")
2031 error_string = str(err)
2032 # We're relying on the repr() of the signal.Signals intenum to provide
2033 # the word signal, the signal name and the numeric value.
2034 self.assertIn("signal", error_string.lower())
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)b4149062016-06-03 06:19:35 +00002035 # We're not being specific about the signal name as some signals have
2036 # multiple names and which name is revealed can vary.
2037 self.assertIn("SIG", error_string)
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00002038 self.assertIn(str(signal.SIGABRT), error_string)
2039
2040 def test_CalledProcessError_str_unknown_signal(self):
2041 err = subprocess.CalledProcessError(-9876543, "fake cmd")
2042 error_string = str(err)
2043 self.assertIn("unknown signal 9876543.", error_string)
2044
2045 def test_CalledProcessError_str_non_zero(self):
2046 err = subprocess.CalledProcessError(2, "fake cmd")
2047 error_string = str(err)
2048 self.assertIn("non-zero exit status 2.", error_string)
2049
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002050 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002051 # DISCLAIMER: Setting environment variables is *not* a good use
2052 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002053 p = subprocess.Popen([sys.executable, "-c",
2054 'import sys,os;'
2055 'sys.stdout.write(os.getenv("FRUIT"))'],
2056 stdout=subprocess.PIPE,
2057 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Victor Stinner7438c612016-05-20 12:43:15 +02002058 with p:
2059 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002060
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002061 def test_preexec_exception(self):
2062 def raise_it():
2063 raise ValueError("What if two swallows carried a coconut?")
2064 try:
2065 p = subprocess.Popen([sys.executable, "-c", ""],
2066 preexec_fn=raise_it)
Gregory P. Smith8d07c262012-11-10 23:53:47 -08002067 except subprocess.SubprocessError as e:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002068 self.assertTrue(
2069 subprocess._posixsubprocess,
2070 "Expected a ValueError from the preexec_fn")
2071 except ValueError as e:
2072 self.assertIn("coconut", e.args[0])
2073 else:
2074 self.fail("Exception raised by preexec_fn did not make it "
2075 "to the parent process.")
2076
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002077 class _TestExecuteChildPopen(subprocess.Popen):
2078 """Used to test behavior at the end of _execute_child."""
2079 def __init__(self, testcase, *args, **kwargs):
2080 self._testcase = testcase
2081 subprocess.Popen.__init__(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08002082
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002083 def _execute_child(self, *args, **kwargs):
Gregory P. Smith12489d92012-11-11 01:37:02 -08002084 try:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002085 subprocess.Popen._execute_child(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08002086 finally:
2087 # Open a bunch of file descriptors and verify that
2088 # none of them are the same as the ones the Popen
2089 # instance is using for stdin/stdout/stderr.
2090 devzero_fds = [os.open("/dev/zero", os.O_RDONLY)
2091 for _ in range(8)]
2092 try:
2093 for fd in devzero_fds:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002094 self._testcase.assertNotIn(
2095 fd, (self.stdin.fileno(), self.stdout.fileno(),
2096 self.stderr.fileno()),
Gregory P. Smith12489d92012-11-11 01:37:02 -08002097 msg="At least one fd was closed early.")
2098 finally:
Richard Oudkerk0e547b62013-06-10 16:29:19 +01002099 for fd in devzero_fds:
2100 os.close(fd)
Gregory P. Smith12489d92012-11-11 01:37:02 -08002101
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002102 @unittest.skipIf(not os.path.exists("/dev/zero"), "/dev/zero required.")
2103 def test_preexec_errpipe_does_not_double_close_pipes(self):
2104 """Issue16140: Don't double close pipes on preexec error."""
2105
2106 def raise_it():
Gregory P. Smith65ee6ec2012-11-11 10:12:40 -08002107 raise subprocess.SubprocessError(
2108 "force the _execute_child() errpipe_data path.")
Gregory P. Smith12489d92012-11-11 01:37:02 -08002109
Gregory P. Smithc2c4cb62012-11-11 01:41:49 -08002110 with self.assertRaises(subprocess.SubprocessError):
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002111 self._TestExecuteChildPopen(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002112 self, ZERO_RETURN_CMD,
Gregory P. Smith12489d92012-11-11 01:37:02 -08002113 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2114 stderr=subprocess.PIPE, preexec_fn=raise_it)
2115
Gregory P. Smith32ec9da2010-03-19 16:53:08 +00002116 def test_preexec_gc_module_failure(self):
2117 # This tests the code that disables garbage collection if the child
2118 # process will execute any Python.
2119 def raise_runtime_error():
2120 raise RuntimeError("this shouldn't escape")
2121 enabled = gc.isenabled()
2122 orig_gc_disable = gc.disable
2123 orig_gc_isenabled = gc.isenabled
2124 try:
2125 gc.disable()
2126 self.assertFalse(gc.isenabled())
2127 subprocess.call([sys.executable, '-c', ''],
2128 preexec_fn=lambda: None)
2129 self.assertFalse(gc.isenabled(),
2130 "Popen enabled gc when it shouldn't.")
2131
2132 gc.enable()
2133 self.assertTrue(gc.isenabled())
2134 subprocess.call([sys.executable, '-c', ''],
2135 preexec_fn=lambda: None)
2136 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
2137
2138 gc.disable = raise_runtime_error
2139 self.assertRaises(RuntimeError, subprocess.Popen,
2140 [sys.executable, '-c', ''],
2141 preexec_fn=lambda: None)
2142
2143 del gc.isenabled # force an AttributeError
2144 self.assertRaises(AttributeError, subprocess.Popen,
2145 [sys.executable, '-c', ''],
2146 preexec_fn=lambda: None)
2147 finally:
2148 gc.disable = orig_gc_disable
2149 gc.isenabled = orig_gc_isenabled
2150 if not enabled:
2151 gc.disable()
2152
Martin Panterf7fdbda2015-12-05 09:51:52 +00002153 @unittest.skipIf(
2154 sys.platform == 'darwin', 'setrlimit() seems to fail on OS X')
Martin Panterafdd5132015-11-30 02:21:41 +00002155 def test_preexec_fork_failure(self):
2156 # The internal code did not preserve the previous exception when
2157 # re-enabling garbage collection
2158 try:
2159 from resource import getrlimit, setrlimit, RLIMIT_NPROC
2160 except ImportError as err:
2161 self.skipTest(err) # RLIMIT_NPROC is specific to Linux and BSD
2162 limits = getrlimit(RLIMIT_NPROC)
2163 [_, hard] = limits
2164 setrlimit(RLIMIT_NPROC, (0, hard))
2165 self.addCleanup(setrlimit, RLIMIT_NPROC, limits)
Martin Panter5cf791b2015-12-11 05:40:14 +00002166 try:
Martin Panterafdd5132015-11-30 02:21:41 +00002167 subprocess.call([sys.executable, '-c', ''],
2168 preexec_fn=lambda: None)
Martin Panter5cf791b2015-12-11 05:40:14 +00002169 except BlockingIOError:
2170 # Forking should raise EAGAIN, translated to BlockingIOError
2171 pass
2172 else:
2173 self.skipTest('RLIMIT_NPROC had no effect; probably superuser')
Martin Panterafdd5132015-11-30 02:21:41 +00002174
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002175 def test_args_string(self):
2176 # args is a string
Berker Peksag16a1f282015-09-28 13:33:14 +03002177 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002178 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00002179 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02002180 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002181 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
2182 sys.executable)
2183 os.chmod(fname, 0o700)
2184 p = subprocess.Popen(fname)
2185 p.wait()
2186 os.remove(fname)
2187 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002188
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002189 def test_invalid_args(self):
2190 # invalid arguments should raise ValueError
2191 self.assertRaises(ValueError, subprocess.call,
2192 [sys.executable, "-c",
2193 "import sys; sys.exit(47)"],
2194 startupinfo=47)
2195 self.assertRaises(ValueError, subprocess.call,
2196 [sys.executable, "-c",
2197 "import sys; sys.exit(47)"],
2198 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002199
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002200 def test_shell_sequence(self):
2201 # Run command through the shell (sequence)
2202 newenv = os.environ.copy()
2203 newenv["FRUIT"] = "apple"
2204 p = subprocess.Popen(["echo $FRUIT"], shell=1,
2205 stdout=subprocess.PIPE,
2206 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02002207 with p:
2208 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002209
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002210 def test_shell_string(self):
2211 # Run command through the shell (string)
2212 newenv = os.environ.copy()
2213 newenv["FRUIT"] = "apple"
2214 p = subprocess.Popen("echo $FRUIT", shell=1,
2215 stdout=subprocess.PIPE,
2216 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02002217 with p:
2218 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +00002219
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002220 def test_call_string(self):
2221 # call() function with string argument on UNIX
Berker Peksag16a1f282015-09-28 13:33:14 +03002222 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002223 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00002224 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02002225 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002226 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
2227 sys.executable)
2228 os.chmod(fname, 0o700)
2229 rc = subprocess.call(fname)
2230 os.remove(fname)
2231 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00002232
Stefan Krah9542cc62010-07-19 14:20:53 +00002233 def test_specific_shell(self):
2234 # Issue #9265: Incorrect name passed as arg[0].
2235 shells = []
2236 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
2237 for name in ['bash', 'ksh']:
2238 sh = os.path.join(prefix, name)
2239 if os.path.isfile(sh):
2240 shells.append(sh)
2241 if not shells: # Will probably work for any shell but csh.
2242 self.skipTest("bash or ksh required for this test")
2243 sh = '/bin/sh'
2244 if os.path.isfile(sh) and not os.path.islink(sh):
2245 # Test will fail if /bin/sh is a symlink to csh.
2246 shells.append(sh)
2247 for sh in shells:
2248 p = subprocess.Popen("echo $0", executable=sh, shell=True,
2249 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02002250 with p:
2251 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
Stefan Krah9542cc62010-07-19 14:20:53 +00002252
Florent Xicluna4886d242010-03-08 13:27:26 +00002253 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00002254 # Do not inherit file handles from the parent.
2255 # It should fix failures on some platforms.
Gregory P. Smithdee04342013-08-29 13:35:27 -07002256 # Also set the SIGINT handler to the default to make sure it's not
2257 # being ignored (some tests rely on that.)
2258 old_handler = signal.signal(signal.SIGINT, signal.default_int_handler)
2259 try:
2260 p = subprocess.Popen([sys.executable, "-c", """if 1:
2261 import sys, time
2262 sys.stdout.write('x\\n')
2263 sys.stdout.flush()
2264 time.sleep(30)
2265 """],
2266 close_fds=True,
2267 stdin=subprocess.PIPE,
2268 stdout=subprocess.PIPE,
2269 stderr=subprocess.PIPE)
2270 finally:
2271 signal.signal(signal.SIGINT, old_handler)
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00002272 # Wait for the interpreter to be completely initialized before
2273 # sending any signal.
2274 p.stdout.read(1)
2275 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00002276 return p
2277
Charles-François Natali53221e32013-01-12 16:52:20 +01002278 @unittest.skipIf(sys.platform.startswith(('netbsd', 'openbsd')),
2279 "Due to known OS bug (issue #16762)")
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002280 def _kill_dead_process(self, method, *args):
2281 # Do not inherit file handles from the parent.
2282 # It should fix failures on some platforms.
2283 p = subprocess.Popen([sys.executable, "-c", """if 1:
2284 import sys, time
2285 sys.stdout.write('x\\n')
2286 sys.stdout.flush()
2287 """],
2288 close_fds=True,
2289 stdin=subprocess.PIPE,
2290 stdout=subprocess.PIPE,
2291 stderr=subprocess.PIPE)
2292 # Wait for the interpreter to be completely initialized before
2293 # sending any signal.
2294 p.stdout.read(1)
2295 # The process should end after this
2296 time.sleep(1)
2297 # This shouldn't raise even though the child is now dead
2298 getattr(p, method)(*args)
2299 p.communicate()
2300
Florent Xicluna4886d242010-03-08 13:27:26 +00002301 def test_send_signal(self):
2302 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00002303 _, stderr = p.communicate()
2304 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002305 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00002306
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002307 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002308 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00002309 _, stderr = p.communicate()
Victor Stinner6cac1132019-12-08 08:38:16 +01002310 self.assertEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002311 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00002312
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002313 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002314 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00002315 _, stderr = p.communicate()
Victor Stinner6cac1132019-12-08 08:38:16 +01002316 self.assertEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002317 self.assertEqual(p.wait(), -signal.SIGTERM)
2318
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002319 def test_send_signal_dead(self):
2320 # Sending a signal to a dead process
2321 self._kill_dead_process('send_signal', signal.SIGINT)
2322
2323 def test_kill_dead(self):
2324 # Killing a dead process
2325 self._kill_dead_process('kill')
2326
2327 def test_terminate_dead(self):
2328 # Terminating a dead process
2329 self._kill_dead_process('terminate')
2330
Victor Stinnerdaf45552013-08-28 00:53:59 +02002331 def _save_fds(self, save_fds):
2332 fds = []
2333 for fd in save_fds:
2334 inheritable = os.get_inheritable(fd)
2335 saved = os.dup(fd)
2336 fds.append((fd, saved, inheritable))
2337 return fds
2338
2339 def _restore_fds(self, fds):
2340 for fd, saved, inheritable in fds:
2341 os.dup2(saved, fd, inheritable=inheritable)
2342 os.close(saved)
2343
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002344 def check_close_std_fds(self, fds):
2345 # Issue #9905: test that subprocess pipes still work properly with
2346 # some standard fds closed
2347 stdin = 0
Victor Stinnerdaf45552013-08-28 00:53:59 +02002348 saved_fds = self._save_fds(fds)
2349 for fd, saved, inheritable in saved_fds:
2350 if fd == 0:
2351 stdin = saved
2352 break
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002353 try:
2354 for fd in fds:
2355 os.close(fd)
2356 out, err = subprocess.Popen([sys.executable, "-c",
2357 'import sys;'
2358 'sys.stdout.write("apple");'
2359 'sys.stdout.flush();'
2360 'sys.stderr.write("orange")'],
2361 stdin=stdin,
2362 stdout=subprocess.PIPE,
2363 stderr=subprocess.PIPE).communicate()
Victor Stinner6cac1132019-12-08 08:38:16 +01002364 self.assertEqual(out, b'apple')
2365 self.assertEqual(err, b'orange')
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002366 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002367 self._restore_fds(saved_fds)
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002368
2369 def test_close_fd_0(self):
2370 self.check_close_std_fds([0])
2371
2372 def test_close_fd_1(self):
2373 self.check_close_std_fds([1])
2374
2375 def test_close_fd_2(self):
2376 self.check_close_std_fds([2])
2377
2378 def test_close_fds_0_1(self):
2379 self.check_close_std_fds([0, 1])
2380
2381 def test_close_fds_0_2(self):
2382 self.check_close_std_fds([0, 2])
2383
2384 def test_close_fds_1_2(self):
2385 self.check_close_std_fds([1, 2])
2386
2387 def test_close_fds_0_1_2(self):
2388 # Issue #10806: test that subprocess pipes still work properly with
2389 # all standard fds closed.
2390 self.check_close_std_fds([0, 1, 2])
2391
Gregory P. Smith53dd8162013-12-01 16:03:24 -08002392 def test_small_errpipe_write_fd(self):
2393 """Issue #15798: Popen should work when stdio fds are available."""
2394 new_stdin = os.dup(0)
2395 new_stdout = os.dup(1)
2396 try:
2397 os.close(0)
2398 os.close(1)
2399
2400 # Side test: if errpipe_write fails to have its CLOEXEC
2401 # flag set this should cause the parent to think the exec
2402 # failed. Extremely unlikely: everyone supports CLOEXEC.
2403 subprocess.Popen([
2404 sys.executable, "-c",
2405 "print('AssertionError:0:CLOEXEC failure.')"]).wait()
2406 finally:
2407 # Restore original stdin and stdout
2408 os.dup2(new_stdin, 0)
2409 os.dup2(new_stdout, 1)
2410 os.close(new_stdin)
2411 os.close(new_stdout)
2412
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002413 def test_remapping_std_fds(self):
2414 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03002415 temps = [tempfile.mkstemp() for i in range(3)]
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002416 try:
2417 temp_fds = [fd for fd, fname in temps]
2418
2419 # unlink the files -- we won't need to reopen them
2420 for fd, fname in temps:
2421 os.unlink(fname)
2422
2423 # write some data to what will become stdin, and rewind
2424 os.write(temp_fds[1], b"STDIN")
2425 os.lseek(temp_fds[1], 0, 0)
2426
2427 # move the standard file descriptors out of the way
Victor Stinnerdaf45552013-08-28 00:53:59 +02002428 saved_fds = self._save_fds(range(3))
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002429 try:
2430 # duplicate the file objects over the standard fd's
2431 for fd, temp_fd in enumerate(temp_fds):
2432 os.dup2(temp_fd, fd)
2433
2434 # now use those files in the "wrong" order, so that subprocess
2435 # has to rearrange them in the child
2436 p = subprocess.Popen([sys.executable, "-c",
2437 'import sys; got = sys.stdin.read();'
2438 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
2439 stdin=temp_fds[1],
2440 stdout=temp_fds[2],
2441 stderr=temp_fds[0])
2442 p.wait()
2443 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002444 self._restore_fds(saved_fds)
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002445
2446 for fd in temp_fds:
2447 os.lseek(fd, 0, 0)
2448
2449 out = os.read(temp_fds[2], 1024)
Victor Stinner6cac1132019-12-08 08:38:16 +01002450 err = os.read(temp_fds[0], 1024).strip()
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002451 self.assertEqual(out, b"got STDIN")
2452 self.assertEqual(err, b"err")
2453
2454 finally:
2455 for fd in temp_fds:
2456 os.close(fd)
2457
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002458 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
2459 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03002460 temps = [tempfile.mkstemp() for i in range(3)]
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002461 temp_fds = [fd for fd, fname in temps]
2462 try:
2463 # unlink the files -- we won't need to reopen them
2464 for fd, fname in temps:
2465 os.unlink(fname)
2466
2467 # save a copy of the standard file descriptors
Victor Stinnerdaf45552013-08-28 00:53:59 +02002468 saved_fds = self._save_fds(range(3))
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002469 try:
2470 # duplicate the temp files over the standard fd's 0, 1, 2
2471 for fd, temp_fd in enumerate(temp_fds):
2472 os.dup2(temp_fd, fd)
2473
2474 # write some data to what will become stdin, and rewind
2475 os.write(stdin_no, b"STDIN")
2476 os.lseek(stdin_no, 0, 0)
2477
2478 # now use those files in the given order, so that subprocess
2479 # has to rearrange them in the child
2480 p = subprocess.Popen([sys.executable, "-c",
2481 'import sys; got = sys.stdin.read();'
2482 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
2483 stdin=stdin_no,
2484 stdout=stdout_no,
2485 stderr=stderr_no)
2486 p.wait()
2487
2488 for fd in temp_fds:
2489 os.lseek(fd, 0, 0)
2490
2491 out = os.read(stdout_no, 1024)
Victor Stinner6cac1132019-12-08 08:38:16 +01002492 err = os.read(stderr_no, 1024).strip()
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002493 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002494 self._restore_fds(saved_fds)
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002495
2496 self.assertEqual(out, b"got STDIN")
2497 self.assertEqual(err, b"err")
2498
2499 finally:
2500 for fd in temp_fds:
2501 os.close(fd)
2502
2503 # When duping fds, if there arises a situation where one of the fds is
2504 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
2505 # This tests all combinations of this.
2506 def test_swap_fds(self):
2507 self.check_swap_fds(0, 1, 2)
2508 self.check_swap_fds(0, 2, 1)
2509 self.check_swap_fds(1, 0, 2)
2510 self.check_swap_fds(1, 2, 0)
2511 self.check_swap_fds(2, 0, 1)
2512 self.check_swap_fds(2, 1, 0)
2513
Alexey Izbyshev0e7144b2018-03-26 22:49:35 +03002514 def _check_swap_std_fds_with_one_closed(self, from_fds, to_fds):
2515 saved_fds = self._save_fds(range(3))
2516 try:
2517 for from_fd in from_fds:
2518 with tempfile.TemporaryFile() as f:
2519 os.dup2(f.fileno(), from_fd)
2520
2521 fd_to_close = (set(range(3)) - set(from_fds)).pop()
2522 os.close(fd_to_close)
2523
2524 arg_names = ['stdin', 'stdout', 'stderr']
2525 kwargs = {}
2526 for from_fd, to_fd in zip(from_fds, to_fds):
2527 kwargs[arg_names[to_fd]] = from_fd
2528
2529 code = textwrap.dedent(r'''
2530 import os, sys
2531 skipped_fd = int(sys.argv[1])
2532 for fd in range(3):
2533 if fd != skipped_fd:
2534 os.write(fd, str(fd).encode('ascii'))
2535 ''')
2536
2537 skipped_fd = (set(range(3)) - set(to_fds)).pop()
2538
2539 rc = subprocess.call([sys.executable, '-c', code, str(skipped_fd)],
2540 **kwargs)
2541 self.assertEqual(rc, 0)
2542
2543 for from_fd, to_fd in zip(from_fds, to_fds):
2544 os.lseek(from_fd, 0, os.SEEK_SET)
2545 read_bytes = os.read(from_fd, 1024)
2546 read_fds = list(map(int, read_bytes.decode('ascii')))
2547 msg = textwrap.dedent(f"""
2548 When testing {from_fds} to {to_fds} redirection,
2549 parent descriptor {from_fd} got redirected
2550 to descriptor(s) {read_fds} instead of descriptor {to_fd}.
2551 """)
2552 self.assertEqual([to_fd], read_fds, msg)
2553 finally:
2554 self._restore_fds(saved_fds)
2555
2556 # Check that subprocess can remap std fds correctly even
2557 # if one of them is closed (#32844).
2558 def test_swap_std_fds_with_one_closed(self):
2559 for from_fds in itertools.combinations(range(3), 2):
2560 for to_fds in itertools.permutations(range(3), 2):
2561 self._check_swap_std_fds_with_one_closed(from_fds, to_fds)
2562
Victor Stinner13bb71c2010-04-23 21:41:56 +00002563 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00002564 def prepare():
2565 raise ValueError("surrogate:\uDCff")
2566
2567 try:
2568 subprocess.call(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002569 ZERO_RETURN_CMD,
Victor Stinner4d078042010-04-23 19:28:32 +00002570 preexec_fn=prepare)
2571 except ValueError as err:
2572 # Pure Python implementations keeps the message
2573 self.assertIsNone(subprocess._posixsubprocess)
2574 self.assertEqual(str(err), "surrogate:\uDCff")
Gregory P. Smith8d07c262012-11-10 23:53:47 -08002575 except subprocess.SubprocessError as err:
Victor Stinner4d078042010-04-23 19:28:32 +00002576 # _posixsubprocess uses a default message
2577 self.assertIsNotNone(subprocess._posixsubprocess)
2578 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
2579 else:
Gregory P. Smith8d07c262012-11-10 23:53:47 -08002580 self.fail("Expected ValueError or subprocess.SubprocessError")
Victor Stinner4d078042010-04-23 19:28:32 +00002581
Victor Stinner13bb71c2010-04-23 21:41:56 +00002582 def test_undecodable_env(self):
2583 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner5323fb02013-11-19 23:46:06 +01002584 encoded_value = value.encode("ascii", "surrogateescape")
2585
Victor Stinner13bb71c2010-04-23 21:41:56 +00002586 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00002587 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002588 env = os.environ.copy()
2589 env[key] = value
Victor Stinner5323fb02013-11-19 23:46:06 +01002590 # Use C locale to get ASCII for the locale encoding to force
Michael Felt89d79b12018-08-26 19:29:36 +02002591 # surrogate-escaping of \xFF in the child process
Victor Stinnerebc78d22010-10-14 10:38:17 +00002592 env['LC_ALL'] = 'C'
Michael Felt89d79b12018-08-26 19:29:36 +02002593 decoded_value = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00002594 stdout = subprocess.check_output(
2595 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002596 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00002597 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01002598 self.assertEqual(stdout.decode('ascii'), ascii(decoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00002599
2600 # test bytes
2601 key = key.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00002602 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002603 env = os.environ.copy()
Victor Stinner5323fb02013-11-19 23:46:06 +01002604 env[key] = encoded_value
Victor Stinner13bb71c2010-04-23 21:41:56 +00002605 stdout = subprocess.check_output(
2606 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002607 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00002608 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01002609 self.assertEqual(stdout.decode('ascii'), ascii(encoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00002610
Victor Stinnerb745a742010-05-18 17:17:23 +00002611 def test_bytes_program(self):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002612 abs_program = os.fsencode(ZERO_RETURN_CMD[0])
2613 args = list(ZERO_RETURN_CMD[1:])
2614 path, program = os.path.split(ZERO_RETURN_CMD[0])
Victor Stinnerb745a742010-05-18 17:17:23 +00002615 program = os.fsencode(program)
2616
2617 # absolute bytes path
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002618 exitcode = subprocess.call([abs_program]+args)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002619 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002620
Victor Stinner7b3b20a2011-03-03 12:54:05 +00002621 # absolute bytes path as a string
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002622 cmd = b"'%s' %s" % (abs_program, " ".join(args).encode("utf-8"))
Victor Stinner7b3b20a2011-03-03 12:54:05 +00002623 exitcode = subprocess.call(cmd, shell=True)
2624 self.assertEqual(exitcode, 0)
2625
Victor Stinnerb745a742010-05-18 17:17:23 +00002626 # bytes program, unicode PATH
2627 env = os.environ.copy()
2628 env["PATH"] = path
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002629 exitcode = subprocess.call([program]+args, env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002630 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002631
2632 # bytes program, bytes PATH
2633 envb = os.environb.copy()
2634 envb[b"PATH"] = os.fsencode(path)
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002635 exitcode = subprocess.call([program]+args, env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002636 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002637
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002638 def test_pipe_cloexec(self):
2639 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
2640 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2641
2642 p1 = subprocess.Popen([sys.executable, sleeper],
2643 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2644 stderr=subprocess.PIPE, close_fds=False)
2645
2646 self.addCleanup(p1.communicate, b'')
2647
2648 p2 = subprocess.Popen([sys.executable, fd_status],
2649 stdout=subprocess.PIPE, close_fds=False)
2650
2651 output, error = p2.communicate()
2652 result_fds = set(map(int, output.split(b',')))
2653 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
2654 p1.stderr.fileno()])
2655
2656 self.assertFalse(result_fds & unwanted_fds,
2657 "Expected no fds from %r to be open in child, "
2658 "found %r" %
2659 (unwanted_fds, result_fds & unwanted_fds))
2660
2661 def test_pipe_cloexec_real_tools(self):
2662 qcat = support.findfile("qcat.py", subdir="subprocessdata")
2663 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
2664
2665 subdata = b'zxcvbn'
2666 data = subdata * 4 + b'\n'
2667
2668 p1 = subprocess.Popen([sys.executable, qcat],
2669 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2670 close_fds=False)
2671
2672 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
2673 stdin=p1.stdout, stdout=subprocess.PIPE,
2674 close_fds=False)
2675
2676 self.addCleanup(p1.wait)
2677 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08002678 def kill_p1():
2679 try:
2680 p1.terminate()
2681 except ProcessLookupError:
2682 pass
2683 def kill_p2():
2684 try:
2685 p2.terminate()
2686 except ProcessLookupError:
2687 pass
2688 self.addCleanup(kill_p1)
2689 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002690
2691 p1.stdin.write(data)
2692 p1.stdin.close()
2693
2694 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
2695
2696 self.assertTrue(readfiles, "The child hung")
2697 self.assertEqual(p2.stdout.read(), data)
2698
Victor Stinnerfaa8c132011-01-03 16:36:00 +00002699 p1.stdout.close()
2700 p2.stdout.close()
2701
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002702 def test_close_fds(self):
2703 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2704
2705 fds = os.pipe()
2706 self.addCleanup(os.close, fds[0])
2707 self.addCleanup(os.close, fds[1])
2708
2709 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002710 # add a bunch more fds
2711 for _ in range(9):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002712 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002713 self.addCleanup(os.close, fd)
2714 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002715
Victor Stinnerdaf45552013-08-28 00:53:59 +02002716 for fd in open_fds:
2717 os.set_inheritable(fd, True)
2718
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002719 p = subprocess.Popen([sys.executable, fd_status],
2720 stdout=subprocess.PIPE, close_fds=False)
2721 output, ignored = p.communicate()
2722 remaining_fds = set(map(int, output.split(b',')))
2723
2724 self.assertEqual(remaining_fds & open_fds, open_fds,
2725 "Some fds were closed")
2726
2727 p = subprocess.Popen([sys.executable, fd_status],
2728 stdout=subprocess.PIPE, close_fds=True)
2729 output, ignored = p.communicate()
2730 remaining_fds = set(map(int, output.split(b',')))
2731
2732 self.assertFalse(remaining_fds & open_fds,
2733 "Some fds were left open")
2734 self.assertIn(1, remaining_fds, "Subprocess failed")
2735
Gregory P. Smith8facece2012-01-21 14:01:08 -08002736 # Keep some of the fd's we opened open in the subprocess.
2737 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
2738 fds_to_keep = set(open_fds.pop() for _ in range(8))
2739 p = subprocess.Popen([sys.executable, fd_status],
2740 stdout=subprocess.PIPE, close_fds=True,
izbyshev2d8f0632017-12-19 03:26:49 +07002741 pass_fds=fds_to_keep)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002742 output, ignored = p.communicate()
2743 remaining_fds = set(map(int, output.split(b',')))
2744
izbyshev2d8f0632017-12-19 03:26:49 +07002745 self.assertFalse((remaining_fds - fds_to_keep) & open_fds,
Gregory P. Smith8facece2012-01-21 14:01:08 -08002746 "Some fds not in pass_fds were left open")
2747 self.assertIn(1, remaining_fds, "Subprocess failed")
2748
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002749
Gregory P. Smithd04f6992014-06-01 15:27:28 -07002750 @unittest.skipIf(sys.platform.startswith("freebsd") and
2751 os.stat("/dev").st_dev == os.stat("/dev/fd").st_dev,
2752 "Requires fdescfs mounted on /dev/fd on FreeBSD.")
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002753 def test_close_fds_when_max_fd_is_lowered(self):
2754 """Confirm that issue21618 is fixed (may fail under valgrind)."""
2755 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2756
Gregory P. Smith634aa682014-06-15 17:51:04 -07002757 # This launches the meat of the test in a child process to
2758 # avoid messing with the larger unittest processes maximum
2759 # number of file descriptors.
2760 # This process launches:
2761 # +--> Process that lowers its RLIMIT_NOFILE aftr setting up
2762 # a bunch of high open fds above the new lower rlimit.
2763 # Those are reported via stdout before launching a new
2764 # process with close_fds=False to run the actual test:
2765 # +--> The TEST: This one launches a fd_status.py
2766 # subprocess with close_fds=True so we can find out if
2767 # any of the fds above the lowered rlimit are still open.
2768 p = subprocess.Popen([sys.executable, '-c', textwrap.dedent(
2769 '''
2770 import os, resource, subprocess, sys, textwrap
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002771 open_fds = set()
2772 # Add a bunch more fds to pass down.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002773 for _ in range(40):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002774 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002775 open_fds.add(fd)
2776
2777 # Leave a two pairs of low ones available for use by the
2778 # internal child error pipe and the stdout pipe.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002779 # We also leave 10 more open as some Python buildbots run into
2780 # "too many open files" errors during the test if we do not.
2781 for fd in sorted(open_fds)[:14]:
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002782 os.close(fd)
2783 open_fds.remove(fd)
2784
2785 for fd in open_fds:
Gregory P. Smith634aa682014-06-15 17:51:04 -07002786 #self.addCleanup(os.close, fd)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002787 os.set_inheritable(fd, True)
2788
2789 max_fd_open = max(open_fds)
2790
Gregory P. Smith634aa682014-06-15 17:51:04 -07002791 # Communicate the open_fds to the parent unittest.TestCase process.
2792 print(','.join(map(str, sorted(open_fds))))
2793 sys.stdout.flush()
2794
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002795 rlim_cur, rlim_max = resource.getrlimit(resource.RLIMIT_NOFILE)
2796 try:
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002797 # 29 is lower than the highest fds we are leaving open.
2798 resource.setrlimit(resource.RLIMIT_NOFILE, (29, rlim_max))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002799 # Launch a new Python interpreter with our low fd rlim_cur that
2800 # inherits open fds above that limit. It then uses subprocess
2801 # with close_fds=True to get a report of open fds in the child.
2802 # An explicit list of fds to check is passed to fd_status.py as
2803 # letting fd_status rely on its default logic would miss the
2804 # fds above rlim_cur as it normally only checks up to that limit.
Gregory P. Smith634aa682014-06-15 17:51:04 -07002805 subprocess.Popen(
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002806 [sys.executable, '-c',
2807 textwrap.dedent("""
2808 import subprocess, sys
Gregory P. Smith634aa682014-06-15 17:51:04 -07002809 subprocess.Popen([sys.executable, %r] +
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002810 [str(x) for x in range({max_fd})],
Gregory P. Smithffd529c2014-06-01 13:46:54 -07002811 close_fds=True).wait()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002812 """.format(max_fd=max_fd_open+1))],
2813 close_fds=False).wait()
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002814 finally:
2815 resource.setrlimit(resource.RLIMIT_NOFILE, (rlim_cur, rlim_max))
Gregory P. Smith634aa682014-06-15 17:51:04 -07002816 ''' % fd_status)], stdout=subprocess.PIPE)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002817
2818 output, unused_stderr = p.communicate()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002819 output_lines = output.splitlines()
2820 self.assertEqual(len(output_lines), 2,
Gregory P. Smith9204e092014-06-15 20:16:01 -07002821 msg="expected exactly two lines of output:\n%r" % output)
Gregory P. Smith634aa682014-06-15 17:51:04 -07002822 opened_fds = set(map(int, output_lines[0].strip().split(b',')))
2823 remaining_fds = set(map(int, output_lines[1].strip().split(b',')))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002824
Gregory P. Smith634aa682014-06-15 17:51:04 -07002825 self.assertFalse(remaining_fds & opened_fds,
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002826 msg="Some fds were left open.")
2827
2828
Victor Stinner88701e22011-06-01 13:13:04 +02002829 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
2830 # descriptor of a pipe closed in the parent process is valid in the
2831 # child process according to fstat(), but the mode of the file
2832 # descriptor is invalid, and read or write raise an error.
2833 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002834 def test_pass_fds(self):
2835 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2836
2837 open_fds = set()
2838
2839 for x in range(5):
2840 fds = os.pipe()
2841 self.addCleanup(os.close, fds[0])
2842 self.addCleanup(os.close, fds[1])
Victor Stinnerdaf45552013-08-28 00:53:59 +02002843 os.set_inheritable(fds[0], True)
2844 os.set_inheritable(fds[1], True)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002845 open_fds.update(fds)
2846
2847 for fd in open_fds:
2848 p = subprocess.Popen([sys.executable, fd_status],
2849 stdout=subprocess.PIPE, close_fds=True,
2850 pass_fds=(fd, ))
2851 output, ignored = p.communicate()
2852
2853 remaining_fds = set(map(int, output.split(b',')))
2854 to_be_closed = open_fds - {fd}
2855
2856 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
2857 self.assertFalse(remaining_fds & to_be_closed,
2858 "fd to be closed passed")
2859
2860 # pass_fds overrides close_fds with a warning.
2861 with self.assertWarns(RuntimeWarning) as context:
2862 self.assertFalse(subprocess.call(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002863 ZERO_RETURN_CMD,
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002864 close_fds=False, pass_fds=(fd, )))
2865 self.assertIn('overriding close_fds', str(context.warning))
2866
Victor Stinnerdaf45552013-08-28 00:53:59 +02002867 def test_pass_fds_inheritable(self):
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002868 script = support.findfile("fd_status.py", subdir="subprocessdata")
Victor Stinnerdaf45552013-08-28 00:53:59 +02002869
2870 inheritable, non_inheritable = os.pipe()
2871 self.addCleanup(os.close, inheritable)
2872 self.addCleanup(os.close, non_inheritable)
2873 os.set_inheritable(inheritable, True)
2874 os.set_inheritable(non_inheritable, False)
2875 pass_fds = (inheritable, non_inheritable)
2876 args = [sys.executable, script]
2877 args += list(map(str, pass_fds))
2878
2879 p = subprocess.Popen(args,
2880 stdout=subprocess.PIPE, close_fds=True,
2881 pass_fds=pass_fds)
2882 output, ignored = p.communicate()
2883 fds = set(map(int, output.split(b',')))
2884
2885 # the inheritable file descriptor must be inherited, so its inheritable
2886 # flag must be set in the child process after fork() and before exec()
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002887 self.assertEqual(fds, set(pass_fds), "output=%a" % output)
Victor Stinnerdaf45552013-08-28 00:53:59 +02002888
2889 # inheritable flag must not be changed in the parent process
2890 self.assertEqual(os.get_inheritable(inheritable), True)
2891 self.assertEqual(os.get_inheritable(non_inheritable), False)
2892
Gregory P. Smithce344102018-09-10 17:46:22 -07002893
2894 # bpo-32270: Ensure that descriptors specified in pass_fds
2895 # are inherited even if they are used in redirections.
2896 # Contributed by @izbyshev.
2897 def test_pass_fds_redirected(self):
2898 """Regression test for https://bugs.python.org/issue32270."""
2899 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2900 pass_fds = []
2901 for _ in range(2):
2902 fd = os.open(os.devnull, os.O_RDWR)
2903 self.addCleanup(os.close, fd)
2904 pass_fds.append(fd)
2905
2906 stdout_r, stdout_w = os.pipe()
2907 self.addCleanup(os.close, stdout_r)
2908 self.addCleanup(os.close, stdout_w)
2909 pass_fds.insert(1, stdout_w)
2910
2911 with subprocess.Popen([sys.executable, fd_status],
2912 stdin=pass_fds[0],
2913 stdout=pass_fds[1],
2914 stderr=pass_fds[2],
2915 close_fds=True,
2916 pass_fds=pass_fds):
2917 output = os.read(stdout_r, 1024)
2918 fds = {int(num) for num in output.split(b',')}
2919
2920 self.assertEqual(fds, {0, 1, 2} | frozenset(pass_fds), f"output={output!a}")
2921
2922
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002923 def test_stdout_stdin_are_single_inout_fd(self):
2924 with io.open(os.devnull, "r+") as inout:
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002925 p = subprocess.Popen(ZERO_RETURN_CMD,
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002926 stdout=inout, stdin=inout)
2927 p.wait()
2928
2929 def test_stdout_stderr_are_single_inout_fd(self):
2930 with io.open(os.devnull, "r+") as inout:
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002931 p = subprocess.Popen(ZERO_RETURN_CMD,
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002932 stdout=inout, stderr=inout)
2933 p.wait()
2934
2935 def test_stderr_stdin_are_single_inout_fd(self):
2936 with io.open(os.devnull, "r+") as inout:
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002937 p = subprocess.Popen(ZERO_RETURN_CMD,
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002938 stderr=inout, stdin=inout)
2939 p.wait()
2940
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002941 def test_wait_when_sigchild_ignored(self):
2942 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
2943 sigchild_ignore = support.findfile("sigchild_ignore.py",
2944 subdir="subprocessdata")
2945 p = subprocess.Popen([sys.executable, sigchild_ignore],
2946 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
2947 stdout, stderr = p.communicate()
2948 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00002949 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00002950 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002951
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002952 def test_select_unbuffered(self):
2953 # Issue #11459: bufsize=0 should really set the pipes as
2954 # unbuffered (and therefore let select() work properly).
Hai Shi0c4f0f32020-06-30 21:46:31 +08002955 select = import_helper.import_module("select")
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002956 p = subprocess.Popen([sys.executable, "-c",
2957 'import sys;'
2958 'sys.stdout.write("apple")'],
2959 stdout=subprocess.PIPE,
2960 bufsize=0)
2961 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02002962 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002963 try:
2964 self.assertEqual(f.read(4), b"appl")
2965 self.assertIn(f, select.select([f], [], [], 0.0)[0])
2966 finally:
2967 p.wait()
2968
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002969 def test_zombie_fast_process_del(self):
2970 # Issue #12650: on Unix, if Popen.__del__() was called before the
2971 # process exited, it wouldn't be added to subprocess._active, and would
2972 # remain a zombie.
2973 # spawn a Popen, and delete its reference before it exits
2974 p = subprocess.Popen([sys.executable, "-c",
2975 'import sys, time;'
2976 'time.sleep(0.2)'],
2977 stdout=subprocess.PIPE,
2978 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002979 self.addCleanup(p.stdout.close)
2980 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002981 ident = id(p)
2982 pid = p.pid
Hai Shi0c4f0f32020-06-30 21:46:31 +08002983 with warnings_helper.check_warnings(('', ResourceWarning)):
Victor Stinner5a48e212016-05-20 12:11:15 +02002984 p = None
2985
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +03002986 if mswindows:
2987 # subprocess._active is not used on Windows and is set to None.
2988 self.assertIsNone(subprocess._active)
2989 else:
2990 # check that p is in the active processes list
2991 self.assertIn(ident, [id(o) for o in subprocess._active])
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002992
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002993 def test_leak_fast_process_del_killed(self):
2994 # Issue #12650: on Unix, if Popen.__del__() was called before the
2995 # process exited, and the process got killed by a signal, it would never
2996 # be removed from subprocess._active, which triggered a FD and memory
2997 # leak.
2998 # spawn a Popen, delete its reference and kill it
2999 p = subprocess.Popen([sys.executable, "-c",
3000 'import time;'
3001 'time.sleep(3)'],
3002 stdout=subprocess.PIPE,
3003 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02003004 self.addCleanup(p.stdout.close)
3005 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02003006 ident = id(p)
3007 pid = p.pid
Hai Shi0c4f0f32020-06-30 21:46:31 +08003008 with warnings_helper.check_warnings(('', ResourceWarning)):
Victor Stinner5a48e212016-05-20 12:11:15 +02003009 p = None
3010
Charles-François Natali134a8ba2011-08-18 18:49:39 +02003011 os.kill(pid, signal.SIGKILL)
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +03003012 if mswindows:
3013 # subprocess._active is not used on Windows and is set to None.
3014 self.assertIsNone(subprocess._active)
3015 else:
3016 # check that p is in the active processes list
3017 self.assertIn(ident, [id(o) for o in subprocess._active])
Charles-François Natali134a8ba2011-08-18 18:49:39 +02003018
3019 # let some time for the process to exit, and create a new Popen: this
3020 # should trigger the wait() of p
3021 time.sleep(0.2)
Victor Stinnerb31206a2018-01-25 19:06:05 +01003022 with self.assertRaises(OSError):
Victor Stinner9a83f652017-08-21 23:51:31 +02003023 with subprocess.Popen(NONEXISTING_CMD,
Charles-François Natali134a8ba2011-08-18 18:49:39 +02003024 stdout=subprocess.PIPE,
3025 stderr=subprocess.PIPE) as proc:
3026 pass
3027 # p should have been wait()ed on, and removed from the _active list
3028 self.assertRaises(OSError, os.waitpid, pid, 0)
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +03003029 if mswindows:
3030 # subprocess._active is not used on Windows and is set to None.
3031 self.assertIsNone(subprocess._active)
3032 else:
3033 self.assertNotIn(ident, [id(o) for o in subprocess._active])
Charles-François Natali134a8ba2011-08-18 18:49:39 +02003034
Charles-François Natali249cdc32013-08-25 18:24:45 +02003035 def test_close_fds_after_preexec(self):
3036 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
3037
3038 # this FD is used as dup2() target by preexec_fn, and should be closed
3039 # in the child process
3040 fd = os.dup(1)
3041 self.addCleanup(os.close, fd)
3042
3043 p = subprocess.Popen([sys.executable, fd_status],
3044 stdout=subprocess.PIPE, close_fds=True,
3045 preexec_fn=lambda: os.dup2(1, fd))
3046 output, ignored = p.communicate()
3047
3048 remaining_fds = set(map(int, output.split(b',')))
3049
3050 self.assertNotIn(fd, remaining_fds)
3051
Victor Stinner8f437aa2014-10-05 17:25:19 +02003052 @support.cpython_only
3053 def test_fork_exec(self):
3054 # Issue #22290: fork_exec() must not crash on memory allocation failure
3055 # or other errors
3056 import _posixsubprocess
3057 gc_enabled = gc.isenabled()
3058 try:
3059 # Use a preexec function and enable the garbage collector
3060 # to force fork_exec() to re-enable the garbage collector
3061 # on error.
3062 func = lambda: None
3063 gc.enable()
3064
Victor Stinner8f437aa2014-10-05 17:25:19 +02003065 for args, exe_list, cwd, env_list in (
3066 (123, [b"exe"], None, [b"env"]),
3067 ([b"arg"], 123, None, [b"env"]),
3068 ([b"arg"], [b"exe"], 123, [b"env"]),
3069 ([b"arg"], [b"exe"], None, 123),
3070 ):
Patrick McLean2b2ead72019-09-12 10:15:44 -07003071 with self.assertRaises(TypeError) as err:
Victor Stinner8f437aa2014-10-05 17:25:19 +02003072 _posixsubprocess.fork_exec(
3073 args, exe_list,
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03003074 True, (), cwd, env_list,
Victor Stinner8f437aa2014-10-05 17:25:19 +02003075 -1, -1, -1, -1,
3076 1, 2, 3, 4,
Patrick McLean2b2ead72019-09-12 10:15:44 -07003077 True, True,
Gregory P. Smithf3751ef2019-10-12 13:24:56 -07003078 False, [], 0, -1,
Patrick McLean2b2ead72019-09-12 10:15:44 -07003079 func)
3080 # Attempt to prevent
3081 # "TypeError: fork_exec() takes exactly N arguments (M given)"
3082 # from passing the test. More refactoring to have us start
3083 # with a valid *args list, confirm a good call with that works
3084 # before mutating it in various ways to ensure that bad calls
3085 # with individual arg type errors raise a typeerror would be
3086 # ideal. Saving that for a future PR...
3087 self.assertNotIn('takes exactly', str(err.exception))
Victor Stinner8f437aa2014-10-05 17:25:19 +02003088 finally:
3089 if not gc_enabled:
3090 gc.disable()
3091
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08003092 @support.cpython_only
3093 def test_fork_exec_sorted_fd_sanity_check(self):
3094 # Issue #23564: sanity check the fork_exec() fds_to_keep sanity check.
3095 import _posixsubprocess
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03003096 class BadInt:
3097 first = True
3098 def __init__(self, value):
3099 self.value = value
3100 def __int__(self):
3101 if self.first:
3102 self.first = False
3103 return self.value
3104 raise ValueError
3105
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08003106 gc_enabled = gc.isenabled()
3107 try:
3108 gc.enable()
3109
3110 for fds_to_keep in (
3111 (-1, 2, 3, 4, 5), # Negative number.
3112 ('str', 4), # Not an int.
3113 (18, 23, 42, 2**63), # Out of range.
3114 (5, 4), # Not sorted.
3115 (6, 7, 7, 8), # Duplicate.
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03003116 (BadInt(1), BadInt(2)),
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08003117 ):
3118 with self.assertRaises(
3119 ValueError,
3120 msg='fds_to_keep={}'.format(fds_to_keep)) as c:
3121 _posixsubprocess.fork_exec(
3122 [b"false"], [b"false"],
3123 True, fds_to_keep, None, [b"env"],
3124 -1, -1, -1, -1,
3125 1, 2, 3, 4,
Patrick McLean2b2ead72019-09-12 10:15:44 -07003126 True, True,
Gregory P. Smithf3751ef2019-10-12 13:24:56 -07003127 None, None, None, -1,
Patrick McLean2b2ead72019-09-12 10:15:44 -07003128 None)
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08003129 self.assertIn('fds_to_keep', str(c.exception))
3130 finally:
3131 if not gc_enabled:
3132 gc.disable()
Victor Stinner8f437aa2014-10-05 17:25:19 +02003133
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)2daf8e72016-06-05 02:57:47 +00003134 def test_communicate_BrokenPipeError_stdin_close(self):
3135 # By not setting stdout or stderr or a timeout we force the fast path
3136 # that just calls _stdin_write() internally due to our mock.
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003137 proc = subprocess.Popen(ZERO_RETURN_CMD)
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)2daf8e72016-06-05 02:57:47 +00003138 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
3139 mock_proc_stdin.close.side_effect = BrokenPipeError
3140 proc.communicate() # Should swallow BrokenPipeError from close.
3141 mock_proc_stdin.close.assert_called_with()
3142
3143 def test_communicate_BrokenPipeError_stdin_write(self):
3144 # By not setting stdout or stderr or a timeout we force the fast path
3145 # that just calls _stdin_write() internally due to our mock.
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003146 proc = subprocess.Popen(ZERO_RETURN_CMD)
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)2daf8e72016-06-05 02:57:47 +00003147 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
3148 mock_proc_stdin.write.side_effect = BrokenPipeError
3149 proc.communicate(b'stuff') # Should swallow the BrokenPipeError.
3150 mock_proc_stdin.write.assert_called_once_with(b'stuff')
3151 mock_proc_stdin.close.assert_called_once_with()
3152
3153 def test_communicate_BrokenPipeError_stdin_flush(self):
3154 # Setting stdin and stdout forces the ._communicate() code path.
3155 # python -h exits faster than python -c pass (but spams stdout).
3156 proc = subprocess.Popen([sys.executable, '-h'],
3157 stdin=subprocess.PIPE,
3158 stdout=subprocess.PIPE)
3159 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin, \
3160 open(os.devnull, 'wb') as dev_null:
3161 mock_proc_stdin.flush.side_effect = BrokenPipeError
3162 # because _communicate registers a selector using proc.stdin...
3163 mock_proc_stdin.fileno.return_value = dev_null.fileno()
3164 # _communicate() should swallow BrokenPipeError from flush.
3165 proc.communicate(b'stuff')
3166 mock_proc_stdin.flush.assert_called_once_with()
3167
3168 def test_communicate_BrokenPipeError_stdin_close_with_timeout(self):
3169 # Setting stdin and stdout forces the ._communicate() code path.
3170 # python -h exits faster than python -c pass (but spams stdout).
3171 proc = subprocess.Popen([sys.executable, '-h'],
3172 stdin=subprocess.PIPE,
3173 stdout=subprocess.PIPE)
3174 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
3175 mock_proc_stdin.close.side_effect = BrokenPipeError
3176 # _communicate() should swallow BrokenPipeError from close.
3177 proc.communicate(timeout=999)
3178 mock_proc_stdin.close.assert_called_once_with()
3179
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003180 @unittest.skipUnless(_testcapi is not None
3181 and hasattr(_testcapi, 'W_STOPCODE'),
3182 'need _testcapi.W_STOPCODE')
3183 def test_stopped(self):
Gregory P. Smith50e16e32017-01-22 17:28:38 -08003184 """Test wait() behavior when waitpid returns WIFSTOPPED; issue29335."""
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003185 args = ZERO_RETURN_CMD
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003186 proc = subprocess.Popen(args)
Victor Stinnercdee3f12017-06-26 17:23:03 +02003187
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003188 # Wait until the real process completes to avoid zombie process
Victor Stinner278c1e12020-03-31 20:08:12 +02003189 support.wait_process(proc.pid, exitcode=0)
Victor Stinnercdee3f12017-06-26 17:23:03 +02003190
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003191 status = _testcapi.W_STOPCODE(3)
Victor Stinner278c1e12020-03-31 20:08:12 +02003192 with mock.patch('subprocess.os.waitpid', return_value=(proc.pid, status)):
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003193 returncode = proc.wait()
Victor Stinnercdee3f12017-06-26 17:23:03 +02003194
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003195 self.assertEqual(returncode, -3)
Gregory P. Smith50e16e32017-01-22 17:28:38 -08003196
Victor Stinnere85a3052020-01-15 17:38:55 +01003197 def test_send_signal_race(self):
3198 # bpo-38630: send_signal() must poll the process exit status to reduce
3199 # the risk of sending the signal to the wrong process.
3200 proc = subprocess.Popen(ZERO_RETURN_CMD)
3201
3202 # wait until the process completes without using the Popen APIs.
Victor Stinner278c1e12020-03-31 20:08:12 +02003203 support.wait_process(proc.pid, exitcode=0)
Victor Stinnere85a3052020-01-15 17:38:55 +01003204
3205 # returncode is still None but the process completed.
3206 self.assertIsNone(proc.returncode)
3207
3208 with mock.patch("os.kill") as mock_kill:
3209 proc.send_signal(signal.SIGTERM)
3210
3211 # send_signal() didn't call os.kill() since the process already
3212 # completed.
3213 mock_kill.assert_not_called()
3214
3215 # Don't check the returncode value: the test reads the exit status,
3216 # so Popen failed to read it and uses a default returncode instead.
3217 self.assertIsNotNone(proc.returncode)
3218
Alex Rebertd3ae95e2020-01-22 18:28:31 -05003219 def test_communicate_repeated_call_after_stdout_close(self):
3220 proc = subprocess.Popen([sys.executable, '-c',
3221 'import os, time; os.close(1), time.sleep(2)'],
3222 stdout=subprocess.PIPE)
3223 while True:
3224 try:
3225 proc.communicate(timeout=0.1)
3226 return
3227 except subprocess.TimeoutExpired:
3228 pass
3229
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003230
Victor Stinner937ee9e2018-06-26 02:11:06 +02003231@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00003232class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00003233
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003234 def test_startupinfo(self):
3235 # startupinfo argument
3236 # We uses hardcoded constants, because we do not want to
3237 # depend on win32all.
3238 STARTF_USESHOWWINDOW = 1
3239 SW_MAXIMIZE = 3
3240 startupinfo = subprocess.STARTUPINFO()
3241 startupinfo.dwFlags = STARTF_USESHOWWINDOW
3242 startupinfo.wShowWindow = SW_MAXIMIZE
3243 # Since Python is a console process, it won't be affected
3244 # by wShowWindow, but the argument should be silently
3245 # ignored
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003246 subprocess.call(ZERO_RETURN_CMD,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003247 startupinfo=startupinfo)
3248
Subhendu Ghoshae160bb2017-02-25 20:29:05 +05303249 def test_startupinfo_keywords(self):
3250 # startupinfo argument
3251 # We use hardcoded constants, because we do not want to
3252 # depend on win32all.
3253 STARTF_USERSHOWWINDOW = 1
3254 SW_MAXIMIZE = 3
3255 startupinfo = subprocess.STARTUPINFO(
3256 dwFlags=STARTF_USERSHOWWINDOW,
3257 wShowWindow=SW_MAXIMIZE
3258 )
3259 # Since Python is a console process, it won't be affected
3260 # by wShowWindow, but the argument should be silently
3261 # ignored
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003262 subprocess.call(ZERO_RETURN_CMD,
Subhendu Ghoshae160bb2017-02-25 20:29:05 +05303263 startupinfo=startupinfo)
3264
Victor Stinner483422f2018-07-05 22:54:17 +02003265 def test_startupinfo_copy(self):
3266 # bpo-34044: Popen must not modify input STARTUPINFO structure
3267 startupinfo = subprocess.STARTUPINFO()
3268 startupinfo.dwFlags = subprocess.STARTF_USESHOWWINDOW
3269 startupinfo.wShowWindow = subprocess.SW_HIDE
3270
3271 # Call Popen() twice with the same startupinfo object to make sure
3272 # that it's not modified
3273 for _ in range(2):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003274 cmd = ZERO_RETURN_CMD
Victor Stinner483422f2018-07-05 22:54:17 +02003275 with open(os.devnull, 'w') as null:
3276 proc = subprocess.Popen(cmd,
3277 stdout=null,
3278 stderr=subprocess.STDOUT,
3279 startupinfo=startupinfo)
3280 with proc:
3281 proc.communicate()
3282 self.assertEqual(proc.returncode, 0)
3283
3284 self.assertEqual(startupinfo.dwFlags,
3285 subprocess.STARTF_USESHOWWINDOW)
3286 self.assertIsNone(startupinfo.hStdInput)
3287 self.assertIsNone(startupinfo.hStdOutput)
3288 self.assertIsNone(startupinfo.hStdError)
3289 self.assertEqual(startupinfo.wShowWindow, subprocess.SW_HIDE)
3290 self.assertEqual(startupinfo.lpAttributeList, {"handle_list": []})
3291
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003292 def test_creationflags(self):
3293 # creationflags argument
3294 CREATE_NEW_CONSOLE = 16
3295 sys.stderr.write(" a DOS box should flash briefly ...\n")
3296 subprocess.call(sys.executable +
3297 ' -c "import time; time.sleep(0.25)"',
3298 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003299
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003300 def test_invalid_args(self):
3301 # invalid arguments should raise ValueError
3302 self.assertRaises(ValueError, subprocess.call,
3303 [sys.executable, "-c",
3304 "import sys; sys.exit(47)"],
3305 preexec_fn=lambda: 1)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003306
Oren Milman0b3a87e2017-09-14 22:30:28 +03003307 @support.cpython_only
3308 def test_issue31471(self):
3309 # There shouldn't be an assertion failure in Popen() in case the env
3310 # argument has a bad keys() method.
3311 class BadEnv(dict):
3312 keys = None
3313 with self.assertRaises(TypeError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003314 subprocess.Popen(ZERO_RETURN_CMD, env=BadEnv())
Oren Milman0b3a87e2017-09-14 22:30:28 +03003315
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003316 def test_close_fds(self):
3317 # close file descriptors
3318 rc = subprocess.call([sys.executable, "-c",
3319 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003320 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003321 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003322
Segev Finerb2a60832017-12-18 11:28:19 +02003323 def test_close_fds_with_stdio(self):
3324 import msvcrt
3325
3326 fds = os.pipe()
3327 self.addCleanup(os.close, fds[0])
3328 self.addCleanup(os.close, fds[1])
3329
3330 handles = []
3331 for fd in fds:
3332 os.set_inheritable(fd, True)
3333 handles.append(msvcrt.get_osfhandle(fd))
3334
3335 p = subprocess.Popen([sys.executable, "-c",
3336 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3337 stdout=subprocess.PIPE, close_fds=False)
3338 stdout, stderr = p.communicate()
3339 self.assertEqual(p.returncode, 0)
3340 int(stdout.strip()) # Check that stdout is an integer
3341
3342 p = subprocess.Popen([sys.executable, "-c",
3343 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3344 stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
3345 stdout, stderr = p.communicate()
3346 self.assertEqual(p.returncode, 1)
3347 self.assertIn(b"OSError", stderr)
3348
3349 # The same as the previous call, but with an empty handle_list
3350 handle_list = []
3351 startupinfo = subprocess.STARTUPINFO()
3352 startupinfo.lpAttributeList = {"handle_list": handle_list}
3353 p = subprocess.Popen([sys.executable, "-c",
3354 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3355 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
3356 startupinfo=startupinfo, close_fds=True)
3357 stdout, stderr = p.communicate()
3358 self.assertEqual(p.returncode, 1)
3359 self.assertIn(b"OSError", stderr)
3360
3361 # Check for a warning due to using handle_list and close_fds=False
Hai Shi0c4f0f32020-06-30 21:46:31 +08003362 with warnings_helper.check_warnings((".*overriding close_fds",
3363 RuntimeWarning)):
Segev Finerb2a60832017-12-18 11:28:19 +02003364 startupinfo = subprocess.STARTUPINFO()
3365 startupinfo.lpAttributeList = {"handle_list": handles[:]}
3366 p = subprocess.Popen([sys.executable, "-c",
3367 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3368 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
3369 startupinfo=startupinfo, close_fds=False)
3370 stdout, stderr = p.communicate()
3371 self.assertEqual(p.returncode, 0)
3372
3373 def test_empty_attribute_list(self):
3374 startupinfo = subprocess.STARTUPINFO()
3375 startupinfo.lpAttributeList = {}
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003376 subprocess.call(ZERO_RETURN_CMD,
Segev Finerb2a60832017-12-18 11:28:19 +02003377 startupinfo=startupinfo)
3378
3379 def test_empty_handle_list(self):
3380 startupinfo = subprocess.STARTUPINFO()
3381 startupinfo.lpAttributeList = {"handle_list": []}
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003382 subprocess.call(ZERO_RETURN_CMD,
Segev Finerb2a60832017-12-18 11:28:19 +02003383 startupinfo=startupinfo)
3384
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003385 def test_shell_sequence(self):
3386 # Run command through the shell (sequence)
3387 newenv = os.environ.copy()
3388 newenv["FRUIT"] = "physalis"
3389 p = subprocess.Popen(["set"], shell=1,
3390 stdout=subprocess.PIPE,
3391 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02003392 with p:
3393 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00003394
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003395 def test_shell_string(self):
3396 # Run command through the shell (string)
3397 newenv = os.environ.copy()
3398 newenv["FRUIT"] = "physalis"
3399 p = subprocess.Popen("set", shell=1,
3400 stdout=subprocess.PIPE,
3401 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02003402 with p:
3403 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003404
Steve Dower050acae2016-09-06 20:16:17 -07003405 def test_shell_encodings(self):
3406 # Run command through the shell (string)
3407 for enc in ['ansi', 'oem']:
3408 newenv = os.environ.copy()
3409 newenv["FRUIT"] = "physalis"
3410 p = subprocess.Popen("set", shell=1,
3411 stdout=subprocess.PIPE,
3412 env=newenv,
3413 encoding=enc)
3414 with p:
3415 self.assertIn("physalis", p.stdout.read(), enc)
3416
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003417 def test_call_string(self):
3418 # call() function with string argument on Windows
3419 rc = subprocess.call(sys.executable +
3420 ' -c "import sys; sys.exit(47)"')
3421 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003422
Florent Xicluna4886d242010-03-08 13:27:26 +00003423 def _kill_process(self, method, *args):
3424 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00003425 p = subprocess.Popen([sys.executable, "-c", """if 1:
3426 import sys, time
3427 sys.stdout.write('x\\n')
3428 sys.stdout.flush()
3429 time.sleep(30)
3430 """],
3431 stdin=subprocess.PIPE,
3432 stdout=subprocess.PIPE,
3433 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02003434 with p:
3435 # Wait for the interpreter to be completely initialized before
3436 # sending any signal.
3437 p.stdout.read(1)
3438 getattr(p, method)(*args)
3439 _, stderr = p.communicate()
Victor Stinner6cac1132019-12-08 08:38:16 +01003440 self.assertEqual(stderr, b'')
Victor Stinner7438c612016-05-20 12:43:15 +02003441 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00003442 self.assertNotEqual(returncode, 0)
3443
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003444 def _kill_dead_process(self, method, *args):
3445 p = subprocess.Popen([sys.executable, "-c", """if 1:
3446 import sys, time
3447 sys.stdout.write('x\\n')
3448 sys.stdout.flush()
3449 sys.exit(42)
3450 """],
3451 stdin=subprocess.PIPE,
3452 stdout=subprocess.PIPE,
3453 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02003454 with p:
3455 # Wait for the interpreter to be completely initialized before
3456 # sending any signal.
3457 p.stdout.read(1)
3458 # The process should end after this
3459 time.sleep(1)
3460 # This shouldn't raise even though the child is now dead
3461 getattr(p, method)(*args)
3462 _, stderr = p.communicate()
Victor Stinner6cac1132019-12-08 08:38:16 +01003463 self.assertEqual(stderr, b'')
Victor Stinner7438c612016-05-20 12:43:15 +02003464 rc = p.wait()
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003465 self.assertEqual(rc, 42)
3466
Florent Xicluna4886d242010-03-08 13:27:26 +00003467 def test_send_signal(self):
3468 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00003469
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003470 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00003471 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00003472
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003473 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00003474 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00003475
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003476 def test_send_signal_dead(self):
3477 self._kill_dead_process('send_signal', signal.SIGTERM)
3478
3479 def test_kill_dead(self):
3480 self._kill_dead_process('kill')
3481
3482 def test_terminate_dead(self):
3483 self._kill_dead_process('terminate')
3484
Martin Panter23172bd2016-04-16 11:28:10 +00003485class MiscTests(unittest.TestCase):
Gregory P. Smithf4d644f2018-01-29 21:27:39 -08003486
3487 class RecordingPopen(subprocess.Popen):
3488 """A Popen that saves a reference to each instance for testing."""
3489 instances_created = []
3490
3491 def __init__(self, *args, **kwargs):
3492 super().__init__(*args, **kwargs)
3493 self.instances_created.append(self)
3494
3495 @mock.patch.object(subprocess.Popen, "_communicate")
3496 def _test_keyboardinterrupt_no_kill(self, popener, mock__communicate,
3497 **kwargs):
3498 """Fake a SIGINT happening during Popen._communicate() and ._wait().
3499
3500 This avoids the need to actually try and get test environments to send
3501 and receive signals reliably across platforms. The net effect of a ^C
3502 happening during a blocking subprocess execution which we want to clean
3503 up from is a KeyboardInterrupt coming out of communicate() or wait().
3504 """
3505
3506 mock__communicate.side_effect = KeyboardInterrupt
3507 try:
3508 with mock.patch.object(subprocess.Popen, "_wait") as mock__wait:
3509 # We patch out _wait() as no signal was involved so the
3510 # child process isn't actually going to exit rapidly.
3511 mock__wait.side_effect = KeyboardInterrupt
3512 with mock.patch.object(subprocess, "Popen",
3513 self.RecordingPopen):
3514 with self.assertRaises(KeyboardInterrupt):
3515 popener([sys.executable, "-c",
3516 "import time\ntime.sleep(9)\nimport sys\n"
3517 "sys.stderr.write('\\n!runaway child!\\n')"],
3518 stdout=subprocess.DEVNULL, **kwargs)
3519 for call in mock__wait.call_args_list[1:]:
3520 self.assertNotEqual(
3521 call, mock.call(timeout=None),
3522 "no open-ended wait() after the first allowed: "
3523 f"{mock__wait.call_args_list}")
3524 sigint_calls = []
3525 for call in mock__wait.call_args_list:
3526 if call == mock.call(timeout=0.25): # from Popen.__init__
3527 sigint_calls.append(call)
3528 self.assertLessEqual(mock__wait.call_count, 2,
3529 msg=mock__wait.call_args_list)
3530 self.assertEqual(len(sigint_calls), 1,
3531 msg=mock__wait.call_args_list)
3532 finally:
3533 # cleanup the forgotten (due to our mocks) child process
3534 process = self.RecordingPopen.instances_created.pop()
3535 process.kill()
3536 process.wait()
3537 self.assertEqual([], self.RecordingPopen.instances_created)
3538
3539 def test_call_keyboardinterrupt_no_kill(self):
3540 self._test_keyboardinterrupt_no_kill(subprocess.call, timeout=6.282)
3541
3542 def test_run_keyboardinterrupt_no_kill(self):
3543 self._test_keyboardinterrupt_no_kill(subprocess.run, timeout=6.282)
3544
3545 def test_context_manager_keyboardinterrupt_no_kill(self):
3546 def popen_via_context_manager(*args, **kwargs):
3547 with subprocess.Popen(*args, **kwargs) as unused_process:
3548 raise KeyboardInterrupt # Test how __exit__ handles ^C.
3549 self._test_keyboardinterrupt_no_kill(popen_via_context_manager)
3550
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003551 def test_getoutput(self):
3552 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
3553 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
3554 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00003555
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003556 # we use mkdtemp in the next line to create an empty directory
3557 # under our exclusive control; from that, we can invent a pathname
3558 # that we _know_ won't exist. This is guaranteed to fail.
3559 dir = None
3560 try:
3561 dir = tempfile.mkdtemp()
3562 name = os.path.join(dir, "foo")
Tim Goldene0041752013-11-03 12:53:17 +00003563 status, output = subprocess.getstatusoutput(
Victor Stinner937ee9e2018-06-26 02:11:06 +02003564 ("type " if mswindows else "cat ") + name)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003565 self.assertNotEqual(status, 0)
3566 finally:
3567 if dir is not None:
3568 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00003569
Gregory P. Smithace55862015-04-07 15:57:54 -07003570 def test__all__(self):
3571 """Ensure that __all__ is populated properly."""
Ruben Vorderman23c0fb82020-10-20 01:30:02 +02003572 intentionally_excluded = {"list2cmdline", "Handle", "pwd", "grp", "fcntl"}
Gregory P. Smithace55862015-04-07 15:57:54 -07003573 exported = set(subprocess.__all__)
3574 possible_exports = set()
3575 import types
3576 for name, value in subprocess.__dict__.items():
3577 if name.startswith('_'):
3578 continue
3579 if isinstance(value, (types.ModuleType,)):
3580 continue
3581 possible_exports.add(name)
3582 self.assertEqual(exported, possible_exports - intentionally_excluded)
3583
3584
Martin Panter23172bd2016-04-16 11:28:10 +00003585@unittest.skipUnless(hasattr(selectors, 'PollSelector'),
3586 "Test needs selectors.PollSelector")
3587class ProcessTestCaseNoPoll(ProcessTestCase):
3588 def setUp(self):
3589 self.orig_selector = subprocess._PopenSelector
3590 subprocess._PopenSelector = selectors.SelectSelector
3591 ProcessTestCase.setUp(self)
3592
3593 def tearDown(self):
3594 subprocess._PopenSelector = self.orig_selector
3595 ProcessTestCase.tearDown(self)
3596
Gregory P. Smithd06fa472009-07-04 02:46:54 +00003597
Victor Stinner937ee9e2018-06-26 02:11:06 +02003598@unittest.skipUnless(mswindows, "Windows-specific tests")
Tim Golden126c2962010-08-11 14:20:40 +00003599class CommandsWithSpaces (BaseTestCase):
3600
3601 def setUp(self):
3602 super().setUp()
Berker Peksag16a1f282015-09-28 13:33:14 +03003603 f, fname = tempfile.mkstemp(".py", "te st")
Tim Golden126c2962010-08-11 14:20:40 +00003604 self.fname = fname.lower ()
3605 os.write(f, b"import sys;"
3606 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
3607 )
3608 os.close(f)
3609
3610 def tearDown(self):
3611 os.remove(self.fname)
3612 super().tearDown()
3613
3614 def with_spaces(self, *args, **kwargs):
3615 kwargs['stdout'] = subprocess.PIPE
3616 p = subprocess.Popen(*args, **kwargs)
Victor Stinner7438c612016-05-20 12:43:15 +02003617 with p:
3618 self.assertEqual(
3619 p.stdout.read ().decode("mbcs"),
3620 "2 [%r, 'ab cd']" % self.fname
3621 )
Tim Golden126c2962010-08-11 14:20:40 +00003622
3623 def test_shell_string_with_spaces(self):
3624 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00003625 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
3626 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00003627
3628 def test_shell_sequence_with_spaces(self):
3629 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00003630 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00003631
3632 def test_noshell_string_with_spaces(self):
3633 # call() function with string argument with spaces on Windows
3634 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
3635 "ab cd"))
3636
3637 def test_noshell_sequence_with_spaces(self):
3638 # call() function with sequence argument with spaces on Windows
3639 self.with_spaces([sys.executable, self.fname, "ab cd"])
3640
Brian Curtin79cdb662010-12-03 02:46:02 +00003641
Georg Brandla86b2622012-02-20 21:34:57 +01003642class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00003643
3644 def test_pipe(self):
3645 with subprocess.Popen([sys.executable, "-c",
3646 "import sys;"
3647 "sys.stdout.write('stdout');"
3648 "sys.stderr.write('stderr');"],
3649 stdout=subprocess.PIPE,
3650 stderr=subprocess.PIPE) as proc:
3651 self.assertEqual(proc.stdout.read(), b"stdout")
Victor Stinner6cac1132019-12-08 08:38:16 +01003652 self.assertEqual(proc.stderr.read(), b"stderr")
Brian Curtin79cdb662010-12-03 02:46:02 +00003653
3654 self.assertTrue(proc.stdout.closed)
3655 self.assertTrue(proc.stderr.closed)
3656
3657 def test_returncode(self):
3658 with subprocess.Popen([sys.executable, "-c",
3659 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07003660 pass
3661 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00003662 self.assertEqual(proc.returncode, 100)
3663
3664 def test_communicate_stdin(self):
3665 with subprocess.Popen([sys.executable, "-c",
3666 "import sys;"
3667 "sys.exit(sys.stdin.read() == 'context')"],
3668 stdin=subprocess.PIPE) as proc:
3669 proc.communicate(b"context")
3670 self.assertEqual(proc.returncode, 1)
3671
3672 def test_invalid_args(self):
Victor Stinnerb31206a2018-01-25 19:06:05 +01003673 with self.assertRaises(NONEXISTING_ERRORS):
Victor Stinner9a83f652017-08-21 23:51:31 +02003674 with subprocess.Popen(NONEXISTING_CMD,
Brian Curtin79cdb662010-12-03 02:46:02 +00003675 stdout=subprocess.PIPE,
3676 stderr=subprocess.PIPE) as proc:
3677 pass
3678
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003679 def test_broken_pipe_cleanup(self):
3680 """Broken pipe error should not prevent wait() (Issue 21619)"""
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003681 proc = subprocess.Popen(ZERO_RETURN_CMD,
Victor Stinner20f4bd42015-03-05 02:38:41 +01003682 stdin=subprocess.PIPE,
Victor Stinner20f4bd42015-03-05 02:38:41 +01003683 bufsize=support.PIPE_MAX_SIZE*2)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003684 proc = proc.__enter__()
3685 # Prepare to send enough data to overflow any OS pipe buffering and
3686 # guarantee a broken pipe error. Data is held in BufferedWriter
3687 # buffer until closed.
3688 proc.stdin.write(b'x' * support.PIPE_MAX_SIZE)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003689 self.assertIsNone(proc.returncode)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003690 # EPIPE expected under POSIX; EINVAL under Windows
Serhiy Storchakacf265fd2015-02-28 13:27:54 +02003691 self.assertRaises(OSError, proc.__exit__, None, None, None)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003692 self.assertEqual(proc.returncode, 0)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003693 self.assertTrue(proc.stdin.closed)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003694
Brian Curtin79cdb662010-12-03 02:46:02 +00003695
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003696if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04003697 unittest.main()