blob: ba2844da9add977e964ce4675575b6c7448f0efc [file] [log] [blame]
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001import unittest
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)1ef8c7e2016-06-04 00:22:17 +00002from unittest import mock
Benjamin Petersonee8712c2008-05-20 21:35:26 +00003from test import support
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00004import subprocess
5import sys
6import signal
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04007import io
Alexey Izbyshev0e7144b2018-03-26 22:49:35 +03008import itertools
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00009import os
Gregory P. Smitha59c59f2010-03-01 00:17:40 +000010import errno
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000011import tempfile
12import time
Gregory P. Smith580d2782019-09-11 04:23:05 -050013import traceback
Guido van Rossum48b069a2020-04-07 09:50:06 -070014import types
Charles-François Natali3a4586a2013-11-08 19:56:59 +010015import selectors
Ezio Melotti184bdfb2010-02-18 09:37:05 +000016import sysconfig
Gregory P. Smith51ee2702010-12-13 07:59:39 +000017import select
Gregory P. Smith81ce6852011-03-15 02:04:11 -040018import shutil
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020019import threading
Benjamin Petersonb870aa12011-12-10 12:44:25 -050020import gc
Andrew Svetlov47ec25d2012-08-19 16:25:37 +030021import textwrap
Patrick McLean2b2ead72019-09-12 10:15:44 -070022import json
Serhiy Storchakab21d1552018-03-02 11:53:51 +020023from test.support import FakePath
Benjamin Peterson964561b2011-12-10 12:31:42 -050024
25try:
Victor Stinner7b7c6dc2017-08-10 12:37:39 +020026 import _testcapi
27except ImportError:
28 _testcapi = None
29
Patrick McLean2b2ead72019-09-12 10:15:44 -070030try:
31 import pwd
32except ImportError:
33 pwd = None
34try:
35 import grp
36except ImportError:
37 grp = None
Victor Stinner8f4ef3b2019-07-01 18:28:25 +020038
Steve Dower22d06982016-09-06 19:38:15 -070039if support.PGO:
40 raise unittest.SkipTest("test is not helpful for PGO")
41
Victor Stinner937ee9e2018-06-26 02:11:06 +020042mswindows = (sys.platform == "win32")
43
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000044#
45# Depends on the following external programs: Python
46#
47
Victor Stinner937ee9e2018-06-26 02:11:06 +020048if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000049 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
50 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000051else:
52 SETBINARY = ''
53
Victor Stinner9a83f652017-08-21 23:51:31 +020054NONEXISTING_CMD = ('nonexisting_i_hope',)
Victor Stinnerb31206a2018-01-25 19:06:05 +010055# Ignore errors that indicate the command was not found
56NONEXISTING_ERRORS = (FileNotFoundError, NotADirectoryError, PermissionError)
Victor Stinner9a83f652017-08-21 23:51:31 +020057
Gregory P. Smith67b93f82019-10-12 16:35:53 -070058ZERO_RETURN_CMD = (sys.executable, '-c', 'pass')
59
60
61def setUpModule():
62 shell_true = shutil.which('true')
Pablo Galindo46113e02019-10-13 02:40:24 +010063 if shell_true is None:
64 return
Gregory P. Smith67b93f82019-10-12 16:35:53 -070065 if (os.access(shell_true, os.X_OK) and
66 subprocess.run([shell_true]).returncode == 0):
67 global ZERO_RETURN_CMD
68 ZERO_RETURN_CMD = (shell_true,) # Faster than Python startup.
69
Florent Xiclunab1e94e82010-02-27 22:12:37 +000070
Florent Xiclunac049d872010-03-27 22:47:23 +000071class BaseTestCase(unittest.TestCase):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000072 def setUp(self):
73 # Try to minimize the number of children we have so this test
74 # doesn't crash on some buildbots (Alphas in particular).
Florent Xiclunab1e94e82010-02-27 22:12:37 +000075 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000076
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000077 def tearDown(self):
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +030078 if not mswindows:
79 # subprocess._active is not used on Windows and is set to None.
80 for inst in subprocess._active:
81 inst.wait()
82 subprocess._cleanup()
83 self.assertFalse(
84 subprocess._active, "subprocess._active not empty"
85 )
Victor Stinnercc42c122017-07-28 18:00:22 +020086 self.doCleanups()
87 support.reap_children()
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000088
Florent Xiclunac049d872010-03-27 22:47:23 +000089
Gregory P. Smith3d8e7762012-11-10 22:32:22 -080090class PopenTestException(Exception):
91 pass
92
93
94class PopenExecuteChildRaises(subprocess.Popen):
95 """Popen subclass for testing cleanup of subprocess.PIPE filehandles when
96 _execute_child fails.
97 """
98 def _execute_child(self, *args, **kwargs):
99 raise PopenTestException("Forced Exception for Test")
100
101
Florent Xiclunac049d872010-03-27 22:47:23 +0000102class ProcessTestCase(BaseTestCase):
103
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700104 def test_io_buffered_by_default(self):
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700105 p = subprocess.Popen(ZERO_RETURN_CMD,
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700106 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
107 stderr=subprocess.PIPE)
108 try:
109 self.assertIsInstance(p.stdin, io.BufferedIOBase)
110 self.assertIsInstance(p.stdout, io.BufferedIOBase)
111 self.assertIsInstance(p.stderr, io.BufferedIOBase)
112 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -0700113 p.stdin.close()
114 p.stdout.close()
115 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700116 p.wait()
117
118 def test_io_unbuffered_works(self):
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700119 p = subprocess.Popen(ZERO_RETURN_CMD,
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700120 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
121 stderr=subprocess.PIPE, bufsize=0)
122 try:
123 self.assertIsInstance(p.stdin, io.RawIOBase)
124 self.assertIsInstance(p.stdout, io.RawIOBase)
125 self.assertIsInstance(p.stderr, io.RawIOBase)
126 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -0700127 p.stdin.close()
128 p.stdout.close()
129 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700130 p.wait()
131
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000132 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000133 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +0000134 rc = subprocess.call([sys.executable, "-c",
135 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000136 self.assertEqual(rc, 47)
137
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400138 def test_call_timeout(self):
139 # call() function with timeout argument; we want to test that the child
140 # process gets killed when the timeout expires. If the child isn't
141 # killed, this call will deadlock since subprocess.call waits for the
142 # child.
143 self.assertRaises(subprocess.TimeoutExpired, subprocess.call,
144 [sys.executable, "-c", "while True: pass"],
145 timeout=0.1)
146
Peter Astrand454f7672005-01-01 09:36:35 +0000147 def test_check_call_zero(self):
148 # check_call() function with zero return code
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700149 rc = subprocess.check_call(ZERO_RETURN_CMD)
Peter Astrand454f7672005-01-01 09:36:35 +0000150 self.assertEqual(rc, 0)
151
152 def test_check_call_nonzero(self):
153 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000154 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +0000155 subprocess.check_call([sys.executable, "-c",
156 "import sys; sys.exit(47)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000157 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +0000158
Georg Brandlf9734072008-12-07 15:30:06 +0000159 def test_check_output(self):
160 # check_output() function with zero return code
161 output = subprocess.check_output(
162 [sys.executable, "-c", "print('BDFL')"])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000163 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000164
165 def test_check_output_nonzero(self):
166 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000167 with self.assertRaises(subprocess.CalledProcessError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000168 subprocess.check_output(
169 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000170 self.assertEqual(c.exception.returncode, 5)
Georg Brandlf9734072008-12-07 15:30:06 +0000171
172 def test_check_output_stderr(self):
173 # check_output() function stderr redirected to stdout
174 output = subprocess.check_output(
175 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
176 stderr=subprocess.STDOUT)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000177 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000178
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300179 def test_check_output_stdin_arg(self):
180 # check_output() can be called with stdin set to a file
181 tf = tempfile.TemporaryFile()
182 self.addCleanup(tf.close)
183 tf.write(b'pear')
184 tf.seek(0)
185 output = subprocess.check_output(
186 [sys.executable, "-c",
187 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
188 stdin=tf)
189 self.assertIn(b'PEAR', output)
190
191 def test_check_output_input_arg(self):
192 # check_output() can be called with input set to a string
193 output = subprocess.check_output(
194 [sys.executable, "-c",
195 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
196 input=b'pear')
197 self.assertIn(b'PEAR', output)
198
Georg Brandlf9734072008-12-07 15:30:06 +0000199 def test_check_output_stdout_arg(self):
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300200 # check_output() refuses to accept 'stdout' argument
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000201 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000202 output = subprocess.check_output(
203 [sys.executable, "-c", "print('will not be run')"],
204 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +0000205 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000206 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +0000207
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300208 def test_check_output_stdin_with_input_arg(self):
209 # check_output() refuses to accept 'stdin' with 'input'
210 tf = tempfile.TemporaryFile()
211 self.addCleanup(tf.close)
212 tf.write(b'pear')
213 tf.seek(0)
214 with self.assertRaises(ValueError) as c:
215 output = subprocess.check_output(
216 [sys.executable, "-c", "print('will not be run')"],
217 stdin=tf, input=b'hare')
218 self.fail("Expected ValueError when stdin and input args supplied.")
219 self.assertIn('stdin', c.exception.args[0])
220 self.assertIn('input', c.exception.args[0])
221
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400222 def test_check_output_timeout(self):
223 # check_output() function with timeout arg
224 with self.assertRaises(subprocess.TimeoutExpired) as c:
225 output = subprocess.check_output(
226 [sys.executable, "-c",
Victor Stinner149b1c72011-06-06 23:43:02 +0200227 "import sys, time\n"
228 "sys.stdout.write('BDFL')\n"
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400229 "sys.stdout.flush()\n"
Victor Stinner149b1c72011-06-06 23:43:02 +0200230 "time.sleep(3600)"],
Reid Klecknerda9ac722011-03-16 17:08:21 -0400231 # Some heavily loaded buildbots (sparc Debian 3.x) require
232 # this much time to start and print.
233 timeout=3)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400234 self.fail("Expected TimeoutExpired.")
235 self.assertEqual(c.exception.output, b'BDFL')
236
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000237 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000238 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000239 newenv = os.environ.copy()
240 newenv["FRUIT"] = "banana"
241 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000242 'import sys, os;'
243 'sys.exit(os.getenv("FRUIT")=="banana")'],
244 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000245 self.assertEqual(rc, 1)
246
Victor Stinner87b9bc32011-06-01 00:57:47 +0200247 def test_invalid_args(self):
248 # Popen() called with invalid arguments should raise TypeError
249 # but Popen.__del__ should not complain (issue #12085)
250 with support.captured_stderr() as s:
251 self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1)
252 argcount = subprocess.Popen.__init__.__code__.co_argcount
253 too_many_args = [0] * (argcount + 1)
254 self.assertRaises(TypeError, subprocess.Popen, *too_many_args)
255 self.assertEqual(s.getvalue(), '')
256
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000257 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000258 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000259 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000260 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000261 self.addCleanup(p.stdout.close)
262 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000263 p.wait()
264 self.assertEqual(p.stdin, None)
265
266 def test_stdout_none(self):
Ezio Melotti42a541b2013-03-11 05:53:34 +0200267 # .stdout is None when not redirected, and the child's stdout will
268 # be inherited from the parent. In order to test this we run a
269 # subprocess in a subprocess:
270 # this_test
271 # \-- subprocess created by this test (parent)
272 # \-- subprocess created by the parent subprocess (child)
273 # The parent doesn't specify stdout, so the child will use the
274 # parent's stdout. This test checks that the message printed by the
275 # child goes to the parent stdout. The parent also checks that the
276 # child's stdout is None. See #11963.
277 code = ('import sys; from subprocess import Popen, PIPE;'
278 'p = Popen([sys.executable, "-c", "print(\'test_stdout_none\')"],'
279 ' stdin=PIPE, stderr=PIPE);'
280 'p.wait(); assert p.stdout is None;')
281 p = subprocess.Popen([sys.executable, "-c", code],
282 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
283 self.addCleanup(p.stdout.close)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000284 self.addCleanup(p.stderr.close)
Ezio Melotti42a541b2013-03-11 05:53:34 +0200285 out, err = p.communicate()
286 self.assertEqual(p.returncode, 0, err)
287 self.assertEqual(out.rstrip(), b'test_stdout_none')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000288
289 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000290 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000291 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000292 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000293 self.addCleanup(p.stdout.close)
294 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000295 p.wait()
296 self.assertEqual(p.stderr, None)
297
Chris Jerdonek776cb192012-10-08 15:56:43 -0700298 def _assert_python(self, pre_args, **kwargs):
299 # We include sys.exit() to prevent the test runner from hanging
300 # whenever python is found.
301 args = pre_args + ["import sys; sys.exit(47)"]
302 p = subprocess.Popen(args, **kwargs)
303 p.wait()
304 self.assertEqual(47, p.returncode)
305
306 def test_executable(self):
307 # Check that the executable argument works.
Chris Jerdonek86b0fb22012-10-09 13:17:49 -0700308 #
309 # On Unix (non-Mac and non-Windows), Python looks at args[0] to
310 # determine where its standard library is, so we need the directory
311 # of args[0] to be valid for the Popen() call to Python to succeed.
312 # See also issue #16170 and issue #7774.
313 doesnotexist = os.path.join(os.path.dirname(sys.executable),
314 "doesnotexist")
315 self._assert_python([doesnotexist, "-c"], executable=sys.executable)
Chris Jerdonek776cb192012-10-08 15:56:43 -0700316
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +0300317 def test_bytes_executable(self):
318 doesnotexist = os.path.join(os.path.dirname(sys.executable),
319 "doesnotexist")
320 self._assert_python([doesnotexist, "-c"],
321 executable=os.fsencode(sys.executable))
322
323 def test_pathlike_executable(self):
324 doesnotexist = os.path.join(os.path.dirname(sys.executable),
325 "doesnotexist")
326 self._assert_python([doesnotexist, "-c"],
327 executable=FakePath(sys.executable))
328
Chris Jerdonek776cb192012-10-08 15:56:43 -0700329 def test_executable_takes_precedence(self):
330 # Check that the executable argument takes precedence over args[0].
331 #
332 # Verify first that the call succeeds without the executable arg.
333 pre_args = [sys.executable, "-c"]
334 self._assert_python(pre_args)
Victor Stinnerb31206a2018-01-25 19:06:05 +0100335 self.assertRaises(NONEXISTING_ERRORS,
Xavier de Gaye38c8b7d2016-11-14 17:14:42 +0100336 self._assert_python, pre_args,
Victor Stinnerb31206a2018-01-25 19:06:05 +0100337 executable=NONEXISTING_CMD[0])
Chris Jerdonek776cb192012-10-08 15:56:43 -0700338
Victor Stinner937ee9e2018-06-26 02:11:06 +0200339 @unittest.skipIf(mswindows, "executable argument replaces shell")
Chris Jerdonek776cb192012-10-08 15:56:43 -0700340 def test_executable_replaces_shell(self):
341 # Check that the executable argument replaces the default shell
342 # when shell=True.
343 self._assert_python([], executable=sys.executable, shell=True)
344
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +0300345 @unittest.skipIf(mswindows, "executable argument replaces shell")
346 def test_bytes_executable_replaces_shell(self):
347 self._assert_python([], executable=os.fsencode(sys.executable),
348 shell=True)
349
350 @unittest.skipIf(mswindows, "executable argument replaces shell")
351 def test_pathlike_executable_replaces_shell(self):
352 self._assert_python([], executable=FakePath(sys.executable),
353 shell=True)
354
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700355 # For use in the test_cwd* tests below.
356 def _normalize_cwd(self, cwd):
357 # Normalize an expected cwd (for Tru64 support).
358 # We can't use os.path.realpath since it doesn't expand Tru64 {memb}
359 # strings. See bug #1063571.
Serhiy Storchaka2a23adf2015-09-06 14:13:25 +0300360 with support.change_cwd(cwd):
361 return os.getcwd()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700362
363 # For use in the test_cwd* tests below.
364 def _split_python_path(self):
365 # Return normalized (python_dir, python_base).
366 python_path = os.path.realpath(sys.executable)
367 return os.path.split(python_path)
368
369 # For use in the test_cwd* tests below.
370 def _assert_cwd(self, expected_cwd, python_arg, **kwargs):
371 # Invoke Python via Popen, and assert that (1) the call succeeds,
372 # and that (2) the current working directory of the child process
373 # matches *expected_cwd*.
374 p = subprocess.Popen([python_arg, "-c",
375 "import os, sys; "
Miss Islington (bot)8b7544c2020-07-26 00:38:52 -0700376 "buf = sys.stdout.buffer; "
377 "buf.write(os.getcwd().encode()); "
378 "buf.flush(); "
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700379 "sys.exit(47)"],
380 stdout=subprocess.PIPE,
381 **kwargs)
382 self.addCleanup(p.stdout.close)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000383 p.wait()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700384 self.assertEqual(47, p.returncode)
385 normcase = os.path.normcase
386 self.assertEqual(normcase(expected_cwd),
Miss Islington (bot)8b7544c2020-07-26 00:38:52 -0700387 normcase(p.stdout.read().decode()))
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700388
389 def test_cwd(self):
390 # Check that cwd changes the cwd for the child process.
391 temp_dir = tempfile.gettempdir()
392 temp_dir = self._normalize_cwd(temp_dir)
393 self._assert_cwd(temp_dir, sys.executable, cwd=temp_dir)
394
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +0300395 def test_cwd_with_bytes(self):
396 temp_dir = tempfile.gettempdir()
397 temp_dir = self._normalize_cwd(temp_dir)
398 self._assert_cwd(temp_dir, sys.executable, cwd=os.fsencode(temp_dir))
399
Sayan Chowdhuryd5c11f72017-02-26 22:36:10 +0530400 def test_cwd_with_pathlike(self):
401 temp_dir = tempfile.gettempdir()
402 temp_dir = self._normalize_cwd(temp_dir)
Serhiy Storchakab21d1552018-03-02 11:53:51 +0200403 self._assert_cwd(temp_dir, sys.executable, cwd=FakePath(temp_dir))
Sayan Chowdhuryd5c11f72017-02-26 22:36:10 +0530404
Victor Stinner937ee9e2018-06-26 02:11:06 +0200405 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700406 def test_cwd_with_relative_arg(self):
407 # Check that Popen looks for args[0] relative to cwd if args[0]
408 # is relative.
409 python_dir, python_base = self._split_python_path()
410 rel_python = os.path.join(os.curdir, python_base)
411 with support.temp_cwd() as wrong_dir:
412 # Before calling with the correct cwd, confirm that the call fails
413 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700414 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700415 [rel_python])
Chris Jerdonek28714c82012-09-30 02:15:37 -0700416 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700417 [rel_python], cwd=wrong_dir)
418 python_dir = self._normalize_cwd(python_dir)
419 self._assert_cwd(python_dir, rel_python, cwd=python_dir)
420
Victor Stinner937ee9e2018-06-26 02:11:06 +0200421 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700422 def test_cwd_with_relative_executable(self):
423 # Check that Popen looks for executable relative to cwd if executable
424 # is relative (and that executable takes precedence over args[0]).
425 python_dir, python_base = self._split_python_path()
426 rel_python = os.path.join(os.curdir, python_base)
427 doesntexist = "somethingyoudonthave"
428 with support.temp_cwd() as wrong_dir:
429 # Before calling with the correct cwd, confirm that the call fails
430 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700431 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700432 [doesntexist], executable=rel_python)
Chris Jerdonek28714c82012-09-30 02:15:37 -0700433 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700434 [doesntexist], executable=rel_python,
435 cwd=wrong_dir)
436 python_dir = self._normalize_cwd(python_dir)
437 self._assert_cwd(python_dir, doesntexist, executable=rel_python,
438 cwd=python_dir)
439
440 def test_cwd_with_absolute_arg(self):
441 # Check that Popen can find the executable when the cwd is wrong
442 # if args[0] is an absolute path.
443 python_dir, python_base = self._split_python_path()
444 abs_python = os.path.join(python_dir, python_base)
445 rel_python = os.path.join(os.curdir, python_base)
Berker Peksagce643912015-05-06 06:33:17 +0300446 with support.temp_dir() as wrong_dir:
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700447 # Before calling with an absolute path, confirm that using a
448 # relative path fails.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700449 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700450 [rel_python], cwd=wrong_dir)
451 wrong_dir = self._normalize_cwd(wrong_dir)
452 self._assert_cwd(wrong_dir, abs_python, cwd=wrong_dir)
453
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100454 @unittest.skipIf(sys.base_prefix != sys.prefix,
455 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000456 def test_executable_with_cwd(self):
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700457 python_dir, python_base = self._split_python_path()
458 python_dir = self._normalize_cwd(python_dir)
459 self._assert_cwd(python_dir, "somethingyoudonthave",
460 executable=sys.executable, cwd=python_dir)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000461
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 @unittest.skipIf(sysconfig.is_python_build(),
465 "need an installed Python. See #7774")
466 def test_executable_without_cwd(self):
467 # For a normal installation, it should work without 'cwd'
468 # argument. For test runs in the build directory, see #7774.
Ned Deilye92dfbf2013-08-02 18:02:21 -0700469 self._assert_cwd(os.getcwd(), "somethingyoudonthave",
470 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000471
472 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000473 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000474 p = subprocess.Popen([sys.executable, "-c",
475 'import sys; sys.exit(sys.stdin.read() == "pear")'],
476 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000477 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000478 p.stdin.close()
479 p.wait()
480 self.assertEqual(p.returncode, 1)
481
482 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000483 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000484 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000485 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000486 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000487 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000488 os.lseek(d, 0, 0)
489 p = subprocess.Popen([sys.executable, "-c",
490 'import sys; sys.exit(sys.stdin.read() == "pear")'],
491 stdin=d)
492 p.wait()
493 self.assertEqual(p.returncode, 1)
494
495 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000496 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000497 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000498 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000499 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000500 tf.seek(0)
501 p = subprocess.Popen([sys.executable, "-c",
502 'import sys; sys.exit(sys.stdin.read() == "pear")'],
503 stdin=tf)
504 p.wait()
505 self.assertEqual(p.returncode, 1)
506
507 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000508 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000509 p = subprocess.Popen([sys.executable, "-c",
510 'import sys; sys.stdout.write("orange")'],
511 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +0200512 with p:
513 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000514
515 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000516 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000517 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000518 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000519 d = tf.fileno()
520 p = subprocess.Popen([sys.executable, "-c",
521 'import sys; sys.stdout.write("orange")'],
522 stdout=d)
523 p.wait()
524 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000525 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000526
527 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000528 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000529 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000530 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000531 p = subprocess.Popen([sys.executable, "-c",
532 'import sys; sys.stdout.write("orange")'],
533 stdout=tf)
534 p.wait()
535 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000536 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000537
538 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000539 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000540 p = subprocess.Popen([sys.executable, "-c",
541 'import sys; sys.stderr.write("strawberry")'],
542 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +0200543 with p:
Victor Stinner6cac1132019-12-08 08:38:16 +0100544 self.assertEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000545
546 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000547 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000548 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000549 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000550 d = tf.fileno()
551 p = subprocess.Popen([sys.executable, "-c",
552 'import sys; sys.stderr.write("strawberry")'],
553 stderr=d)
554 p.wait()
555 os.lseek(d, 0, 0)
Victor Stinner6cac1132019-12-08 08:38:16 +0100556 self.assertEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000557
558 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000559 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000560 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000561 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000562 p = subprocess.Popen([sys.executable, "-c",
563 'import sys; sys.stderr.write("strawberry")'],
564 stderr=tf)
565 p.wait()
566 tf.seek(0)
Victor Stinner6cac1132019-12-08 08:38:16 +0100567 self.assertEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000568
Martin Panterc7635892016-05-13 01:54:44 +0000569 def test_stderr_redirect_with_no_stdout_redirect(self):
570 # test stderr=STDOUT while stdout=None (not set)
571
572 # - grandchild prints to stderr
573 # - child redirects grandchild's stderr to its stdout
574 # - the parent should get grandchild's stderr in child's stdout
575 p = subprocess.Popen([sys.executable, "-c",
576 'import sys, subprocess;'
577 'rc = subprocess.call([sys.executable, "-c",'
578 ' "import sys;"'
579 ' "sys.stderr.write(\'42\')"],'
580 ' stderr=subprocess.STDOUT);'
581 'sys.exit(rc)'],
582 stdout=subprocess.PIPE,
583 stderr=subprocess.PIPE)
584 stdout, stderr = p.communicate()
585 #NOTE: stdout should get stderr from grandchild
Victor Stinner6cac1132019-12-08 08:38:16 +0100586 self.assertEqual(stdout, b'42')
587 self.assertEqual(stderr, b'') # should be empty
Martin Panterc7635892016-05-13 01:54:44 +0000588 self.assertEqual(p.returncode, 0)
589
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000590 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000591 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000592 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000593 'import sys;'
594 'sys.stdout.write("apple");'
595 'sys.stdout.flush();'
596 'sys.stderr.write("orange")'],
597 stdout=subprocess.PIPE,
598 stderr=subprocess.STDOUT)
Victor Stinner7438c612016-05-20 12:43:15 +0200599 with p:
Victor Stinner6cac1132019-12-08 08:38:16 +0100600 self.assertEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000601
602 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000603 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000604 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000605 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000606 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000607 'import sys;'
608 'sys.stdout.write("apple");'
609 'sys.stdout.flush();'
610 'sys.stderr.write("orange")'],
611 stdout=tf,
612 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000613 p.wait()
614 tf.seek(0)
Victor Stinner6cac1132019-12-08 08:38:16 +0100615 self.assertEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000616
Thomas Wouters89f507f2006-12-13 04:49:30 +0000617 def test_stdout_filedes_of_stdout(self):
618 # stdout is set to 1 (#1531862).
Ezio Melotti42a541b2013-03-11 05:53:34 +0200619 # To avoid printing the text on stdout, we do something similar to
620 # test_stdout_none (see above). The parent subprocess calls the child
621 # subprocess passing stdout=1, and this test uses stdout=PIPE in
622 # order to capture and check the output of the parent. See #11963.
623 code = ('import sys, subprocess; '
624 'rc = subprocess.call([sys.executable, "-c", '
625 ' "import os, sys; sys.exit(os.write(sys.stdout.fileno(), '
626 'b\'test with stdout=1\'))"], stdout=1); '
627 'assert rc == 18')
628 p = subprocess.Popen([sys.executable, "-c", code],
629 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
630 self.addCleanup(p.stdout.close)
631 self.addCleanup(p.stderr.close)
632 out, err = p.communicate()
633 self.assertEqual(p.returncode, 0, err)
634 self.assertEqual(out.rstrip(), b'test with stdout=1')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000635
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200636 def test_stdout_devnull(self):
637 p = subprocess.Popen([sys.executable, "-c",
638 'for i in range(10240):'
639 'print("x" * 1024)'],
640 stdout=subprocess.DEVNULL)
641 p.wait()
642 self.assertEqual(p.stdout, None)
643
644 def test_stderr_devnull(self):
645 p = subprocess.Popen([sys.executable, "-c",
646 'import sys\n'
647 'for i in range(10240):'
648 'sys.stderr.write("x" * 1024)'],
649 stderr=subprocess.DEVNULL)
650 p.wait()
651 self.assertEqual(p.stderr, None)
652
653 def test_stdin_devnull(self):
654 p = subprocess.Popen([sys.executable, "-c",
655 'import sys;'
656 'sys.stdin.read(1)'],
657 stdin=subprocess.DEVNULL)
658 p.wait()
659 self.assertEqual(p.stdin, None)
660
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000661 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000662 newenv = os.environ.copy()
663 newenv["FRUIT"] = "orange"
Victor Stinnerf1512a22011-06-21 17:18:38 +0200664 with subprocess.Popen([sys.executable, "-c",
665 'import sys,os;'
666 'sys.stdout.write(os.getenv("FRUIT"))'],
667 stdout=subprocess.PIPE,
668 env=newenv) as p:
669 stdout, stderr = p.communicate()
670 self.assertEqual(stdout, b"orange")
671
Victor Stinner62d51182011-06-23 01:02:25 +0200672 # Windows requires at least the SYSTEMROOT environment variable to start
673 # Python
674 @unittest.skipIf(sys.platform == 'win32',
675 'cannot test an empty env on Windows')
Gregory P. Smithb3512482017-05-30 14:40:37 -0700676 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') == 1,
677 'The Python shared library cannot be loaded '
678 'with an empty environment.')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200679 def test_empty_env(self):
Gregory P. Smithb3512482017-05-30 14:40:37 -0700680 """Verify that env={} is as empty as possible."""
681
Gregory P. Smith85aba232017-05-30 16:21:47 -0700682 def is_env_var_to_ignore(n):
Gregory P. Smithb3512482017-05-30 14:40:37 -0700683 """Determine if an environment variable is under our control."""
684 # This excludes some __CF_* and VERSIONER_* keys MacOS insists
685 # on adding even when the environment in exec is empty.
686 # Gentoo sandboxes also force LD_PRELOAD and SANDBOX_* to exist.
Gregory P. Smith85aba232017-05-30 16:21:47 -0700687 return ('VERSIONER' in n or '__CF' in n or # MacOS
Nick Coghlan6ea41862017-06-11 13:16:15 +1000688 n == 'LD_PRELOAD' or n.startswith('SANDBOX') or # Gentoo
689 n == 'LC_CTYPE') # Locale coercion triggered
Gregory P. Smithb3512482017-05-30 14:40:37 -0700690
Victor Stinnerf1512a22011-06-21 17:18:38 +0200691 with subprocess.Popen([sys.executable, "-c",
Gregory P. Smithb3512482017-05-30 14:40:37 -0700692 'import os; print(list(os.environ.keys()))'],
693 stdout=subprocess.PIPE, env={}) as p:
Victor Stinnerf1512a22011-06-21 17:18:38 +0200694 stdout, stderr = p.communicate()
Gregory P. Smithb3512482017-05-30 14:40:37 -0700695 child_env_names = eval(stdout.strip())
696 self.assertIsInstance(child_env_names, list)
697 child_env_names = [k for k in child_env_names
698 if not is_env_var_to_ignore(k)]
699 self.assertEqual(child_env_names, [])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000700
Serhiy Storchakad174d242017-06-23 19:39:27 +0300701 def test_invalid_cmd(self):
702 # null character in the command name
703 cmd = sys.executable + '\0'
704 with self.assertRaises(ValueError):
705 subprocess.Popen([cmd, "-c", "pass"])
706
707 # null character in the command argument
708 with self.assertRaises(ValueError):
709 subprocess.Popen([sys.executable, "-c", "pass#\0"])
710
711 def test_invalid_env(self):
Ville Skyttä49b27342017-08-03 09:00:59 +0300712 # null character in the environment variable name
Serhiy Storchakad174d242017-06-23 19:39:27 +0300713 newenv = os.environ.copy()
714 newenv["FRUIT\0VEGETABLE"] = "cabbage"
715 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700716 subprocess.Popen(ZERO_RETURN_CMD, env=newenv)
Serhiy Storchakad174d242017-06-23 19:39:27 +0300717
Ville Skyttä49b27342017-08-03 09:00:59 +0300718 # null character in the environment variable value
Serhiy Storchakad174d242017-06-23 19:39:27 +0300719 newenv = os.environ.copy()
720 newenv["FRUIT"] = "orange\0VEGETABLE=cabbage"
721 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700722 subprocess.Popen(ZERO_RETURN_CMD, env=newenv)
Serhiy Storchakad174d242017-06-23 19:39:27 +0300723
Ville Skyttä49b27342017-08-03 09:00:59 +0300724 # equal character in the environment variable name
Serhiy Storchakad174d242017-06-23 19:39:27 +0300725 newenv = os.environ.copy()
726 newenv["FRUIT=ORANGE"] = "lemon"
727 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700728 subprocess.Popen(ZERO_RETURN_CMD, env=newenv)
Serhiy Storchakad174d242017-06-23 19:39:27 +0300729
Ville Skyttä49b27342017-08-03 09:00:59 +0300730 # equal character in the environment variable value
Serhiy Storchakad174d242017-06-23 19:39:27 +0300731 newenv = os.environ.copy()
732 newenv["FRUIT"] = "orange=lemon"
733 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=lemon")
740
Peter Astrandcbac93c2005-03-03 20:24:28 +0000741 def test_communicate_stdin(self):
742 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000743 'import sys;'
744 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000745 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000746 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000747 self.assertEqual(p.returncode, 1)
748
749 def test_communicate_stdout(self):
750 p = subprocess.Popen([sys.executable, "-c",
751 'import sys; sys.stdout.write("pineapple")'],
752 stdout=subprocess.PIPE)
753 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000754 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000755 self.assertEqual(stderr, None)
756
757 def test_communicate_stderr(self):
758 p = subprocess.Popen([sys.executable, "-c",
759 'import sys; sys.stderr.write("pineapple")'],
760 stderr=subprocess.PIPE)
761 (stdout, stderr) = p.communicate()
762 self.assertEqual(stdout, None)
Victor Stinner6cac1132019-12-08 08:38:16 +0100763 self.assertEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000764
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000765 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000766 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000767 'import sys,os;'
768 'sys.stderr.write("pineapple");'
769 'sys.stdout.write(sys.stdin.read())'],
770 stdin=subprocess.PIPE,
771 stdout=subprocess.PIPE,
772 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000773 self.addCleanup(p.stdout.close)
774 self.addCleanup(p.stderr.close)
775 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000776 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000777 self.assertEqual(stdout, b"banana")
Victor Stinner6cac1132019-12-08 08:38:16 +0100778 self.assertEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000779
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400780 def test_communicate_timeout(self):
781 p = subprocess.Popen([sys.executable, "-c",
782 'import sys,os,time;'
783 'sys.stderr.write("pineapple\\n");'
784 'time.sleep(1);'
785 'sys.stderr.write("pear\\n");'
786 'sys.stdout.write(sys.stdin.read())'],
787 universal_newlines=True,
788 stdin=subprocess.PIPE,
789 stdout=subprocess.PIPE,
790 stderr=subprocess.PIPE)
791 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
792 timeout=0.3)
793 # Make sure we can keep waiting for it, and that we get the whole output
794 # after it completes.
795 (stdout, stderr) = p.communicate()
796 self.assertEqual(stdout, "banana")
Victor Stinner6cac1132019-12-08 08:38:16 +0100797 self.assertEqual(stderr.encode(), b"pineapple\npear\n")
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400798
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700799 def test_communicate_timeout_large_output(self):
Ross Lagerwall003c7a32012-02-12 09:02:01 +0200800 # Test an expiring timeout while the child is outputting lots of data.
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400801 p = subprocess.Popen([sys.executable, "-c",
802 'import sys,os,time;'
803 'sys.stdout.write("a" * (64 * 1024));'
804 'time.sleep(0.2);'
805 'sys.stdout.write("a" * (64 * 1024));'
806 'time.sleep(0.2);'
807 'sys.stdout.write("a" * (64 * 1024));'
808 'time.sleep(0.2);'
809 'sys.stdout.write("a" * (64 * 1024));'],
810 stdout=subprocess.PIPE)
811 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
812 (stdout, _) = p.communicate()
813 self.assertEqual(len(stdout), 4 * 64 * 1024)
814
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000815 # Test for the fd leak reported in http://bugs.python.org/issue2791.
816 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000817 for stdin_pipe in (False, True):
818 for stdout_pipe in (False, True):
819 for stderr_pipe in (False, True):
820 options = {}
821 if stdin_pipe:
822 options['stdin'] = subprocess.PIPE
823 if stdout_pipe:
824 options['stdout'] = subprocess.PIPE
825 if stderr_pipe:
826 options['stderr'] = subprocess.PIPE
827 if not options:
828 continue
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700829 p = subprocess.Popen(ZERO_RETURN_CMD, **options)
Victor Stinner667d4b52010-12-25 22:40:32 +0000830 p.communicate()
831 if p.stdin is not None:
832 self.assertTrue(p.stdin.closed)
833 if p.stdout is not None:
834 self.assertTrue(p.stdout.closed)
835 if p.stderr is not None:
836 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000837
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000838 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000839 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000840 p = subprocess.Popen([sys.executable, "-c",
841 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000842 (stdout, stderr) = p.communicate()
843 self.assertEqual(stdout, None)
844 self.assertEqual(stderr, None)
845
846 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000847 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000848 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000849 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000850 x, y = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000851 os.close(x)
852 os.close(y)
853 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000854 'import sys,os;'
855 'sys.stdout.write(sys.stdin.read(47));'
Charles-François Natali2d517212011-05-29 16:36:44 +0200856 'sys.stderr.write("x" * %d);'
857 'sys.stdout.write(sys.stdin.read())' %
858 support.PIPE_MAX_SIZE],
Guido van Rossum98297ee2007-11-06 21:34:58 +0000859 stdin=subprocess.PIPE,
860 stdout=subprocess.PIPE,
861 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000862 self.addCleanup(p.stdout.close)
863 self.addCleanup(p.stderr.close)
864 self.addCleanup(p.stdin.close)
Charles-François Natali2d517212011-05-29 16:36:44 +0200865 string_to_write = b"a" * support.PIPE_MAX_SIZE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000866 (stdout, stderr) = p.communicate(string_to_write)
867 self.assertEqual(stdout, string_to_write)
868
869 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000870 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000871 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000872 'import sys,os;'
873 'sys.stdout.write(sys.stdin.read())'],
874 stdin=subprocess.PIPE,
875 stdout=subprocess.PIPE,
876 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000877 self.addCleanup(p.stdout.close)
878 self.addCleanup(p.stderr.close)
879 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000880 p.stdin.write(b"banana")
881 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000882 self.assertEqual(stdout, b"bananasplit")
Victor Stinner6cac1132019-12-08 08:38:16 +0100883 self.assertEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000884
andyclegg7fed7bd2017-10-23 03:01:19 +0100885 def test_universal_newlines_and_text(self):
886 args = [
887 sys.executable, "-c",
888 'import sys,os;' + SETBINARY +
889 'buf = sys.stdout.buffer;'
890 'buf.write(sys.stdin.readline().encode());'
891 'buf.flush();'
892 'buf.write(b"line2\\n");'
893 'buf.flush();'
894 'buf.write(sys.stdin.read().encode());'
895 'buf.flush();'
896 'buf.write(b"line4\\n");'
897 'buf.flush();'
898 'buf.write(b"line5\\r\\n");'
899 'buf.flush();'
900 'buf.write(b"line6\\r");'
901 'buf.flush();'
902 'buf.write(b"\\nline7");'
903 'buf.flush();'
904 'buf.write(b"\\nline8");']
905
906 for extra_kwarg in ('universal_newlines', 'text'):
907 p = subprocess.Popen(args, **{'stdin': subprocess.PIPE,
908 'stdout': subprocess.PIPE,
909 extra_kwarg: True})
910 with p:
911 p.stdin.write("line1\n")
912 p.stdin.flush()
913 self.assertEqual(p.stdout.readline(), "line1\n")
914 p.stdin.write("line3\n")
915 p.stdin.close()
916 self.addCleanup(p.stdout.close)
917 self.assertEqual(p.stdout.readline(),
918 "line2\n")
919 self.assertEqual(p.stdout.read(6),
920 "line3\n")
921 self.assertEqual(p.stdout.read(),
922 "line4\nline5\nline6\nline7\nline8")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000923
924 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000925 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000926 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000927 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200928 'buf = sys.stdout.buffer;'
929 'buf.write(b"line2\\n");'
930 'buf.flush();'
931 'buf.write(b"line4\\n");'
932 'buf.flush();'
933 'buf.write(b"line5\\r\\n");'
934 'buf.flush();'
935 'buf.write(b"line6\\r");'
936 'buf.flush();'
937 'buf.write(b"\\nline7");'
938 'buf.flush();'
939 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200940 stderr=subprocess.PIPE,
941 stdout=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000942 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000943 self.addCleanup(p.stdout.close)
944 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000945 (stdout, stderr) = p.communicate()
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200946 self.assertEqual(stdout,
947 "line2\nline4\nline5\nline6\nline7\nline8")
948
949 def test_universal_newlines_communicate_stdin(self):
950 # universal newlines through communicate(), with only stdin
951 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300952 'import sys,os;' + SETBINARY + textwrap.dedent('''
953 s = sys.stdin.readline()
954 assert s == "line1\\n", repr(s)
955 s = sys.stdin.read()
956 assert s == "line3\\n", repr(s)
957 ''')],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200958 stdin=subprocess.PIPE,
959 universal_newlines=1)
960 (stdout, stderr) = p.communicate("line1\nline3\n")
961 self.assertEqual(p.returncode, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000962
Andrew Svetlovf3765072012-08-14 18:35:17 +0300963 def test_universal_newlines_communicate_input_none(self):
964 # Test communicate(input=None) with universal newlines.
965 #
966 # We set stdout to PIPE because, as of this writing, a different
967 # code path is tested when the number of pipes is zero or one.
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700968 p = subprocess.Popen(ZERO_RETURN_CMD,
Andrew Svetlovf3765072012-08-14 18:35:17 +0300969 stdin=subprocess.PIPE,
970 stdout=subprocess.PIPE,
971 universal_newlines=True)
972 p.communicate()
973 self.assertEqual(p.returncode, 0)
974
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300975 def test_universal_newlines_communicate_stdin_stdout_stderr(self):
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300976 # universal newlines through communicate(), with stdin, stdout, stderr
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300977 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300978 'import sys,os;' + SETBINARY + textwrap.dedent('''
979 s = sys.stdin.buffer.readline()
980 sys.stdout.buffer.write(s)
981 sys.stdout.buffer.write(b"line2\\r")
982 sys.stderr.buffer.write(b"eline2\\n")
983 s = sys.stdin.buffer.read()
984 sys.stdout.buffer.write(s)
985 sys.stdout.buffer.write(b"line4\\n")
986 sys.stdout.buffer.write(b"line5\\r\\n")
987 sys.stderr.buffer.write(b"eline6\\r")
988 sys.stderr.buffer.write(b"eline7\\r\\nz")
989 ''')],
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300990 stdin=subprocess.PIPE,
991 stderr=subprocess.PIPE,
992 stdout=subprocess.PIPE,
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300993 universal_newlines=True)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300994 self.addCleanup(p.stdout.close)
995 self.addCleanup(p.stderr.close)
996 (stdout, stderr) = p.communicate("line1\nline3\n")
997 self.assertEqual(p.returncode, 0)
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300998 self.assertEqual("line1\nline2\nline3\nline4\nline5\n", stdout)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300999 # Python debug build push something like "[42442 refs]\n"
1000 # to stderr at exit of subprocess.
Andrew Svetlov943c5b32012-08-16 20:17:47 +03001001 self.assertTrue(stderr.startswith("eline2\neline6\neline7\n"))
Andrew Svetlov5395d2f2012-08-15 22:46:43 +03001002
Andrew Svetlov82860712012-08-19 22:13:41 +03001003 def test_universal_newlines_communicate_encodings(self):
1004 # Check that universal newlines mode works for various encodings,
1005 # in particular for encodings in the UTF-16 and UTF-32 families.
1006 # See issue #15595.
1007 #
1008 # UTF-16 and UTF-32-BE are sufficient to check both with BOM and
1009 # without, and UTF-16 and UTF-32.
1010 for encoding in ['utf-16', 'utf-32-be']:
Andrew Svetlov82860712012-08-19 22:13:41 +03001011 code = ("import sys; "
1012 r"sys.stdout.buffer.write('1\r\n2\r3\n4'.encode('%s'))" %
1013 encoding)
1014 args = [sys.executable, '-c', code]
Steve Dower050acae2016-09-06 20:16:17 -07001015 # We set stdin to be non-None because, as of this writing,
1016 # a different code path is used when the number of pipes is
1017 # zero or one.
1018 popen = subprocess.Popen(args,
1019 stdin=subprocess.PIPE,
1020 stdout=subprocess.PIPE,
1021 encoding=encoding)
1022 stdout, stderr = popen.communicate(input='')
Andrew Svetlov82860712012-08-19 22:13:41 +03001023 self.assertEqual(stdout, '1\n2\n3\n4')
1024
Steve Dower050acae2016-09-06 20:16:17 -07001025 def test_communicate_errors(self):
1026 for errors, expected in [
1027 ('ignore', ''),
1028 ('replace', '\ufffd\ufffd'),
1029 ('surrogateescape', '\udc80\udc80'),
1030 ('backslashreplace', '\\x80\\x80'),
1031 ]:
1032 code = ("import sys; "
1033 r"sys.stdout.buffer.write(b'[\x80\x80]')")
1034 args = [sys.executable, '-c', code]
1035 # We set stdin to be non-None because, as of this writing,
1036 # a different code path is used when the number of pipes is
1037 # zero or one.
1038 popen = subprocess.Popen(args,
1039 stdin=subprocess.PIPE,
1040 stdout=subprocess.PIPE,
1041 encoding='utf-8',
1042 errors=errors)
1043 stdout, stderr = popen.communicate(input='')
1044 self.assertEqual(stdout, '[{}]'.format(expected))
1045
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001046 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +00001047 # Make sure we leak no resources
Victor Stinner937ee9e2018-06-26 02:11:06 +02001048 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +00001049 max_handles = 1026 # too much for most UNIX systems
1050 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +00001051 max_handles = 2050 # too much for (at least some) Windows setups
1052 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001053 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +00001054 try:
1055 for i in range(max_handles):
1056 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001057 tmpfile = os.path.join(tmpdir, support.TESTFN)
1058 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +00001059 except OSError as e:
1060 if e.errno != errno.EMFILE:
1061 raise
1062 break
1063 else:
1064 self.skipTest("failed to reach the file descriptor limit "
1065 "(tried %d)" % max_handles)
1066 # Close a couple of them (should be enough for a subprocess)
1067 for i in range(10):
1068 os.close(handles.pop())
1069 # Loop creating some subprocesses. If one of them leaks some fds,
1070 # the next loop iteration will fail by reaching the max fd limit.
1071 for i in range(15):
1072 p = subprocess.Popen([sys.executable, "-c",
1073 "import sys;"
1074 "sys.stdout.write(sys.stdin.read())"],
1075 stdin=subprocess.PIPE,
1076 stdout=subprocess.PIPE,
1077 stderr=subprocess.PIPE)
1078 data = p.communicate(b"lime")[0]
1079 self.assertEqual(data, b"lime")
1080 finally:
1081 for h in handles:
1082 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001083 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001084
1085 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001086 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
1087 '"a b c" d e')
1088 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
1089 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +00001090 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
1091 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001092 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
1093 'a\\\\\\b "de fg" h')
1094 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
1095 'a\\\\\\"b c d')
1096 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
1097 '"a\\\\b c" d e')
1098 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
1099 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001100 self.assertEqual(subprocess.list2cmdline(['ab', '']),
1101 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001102
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001103 def test_poll(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001104 p = subprocess.Popen([sys.executable, "-c",
Ross Lagerwalle7ad4192012-02-22 06:02:07 +02001105 "import os; os.read(0, 1)"],
1106 stdin=subprocess.PIPE)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001107 self.addCleanup(p.stdin.close)
1108 self.assertIsNone(p.poll())
1109 os.write(p.stdin.fileno(), b'A')
1110 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001111 # Subsequent invocations should just return the returncode
1112 self.assertEqual(p.poll(), 0)
1113
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001114 def test_wait(self):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001115 p = subprocess.Popen(ZERO_RETURN_CMD)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001116 self.assertEqual(p.wait(), 0)
1117 # Subsequent invocations should just return the returncode
1118 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +00001119
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001120 def test_wait_timeout(self):
1121 p = subprocess.Popen([sys.executable,
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001122 "-c", "import time; time.sleep(0.3)"])
Reid Kleckner2b228f02011-03-16 16:57:54 -04001123 with self.assertRaises(subprocess.TimeoutExpired) as c:
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001124 p.wait(timeout=0.0001)
1125 self.assertIn("0.0001", str(c.exception)) # For coverage of __str__.
Victor Stinner0d63bac2019-12-11 11:30:03 +01001126 self.assertEqual(p.wait(timeout=support.SHORT_TIMEOUT), 0)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001127
Peter Astrand738131d2004-11-30 21:04:45 +00001128 def test_invalid_bufsize(self):
1129 # an invalid type of the bufsize argument should raise
1130 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001131 with self.assertRaises(TypeError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001132 subprocess.Popen(ZERO_RETURN_CMD, "orange")
Peter Astrand738131d2004-11-30 21:04:45 +00001133
Guido van Rossum46a05a72007-06-07 21:56:45 +00001134 def test_bufsize_is_none(self):
1135 # bufsize=None should be the same as bufsize=0.
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001136 p = subprocess.Popen(ZERO_RETURN_CMD, None)
Guido van Rossum46a05a72007-06-07 21:56:45 +00001137 self.assertEqual(p.wait(), 0)
1138 # Again with keyword arg
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001139 p = subprocess.Popen(ZERO_RETURN_CMD, bufsize=None)
Guido van Rossum46a05a72007-06-07 21:56:45 +00001140 self.assertEqual(p.wait(), 0)
1141
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001142 def _test_bufsize_equal_one(self, line, expected, universal_newlines):
1143 # subprocess may deadlock with bufsize=1, see issue #21332
1144 with subprocess.Popen([sys.executable, "-c", "import sys;"
1145 "sys.stdout.write(sys.stdin.readline());"
1146 "sys.stdout.flush()"],
1147 stdin=subprocess.PIPE,
1148 stdout=subprocess.PIPE,
1149 stderr=subprocess.DEVNULL,
1150 bufsize=1,
1151 universal_newlines=universal_newlines) as p:
1152 p.stdin.write(line) # expect that it flushes the line in text mode
1153 os.close(p.stdin.fileno()) # close it without flushing the buffer
1154 read_line = p.stdout.readline()
Segev Finer4d385172017-08-18 16:18:13 +03001155 with support.SuppressCrashReport():
1156 try:
1157 p.stdin.close()
1158 except OSError:
1159 pass
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001160 p.stdin = None
1161 self.assertEqual(p.returncode, 0)
1162 self.assertEqual(read_line, expected)
1163
1164 def test_bufsize_equal_one_text_mode(self):
1165 # line is flushed in text mode with bufsize=1.
1166 # we should get the full line in return
1167 line = "line\n"
1168 self._test_bufsize_equal_one(line, line, universal_newlines=True)
1169
1170 def test_bufsize_equal_one_binary_mode(self):
1171 # line is not flushed in binary mode with bufsize=1.
1172 # we should get empty response
1173 line = b'line' + os.linesep.encode() # assume ascii-based locale
Alexey Izbysheva2670562018-10-20 03:22:31 +03001174 with self.assertWarnsRegex(RuntimeWarning, 'line buffering'):
1175 self._test_bufsize_equal_one(line, b'', universal_newlines=False)
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001176
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001177 def test_leaking_fds_on_error(self):
1178 # see bug #5179: Popen leaks file descriptors to PIPEs if
1179 # the child fails to execute; this will eventually exhaust
1180 # the maximum number of open fds. 1024 seems a very common
1181 # value for that limit, but Windows has 2048, so we loop
1182 # 1024 times (each call leaked two fds).
1183 for i in range(1024):
Victor Stinnerb31206a2018-01-25 19:06:05 +01001184 with self.assertRaises(NONEXISTING_ERRORS):
Victor Stinner9a83f652017-08-21 23:51:31 +02001185 subprocess.Popen(NONEXISTING_CMD,
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001186 stdout=subprocess.PIPE,
1187 stderr=subprocess.PIPE)
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001188
Victor Stinner9a83f652017-08-21 23:51:31 +02001189 def test_nonexisting_with_pipes(self):
1190 # bpo-30121: Popen with pipes must close properly pipes on error.
1191 # Previously, os.close() was called with a Windows handle which is not
1192 # a valid file descriptor.
1193 #
1194 # Run the test in a subprocess to control how the CRT reports errors
1195 # and to get stderr content.
1196 try:
1197 import msvcrt
1198 msvcrt.CrtSetReportMode
1199 except (AttributeError, ImportError):
1200 self.skipTest("need msvcrt.CrtSetReportMode")
1201
1202 code = textwrap.dedent(f"""
1203 import msvcrt
1204 import subprocess
1205
1206 cmd = {NONEXISTING_CMD!r}
1207
1208 for report_type in [msvcrt.CRT_WARN,
1209 msvcrt.CRT_ERROR,
1210 msvcrt.CRT_ASSERT]:
1211 msvcrt.CrtSetReportMode(report_type, msvcrt.CRTDBG_MODE_FILE)
1212 msvcrt.CrtSetReportFile(report_type, msvcrt.CRTDBG_FILE_STDERR)
1213
1214 try:
Zachary Ware55376462018-02-19 14:02:38 -06001215 subprocess.Popen(cmd,
Victor Stinner9a83f652017-08-21 23:51:31 +02001216 stdout=subprocess.PIPE,
1217 stderr=subprocess.PIPE)
1218 except OSError:
1219 pass
1220 """)
1221 cmd = [sys.executable, "-c", code]
1222 proc = subprocess.Popen(cmd,
1223 stderr=subprocess.PIPE,
1224 universal_newlines=True)
1225 with proc:
1226 stderr = proc.communicate()[1]
1227 self.assertEqual(stderr, "")
1228 self.assertEqual(proc.returncode, 0)
1229
Antoine Pitroua8392712013-08-30 23:38:13 +02001230 def test_double_close_on_error(self):
1231 # Issue #18851
1232 fds = []
1233 def open_fds():
1234 for i in range(20):
1235 fds.extend(os.pipe())
1236 time.sleep(0.001)
1237 t = threading.Thread(target=open_fds)
1238 t.start()
1239 try:
1240 with self.assertRaises(EnvironmentError):
Victor Stinner9a83f652017-08-21 23:51:31 +02001241 subprocess.Popen(NONEXISTING_CMD,
Antoine Pitroua8392712013-08-30 23:38:13 +02001242 stdin=subprocess.PIPE,
1243 stdout=subprocess.PIPE,
1244 stderr=subprocess.PIPE)
1245 finally:
1246 t.join()
1247 exc = None
1248 for fd in fds:
1249 # If a double close occurred, some of those fds will
1250 # already have been closed by mistake, and os.close()
1251 # here will raise.
1252 try:
1253 os.close(fd)
1254 except OSError as e:
1255 exc = e
1256 if exc is not None:
1257 raise exc
1258
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001259 def test_threadsafe_wait(self):
1260 """Issue21291: Popen.wait() needs to be threadsafe for returncode."""
1261 proc = subprocess.Popen([sys.executable, '-c',
1262 'import time; time.sleep(12)'])
1263 self.assertEqual(proc.returncode, None)
1264 results = []
1265
1266 def kill_proc_timer_thread():
1267 results.append(('thread-start-poll-result', proc.poll()))
1268 # terminate it from the thread and wait for the result.
1269 proc.kill()
1270 proc.wait()
1271 results.append(('thread-after-kill-and-wait', proc.returncode))
1272 # this wait should be a no-op given the above.
1273 proc.wait()
1274 results.append(('thread-after-second-wait', proc.returncode))
1275
1276 # This is a timing sensitive test, the failure mode is
1277 # triggered when both the main thread and this thread are in
1278 # the wait() call at once. The delay here is to allow the
1279 # main thread to most likely be blocked in its wait() call.
1280 t = threading.Timer(0.2, kill_proc_timer_thread)
1281 t.start()
1282
Victor Stinner937ee9e2018-06-26 02:11:06 +02001283 if mswindows:
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001284 expected_errorcode = 1
1285 else:
1286 # Should be -9 because of the proc.kill() from the thread.
1287 expected_errorcode = -9
1288
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001289 # Wait for the process to finish; the thread should kill it
1290 # long before it finishes on its own. Supplying a timeout
1291 # triggers a different code path for better coverage.
Victor Stinner0d63bac2019-12-11 11:30:03 +01001292 proc.wait(timeout=support.SHORT_TIMEOUT)
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001293 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001294 msg="unexpected result in wait from main thread")
1295
1296 # This should be a no-op with no change in returncode.
1297 proc.wait()
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001298 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001299 msg="unexpected result in second main wait.")
1300
1301 t.join()
1302 # Ensure that all of the thread results are as expected.
1303 # When a race condition occurs in wait(), the returncode could
1304 # be set by the wrong thread that doesn't actually have it
1305 # leading to an incorrect value.
1306 self.assertEqual([('thread-start-poll-result', None),
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001307 ('thread-after-kill-and-wait', expected_errorcode),
1308 ('thread-after-second-wait', expected_errorcode)],
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001309 results)
1310
Victor Stinnerb3693582010-05-21 20:13:12 +00001311 def test_issue8780(self):
1312 # Ensure that stdout is inherited from the parent
1313 # if stdout=PIPE is not used
1314 code = ';'.join((
1315 'import subprocess, sys',
1316 'retcode = subprocess.call('
1317 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
1318 'assert retcode == 0'))
1319 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001320 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +00001321
Tim Goldenaf5ac392010-08-06 13:03:56 +00001322 def test_handles_closed_on_exception(self):
1323 # If CreateProcess exits with an error, ensure the
1324 # duplicate output handles are released
Berker Peksag16a1f282015-09-28 13:33:14 +03001325 ifhandle, ifname = tempfile.mkstemp()
1326 ofhandle, ofname = tempfile.mkstemp()
1327 efhandle, efname = tempfile.mkstemp()
Tim Goldenaf5ac392010-08-06 13:03:56 +00001328 try:
1329 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
1330 stderr=efhandle)
1331 except OSError:
1332 os.close(ifhandle)
1333 os.remove(ifname)
1334 os.close(ofhandle)
1335 os.remove(ofname)
1336 os.close(efhandle)
1337 os.remove(efname)
1338 self.assertFalse(os.path.exists(ifname))
1339 self.assertFalse(os.path.exists(ofname))
1340 self.assertFalse(os.path.exists(efname))
1341
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001342 def test_communicate_epipe(self):
1343 # Issue 10963: communicate() should hide EPIPE
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001344 p = subprocess.Popen(ZERO_RETURN_CMD,
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001345 stdin=subprocess.PIPE,
1346 stdout=subprocess.PIPE,
1347 stderr=subprocess.PIPE)
1348 self.addCleanup(p.stdout.close)
1349 self.addCleanup(p.stderr.close)
1350 self.addCleanup(p.stdin.close)
1351 p.communicate(b"x" * 2**20)
1352
Andrey Doroschenko645005e2019-11-17 17:08:31 +03001353 def test_repr(self):
1354 # Run a command that waits for user input, to check the repr() of
1355 # a Proc object while and after the sub-process runs.
1356 code = 'import sys; input(); sys.exit(57)'
1357 cmd = [sys.executable, '-c', code]
1358 result = "<Popen: returncode: {}"
1359
1360 with subprocess.Popen(
1361 cmd, stdin=subprocess.PIPE, universal_newlines=True) as proc:
1362 self.assertIsNone(proc.returncode)
1363 self.assertTrue(
1364 repr(proc).startswith(result.format(proc.returncode)) and
1365 repr(proc).endswith('>')
1366 )
1367
1368 proc.communicate(input='exit...\n')
1369 proc.wait()
1370
1371 self.assertIsNotNone(proc.returncode)
1372 self.assertTrue(
1373 repr(proc).startswith(result.format(proc.returncode)) and
1374 repr(proc).endswith('>')
1375 )
1376
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001377 def test_communicate_epipe_only_stdin(self):
1378 # Issue 10963: communicate() should hide EPIPE
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001379 p = subprocess.Popen(ZERO_RETURN_CMD,
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001380 stdin=subprocess.PIPE)
1381 self.addCleanup(p.stdin.close)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001382 p.wait()
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001383 p.communicate(b"x" * 2**20)
1384
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001385 @unittest.skipUnless(hasattr(signal, 'SIGUSR1'),
1386 "Requires signal.SIGUSR1")
1387 @unittest.skipUnless(hasattr(os, 'kill'),
1388 "Requires os.kill")
1389 @unittest.skipUnless(hasattr(os, 'getppid'),
1390 "Requires os.getppid")
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001391 def test_communicate_eintr(self):
1392 # Issue #12493: communicate() should handle EINTR
1393 def handler(signum, frame):
1394 pass
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001395 old_handler = signal.signal(signal.SIGUSR1, handler)
1396 self.addCleanup(signal.signal, signal.SIGUSR1, old_handler)
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001397
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001398 args = [sys.executable, "-c",
1399 'import os, signal;'
1400 'os.kill(os.getppid(), signal.SIGUSR1)']
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001401 for stream in ('stdout', 'stderr'):
1402 kw = {stream: subprocess.PIPE}
1403 with subprocess.Popen(args, **kw) as process:
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001404 # communicate() will be interrupted by SIGUSR1
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001405 process.communicate()
1406
Tim Peterse718f612004-10-12 21:51:32 +00001407
Gregory P. Smith3d8e7762012-11-10 22:32:22 -08001408 # This test is Linux-ish specific for simplicity to at least have
1409 # some coverage. It is not a platform specific bug.
1410 @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
1411 "Linux specific")
1412 def test_failed_child_execute_fd_leak(self):
1413 """Test for the fork() failure fd leak reported in issue16327."""
1414 fd_directory = '/proc/%d/fd' % os.getpid()
1415 fds_before_popen = os.listdir(fd_directory)
1416 with self.assertRaises(PopenTestException):
1417 PopenExecuteChildRaises(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001418 ZERO_RETURN_CMD, stdin=subprocess.PIPE,
Gregory P. Smith3d8e7762012-11-10 22:32:22 -08001419 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1420
1421 # NOTE: This test doesn't verify that the real _execute_child
1422 # does not close the file descriptors itself on the way out
1423 # during an exception. Code inspection has confirmed that.
1424
1425 fds_after_exception = os.listdir(fd_directory)
1426 self.assertEqual(fds_before_popen, fds_after_exception)
1427
Victor Stinner937ee9e2018-06-26 02:11:06 +02001428 @unittest.skipIf(mswindows, "behavior currently not supported on Windows")
Gregory P. Smith8621bb52017-08-24 14:58:25 -07001429 def test_file_not_found_includes_filename(self):
1430 with self.assertRaises(FileNotFoundError) as c:
1431 subprocess.call(['/opt/nonexistent_binary', 'with', 'some', 'args'])
1432 self.assertEqual(c.exception.filename, '/opt/nonexistent_binary')
1433
Victor Stinner937ee9e2018-06-26 02:11:06 +02001434 @unittest.skipIf(mswindows, "behavior currently not supported on Windows")
Gregory P. Smith8621bb52017-08-24 14:58:25 -07001435 def test_file_not_found_with_bad_cwd(self):
1436 with self.assertRaises(FileNotFoundError) as c:
1437 subprocess.Popen(['exit', '0'], cwd='/some/nonexistent/directory')
1438 self.assertEqual(c.exception.filename, '/some/nonexistent/directory')
1439
Batuhan Taşkaya4dc5a9d2019-12-30 19:02:04 +03001440 def test_class_getitems(self):
Guido van Rossum48b069a2020-04-07 09:50:06 -07001441 self.assertIsInstance(subprocess.Popen[bytes], types.GenericAlias)
1442 self.assertIsInstance(subprocess.CompletedProcess[str], types.GenericAlias)
Gregory P. Smith6e730002015-04-14 16:14:25 -07001443
1444class RunFuncTestCase(BaseTestCase):
1445 def run_python(self, code, **kwargs):
1446 """Run Python code in a subprocess using subprocess.run"""
1447 argv = [sys.executable, "-c", code]
1448 return subprocess.run(argv, **kwargs)
1449
1450 def test_returncode(self):
1451 # call() function with sequence argument
1452 cp = self.run_python("import sys; sys.exit(47)")
1453 self.assertEqual(cp.returncode, 47)
1454 with self.assertRaises(subprocess.CalledProcessError):
1455 cp.check_returncode()
1456
1457 def test_check(self):
1458 with self.assertRaises(subprocess.CalledProcessError) as c:
1459 self.run_python("import sys; sys.exit(47)", check=True)
1460 self.assertEqual(c.exception.returncode, 47)
1461
1462 def test_check_zero(self):
1463 # check_returncode shouldn't raise when returncode is zero
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001464 cp = subprocess.run(ZERO_RETURN_CMD, check=True)
Gregory P. Smith6e730002015-04-14 16:14:25 -07001465 self.assertEqual(cp.returncode, 0)
1466
1467 def test_timeout(self):
1468 # run() function with timeout argument; we want to test that the child
1469 # process gets killed when the timeout expires. If the child isn't
1470 # killed, this call will deadlock since subprocess.run waits for the
1471 # child.
1472 with self.assertRaises(subprocess.TimeoutExpired):
1473 self.run_python("while True: pass", timeout=0.0001)
1474
1475 def test_capture_stdout(self):
1476 # capture stdout with zero return code
1477 cp = self.run_python("print('BDFL')", stdout=subprocess.PIPE)
1478 self.assertIn(b'BDFL', cp.stdout)
1479
1480 def test_capture_stderr(self):
1481 cp = self.run_python("import sys; sys.stderr.write('BDFL')",
1482 stderr=subprocess.PIPE)
1483 self.assertIn(b'BDFL', cp.stderr)
1484
1485 def test_check_output_stdin_arg(self):
1486 # run() can be called with stdin set to a file
1487 tf = tempfile.TemporaryFile()
1488 self.addCleanup(tf.close)
1489 tf.write(b'pear')
1490 tf.seek(0)
1491 cp = self.run_python(
1492 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1493 stdin=tf, stdout=subprocess.PIPE)
1494 self.assertIn(b'PEAR', cp.stdout)
1495
1496 def test_check_output_input_arg(self):
1497 # check_output() can be called with input set to a string
1498 cp = self.run_python(
1499 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1500 input=b'pear', stdout=subprocess.PIPE)
1501 self.assertIn(b'PEAR', cp.stdout)
1502
1503 def test_check_output_stdin_with_input_arg(self):
1504 # run() refuses to accept 'stdin' with 'input'
1505 tf = tempfile.TemporaryFile()
1506 self.addCleanup(tf.close)
1507 tf.write(b'pear')
1508 tf.seek(0)
1509 with self.assertRaises(ValueError,
1510 msg="Expected ValueError when stdin and input args supplied.") as c:
1511 output = self.run_python("print('will not be run')",
1512 stdin=tf, input=b'hare')
1513 self.assertIn('stdin', c.exception.args[0])
1514 self.assertIn('input', c.exception.args[0])
1515
1516 def test_check_output_timeout(self):
1517 with self.assertRaises(subprocess.TimeoutExpired) as c:
1518 cp = self.run_python((
1519 "import sys, time\n"
1520 "sys.stdout.write('BDFL')\n"
1521 "sys.stdout.flush()\n"
1522 "time.sleep(3600)"),
1523 # Some heavily loaded buildbots (sparc Debian 3.x) require
1524 # this much time to start and print.
1525 timeout=3, stdout=subprocess.PIPE)
1526 self.assertEqual(c.exception.output, b'BDFL')
1527 # output is aliased to stdout
1528 self.assertEqual(c.exception.stdout, b'BDFL')
1529
1530 def test_run_kwargs(self):
1531 newenv = os.environ.copy()
1532 newenv["FRUIT"] = "banana"
1533 cp = self.run_python(('import sys, os;'
1534 'sys.exit(33 if os.getenv("FRUIT")=="banana" else 31)'),
1535 env=newenv)
1536 self.assertEqual(cp.returncode, 33)
1537
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +03001538 def test_run_with_pathlike_path(self):
1539 # bpo-31961: test run(pathlike_object)
1540 # the name of a command that can be run without
Min ho Kimc4cacc82019-07-31 08:16:13 +10001541 # any arguments that exit fast
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +03001542 prog = 'tree.com' if mswindows else 'ls'
1543 path = shutil.which(prog)
1544 if path is None:
1545 self.skipTest(f'{prog} required for this test')
1546 path = FakePath(path)
1547 res = subprocess.run(path, stdout=subprocess.DEVNULL)
1548 self.assertEqual(res.returncode, 0)
1549 with self.assertRaises(TypeError):
1550 subprocess.run(path, stdout=subprocess.DEVNULL, shell=True)
1551
1552 def test_run_with_bytes_path_and_arguments(self):
1553 # bpo-31961: test run([bytes_object, b'additional arguments'])
1554 path = os.fsencode(sys.executable)
1555 args = [path, '-c', b'import sys; sys.exit(57)']
1556 res = subprocess.run(args)
1557 self.assertEqual(res.returncode, 57)
1558
1559 def test_run_with_pathlike_path_and_arguments(self):
1560 # bpo-31961: test run([pathlike_object, 'additional arguments'])
1561 path = FakePath(sys.executable)
1562 args = [path, '-c', 'import sys; sys.exit(57)']
1563 res = subprocess.run(args)
1564 self.assertEqual(res.returncode, 57)
1565
Bo Baylesce0f33d2018-01-30 00:40:39 -06001566 def test_capture_output(self):
1567 cp = self.run_python(("import sys;"
1568 "sys.stdout.write('BDFL'); "
1569 "sys.stderr.write('FLUFL')"),
1570 capture_output=True)
1571 self.assertIn(b'BDFL', cp.stdout)
1572 self.assertIn(b'FLUFL', cp.stderr)
1573
1574 def test_stdout_with_capture_output_arg(self):
1575 # run() refuses to accept 'stdout' with 'capture_output'
1576 tf = tempfile.TemporaryFile()
1577 self.addCleanup(tf.close)
1578 with self.assertRaises(ValueError,
1579 msg=("Expected ValueError when stdout and capture_output "
1580 "args supplied.")) as c:
1581 output = self.run_python("print('will not be run')",
1582 capture_output=True, stdout=tf)
1583 self.assertIn('stdout', c.exception.args[0])
1584 self.assertIn('capture_output', c.exception.args[0])
1585
1586 def test_stderr_with_capture_output_arg(self):
1587 # run() refuses to accept 'stderr' with 'capture_output'
1588 tf = tempfile.TemporaryFile()
1589 self.addCleanup(tf.close)
1590 with self.assertRaises(ValueError,
1591 msg=("Expected ValueError when stderr and capture_output "
1592 "args supplied.")) as c:
1593 output = self.run_python("print('will not be run')",
1594 capture_output=True, stderr=tf)
1595 self.assertIn('stderr', c.exception.args[0])
1596 self.assertIn('capture_output', c.exception.args[0])
1597
Gregory P. Smith580d2782019-09-11 04:23:05 -05001598 # This test _might_ wind up a bit fragile on loaded build+test machines
1599 # as it depends on the timing with wide enough margins for normal situations
1600 # but does assert that it happened "soon enough" to believe the right thing
1601 # happened.
1602 @unittest.skipIf(mswindows, "requires posix like 'sleep' shell command")
1603 def test_run_with_shell_timeout_and_capture_output(self):
1604 """Output capturing after a timeout mustn't hang forever on open filehandles."""
1605 before_secs = time.monotonic()
1606 try:
1607 subprocess.run('sleep 3', shell=True, timeout=0.1,
1608 capture_output=True) # New session unspecified.
1609 except subprocess.TimeoutExpired as exc:
1610 after_secs = time.monotonic()
1611 stacks = traceback.format_exc() # assertRaises doesn't give this.
1612 else:
1613 self.fail("TimeoutExpired not raised.")
1614 self.assertLess(after_secs - before_secs, 1.5,
1615 msg="TimeoutExpired was delayed! Bad traceback:\n```\n"
1616 f"{stacks}```")
1617
Gregory P. Smith6e730002015-04-14 16:14:25 -07001618
Gregory P. Smith693aa802019-09-13 14:43:35 +01001619def _get_test_grp_name():
Victor Stinnerfaca8552019-09-25 15:52:49 +02001620 for name_group in ('staff', 'nogroup', 'grp', 'nobody', 'nfsnobody'):
Gregory P. Smith693aa802019-09-13 14:43:35 +01001621 if grp:
1622 try:
1623 grp.getgrnam(name_group)
1624 except KeyError:
1625 continue
1626 return name_group
1627 else:
1628 raise unittest.SkipTest('No identified group name to use for this test on this platform.')
1629
1630
Victor Stinner937ee9e2018-06-26 02:11:06 +02001631@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001632class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001633
Gregory P. Smith5591b022012-10-10 03:34:47 -07001634 def setUp(self):
1635 super().setUp()
1636 self._nonexistent_dir = "/_this/pa.th/does/not/exist"
1637
1638 def _get_chdir_exception(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001639 try:
Gregory P. Smith5591b022012-10-10 03:34:47 -07001640 os.chdir(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001641 except OSError as e:
1642 # This avoids hard coding the errno value or the OS perror()
1643 # string and instead capture the exception that we want to see
1644 # below for comparison.
1645 desired_exception = e
1646 else:
Martin Pantereb995702016-07-28 01:11:04 +00001647 self.fail("chdir to nonexistent directory %s succeeded." %
Gregory P. Smith5591b022012-10-10 03:34:47 -07001648 self._nonexistent_dir)
1649 return desired_exception
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001650
Gregory P. Smith5591b022012-10-10 03:34:47 -07001651 def test_exception_cwd(self):
1652 """Test error in the child raised in the parent for a bad cwd."""
1653 desired_exception = self._get_chdir_exception()
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001654 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001655 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smith5591b022012-10-10 03:34:47 -07001656 cwd=self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001657 except OSError as e:
1658 # Test that the child process chdir failure actually makes
1659 # it up to the parent process as the correct exception.
1660 self.assertEqual(desired_exception.errno, e.errno)
1661 self.assertEqual(desired_exception.strerror, e.strerror)
Zackery Spytz73870bf2018-09-11 09:54:07 -06001662 self.assertEqual(desired_exception.filename, e.filename)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001663 else:
1664 self.fail("Expected OSError: %s" % desired_exception)
1665
Gregory P. Smith5591b022012-10-10 03:34:47 -07001666 def test_exception_bad_executable(self):
1667 """Test error in the child raised in the parent for a bad executable."""
1668 desired_exception = self._get_chdir_exception()
1669 try:
1670 p = subprocess.Popen([sys.executable, "-c", ""],
1671 executable=self._nonexistent_dir)
1672 except OSError as e:
1673 # Test that the child process exec failure actually makes
1674 # it up to the parent process as the correct exception.
1675 self.assertEqual(desired_exception.errno, e.errno)
1676 self.assertEqual(desired_exception.strerror, e.strerror)
Zackery Spytz73870bf2018-09-11 09:54:07 -06001677 self.assertEqual(desired_exception.filename, e.filename)
Gregory P. Smith5591b022012-10-10 03:34:47 -07001678 else:
1679 self.fail("Expected OSError: %s" % desired_exception)
1680
1681 def test_exception_bad_args_0(self):
1682 """Test error in the child raised in the parent for a bad args[0]."""
1683 desired_exception = self._get_chdir_exception()
1684 try:
1685 p = subprocess.Popen([self._nonexistent_dir, "-c", ""])
1686 except OSError as e:
1687 # Test that the child process exec failure actually makes
1688 # it up to the parent process as the correct exception.
1689 self.assertEqual(desired_exception.errno, e.errno)
1690 self.assertEqual(desired_exception.strerror, e.strerror)
Zackery Spytz73870bf2018-09-11 09:54:07 -06001691 self.assertEqual(desired_exception.filename, e.filename)
Gregory P. Smith5591b022012-10-10 03:34:47 -07001692 else:
1693 self.fail("Expected OSError: %s" % desired_exception)
1694
Ammar Askar3fc499b2017-09-06 02:41:30 -04001695 # We mock the __del__ method for Popen in the next two tests
1696 # because it does cleanup based on the pid returned by fork_exec
1697 # along with issuing a resource warning if it still exists. Since
1698 # we don't actually spawn a process in these tests we can forego
1699 # the destructor. An alternative would be to set _child_created to
1700 # False before the destructor is called but there is no easy way
1701 # to do that
1702 class PopenNoDestructor(subprocess.Popen):
1703 def __del__(self):
1704 pass
1705
1706 @mock.patch("subprocess._posixsubprocess.fork_exec")
1707 def test_exception_errpipe_normal(self, fork_exec):
1708 """Test error passing done through errpipe_write in the good case"""
1709 def proper_error(*args):
1710 errpipe_write = args[13]
1711 # Write the hex for the error code EISDIR: 'is a directory'
1712 err_code = '{:x}'.format(errno.EISDIR).encode()
1713 os.write(errpipe_write, b"OSError:" + err_code + b":")
1714 return 0
1715
1716 fork_exec.side_effect = proper_error
1717
Victor Stinner11045c92017-10-05 06:32:53 -07001718 with mock.patch("subprocess.os.waitpid",
1719 side_effect=ChildProcessError):
1720 with self.assertRaises(IsADirectoryError):
1721 self.PopenNoDestructor(["non_existent_command"])
Ammar Askar3fc499b2017-09-06 02:41:30 -04001722
1723 @mock.patch("subprocess._posixsubprocess.fork_exec")
1724 def test_exception_errpipe_bad_data(self, fork_exec):
1725 """Test error passing done through errpipe_write where its not
1726 in the expected format"""
1727 error_data = b"\xFF\x00\xDE\xAD"
1728 def bad_error(*args):
1729 errpipe_write = args[13]
1730 # Anything can be in the pipe, no assumptions should
1731 # be made about its encoding, so we'll write some
1732 # arbitrary hex bytes to test it out
1733 os.write(errpipe_write, error_data)
1734 return 0
1735
1736 fork_exec.side_effect = bad_error
1737
Victor Stinner11045c92017-10-05 06:32:53 -07001738 with mock.patch("subprocess.os.waitpid",
1739 side_effect=ChildProcessError):
1740 with self.assertRaises(subprocess.SubprocessError) as e:
1741 self.PopenNoDestructor(["non_existent_command"])
Ammar Askar3fc499b2017-09-06 02:41:30 -04001742
1743 self.assertIn(repr(error_data), str(e.exception))
1744
Gregory P. Smith5f3d04f2018-06-05 12:00:57 -07001745 @unittest.skipIf(not os.path.exists('/proc/self/status'),
1746 "need /proc/self/status")
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001747 def test_restore_signals(self):
Gregory P. Smith5f3d04f2018-06-05 12:00:57 -07001748 # Blindly assume that cat exists on systems with /proc/self/status...
1749 default_proc_status = subprocess.check_output(
1750 ['cat', '/proc/self/status'],
1751 restore_signals=False)
1752 for line in default_proc_status.splitlines():
1753 if line.startswith(b'SigIgn'):
1754 default_sig_ign_mask = line
1755 break
1756 else:
1757 self.skipTest("SigIgn not found in /proc/self/status.")
1758 restored_proc_status = subprocess.check_output(
1759 ['cat', '/proc/self/status'],
1760 restore_signals=True)
1761 for line in restored_proc_status.splitlines():
1762 if line.startswith(b'SigIgn'):
1763 restored_sig_ign_mask = line
1764 break
1765 self.assertNotEqual(default_sig_ign_mask, restored_sig_ign_mask,
1766 msg="restore_signals=True should've unblocked "
1767 "SIGPIPE and friends.")
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001768
1769 def test_start_new_session(self):
1770 # For code coverage of calling setsid(). We don't care if we get an
1771 # EPERM error from it depending on the test execution environment, that
1772 # still indicates that it was called.
1773 try:
1774 output = subprocess.check_output(
Victor Stinner58840432019-06-14 19:31:43 +02001775 [sys.executable, "-c", "import os; print(os.getsid(0))"],
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001776 start_new_session=True)
1777 except OSError as e:
1778 if e.errno != errno.EPERM:
1779 raise
1780 else:
Victor Stinner58840432019-06-14 19:31:43 +02001781 parent_sid = os.getsid(0)
1782 child_sid = int(output)
1783 self.assertNotEqual(parent_sid, child_sid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001784
Patrick McLean2b2ead72019-09-12 10:15:44 -07001785 @unittest.skipUnless(hasattr(os, 'setreuid'), 'no setreuid on platform')
1786 def test_user(self):
1787 # For code coverage of the user parameter. We don't care if we get an
1788 # EPERM error from it depending on the test execution environment, that
1789 # still indicates that it was called.
1790
1791 uid = os.geteuid()
1792 test_users = [65534 if uid != 65534 else 65533, uid]
1793 name_uid = "nobody" if sys.platform != 'darwin' else "unknown"
1794
1795 if pwd is not None:
Victor Stinnerf7b5d412020-03-05 14:28:40 +01001796 try:
1797 pwd.getpwnam(name_uid)
1798 test_users.append(name_uid)
1799 except KeyError:
1800 # unknown user name
1801 name_uid = None
Patrick McLean2b2ead72019-09-12 10:15:44 -07001802
1803 for user in test_users:
Victor Stinnerfaca8552019-09-25 15:52:49 +02001804 # posix_spawn() may be used with close_fds=False
1805 for close_fds in (False, True):
1806 with self.subTest(user=user, close_fds=close_fds):
1807 try:
1808 output = subprocess.check_output(
1809 [sys.executable, "-c",
1810 "import os; print(os.getuid())"],
1811 user=user,
1812 close_fds=close_fds)
1813 except PermissionError: # (EACCES, EPERM)
1814 pass
1815 except OSError as e:
1816 if e.errno not in (errno.EACCES, errno.EPERM):
1817 raise
Patrick McLean2b2ead72019-09-12 10:15:44 -07001818 else:
Victor Stinnerfaca8552019-09-25 15:52:49 +02001819 if isinstance(user, str):
1820 user_uid = pwd.getpwnam(user).pw_uid
1821 else:
1822 user_uid = user
1823 child_user = int(output)
1824 self.assertEqual(child_user, user_uid)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001825
1826 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001827 subprocess.check_call(ZERO_RETURN_CMD, user=-1)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001828
Victor Stinnerf7b5d412020-03-05 14:28:40 +01001829 if pwd is None and name_uid is not None:
Patrick McLean2b2ead72019-09-12 10:15:44 -07001830 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001831 subprocess.check_call(ZERO_RETURN_CMD, user=name_uid)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001832
1833 @unittest.skipIf(hasattr(os, 'setreuid'), 'setreuid() available on platform')
1834 def test_user_error(self):
1835 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001836 subprocess.check_call(ZERO_RETURN_CMD, user=65535)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001837
1838 @unittest.skipUnless(hasattr(os, 'setregid'), 'no setregid() on platform')
1839 def test_group(self):
1840 gid = os.getegid()
1841 group_list = [65534 if gid != 65534 else 65533]
Gregory P. Smith693aa802019-09-13 14:43:35 +01001842 name_group = _get_test_grp_name()
Patrick McLean2b2ead72019-09-12 10:15:44 -07001843
1844 if grp is not None:
1845 group_list.append(name_group)
1846
1847 for group in group_list + [gid]:
Victor Stinnerfaca8552019-09-25 15:52:49 +02001848 # posix_spawn() may be used with close_fds=False
1849 for close_fds in (False, True):
1850 with self.subTest(group=group, close_fds=close_fds):
1851 try:
1852 output = subprocess.check_output(
1853 [sys.executable, "-c",
1854 "import os; print(os.getgid())"],
1855 group=group,
1856 close_fds=close_fds)
1857 except PermissionError: # (EACCES, EPERM)
1858 pass
Patrick McLean2b2ead72019-09-12 10:15:44 -07001859 else:
Victor Stinnerfaca8552019-09-25 15:52:49 +02001860 if isinstance(group, str):
1861 group_gid = grp.getgrnam(group).gr_gid
1862 else:
1863 group_gid = group
Patrick McLean2b2ead72019-09-12 10:15:44 -07001864
Victor Stinnerfaca8552019-09-25 15:52:49 +02001865 child_group = int(output)
1866 self.assertEqual(child_group, group_gid)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001867
1868 # make sure we bomb on negative values
1869 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001870 subprocess.check_call(ZERO_RETURN_CMD, group=-1)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001871
1872 if grp is None:
1873 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001874 subprocess.check_call(ZERO_RETURN_CMD, group=name_group)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001875
1876 @unittest.skipIf(hasattr(os, 'setregid'), 'setregid() available on platform')
1877 def test_group_error(self):
1878 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001879 subprocess.check_call(ZERO_RETURN_CMD, group=65535)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001880
1881 @unittest.skipUnless(hasattr(os, 'setgroups'), 'no setgroups() on platform')
1882 def test_extra_groups(self):
1883 gid = os.getegid()
1884 group_list = [65534 if gid != 65534 else 65533]
Gregory P. Smith693aa802019-09-13 14:43:35 +01001885 name_group = _get_test_grp_name()
Patrick McLean2b2ead72019-09-12 10:15:44 -07001886 perm_error = False
1887
1888 if grp is not None:
1889 group_list.append(name_group)
1890
1891 try:
1892 output = subprocess.check_output(
1893 [sys.executable, "-c",
1894 "import os, sys, json; json.dump(os.getgroups(), sys.stdout)"],
1895 extra_groups=group_list)
1896 except OSError as ex:
1897 if ex.errno != errno.EPERM:
1898 raise
1899 perm_error = True
1900
1901 else:
1902 parent_groups = os.getgroups()
1903 child_groups = json.loads(output)
1904
1905 if grp is not None:
1906 desired_gids = [grp.getgrnam(g).gr_gid if isinstance(g, str) else g
1907 for g in group_list]
1908 else:
1909 desired_gids = group_list
1910
1911 if perm_error:
1912 self.assertEqual(set(child_groups), set(parent_groups))
1913 else:
1914 self.assertEqual(set(desired_gids), set(child_groups))
1915
1916 # make sure we bomb on negative values
1917 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001918 subprocess.check_call(ZERO_RETURN_CMD, extra_groups=[-1])
Patrick McLean2b2ead72019-09-12 10:15:44 -07001919
1920 if grp is None:
1921 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001922 subprocess.check_call(ZERO_RETURN_CMD,
Patrick McLean2b2ead72019-09-12 10:15:44 -07001923 extra_groups=[name_group])
1924
1925 @unittest.skipIf(hasattr(os, 'setgroups'), 'setgroups() available on platform')
1926 def test_extra_groups_error(self):
1927 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001928 subprocess.check_call(ZERO_RETURN_CMD, extra_groups=[])
Patrick McLean2b2ead72019-09-12 10:15:44 -07001929
Gregory P. Smithf3751ef2019-10-12 13:24:56 -07001930 @unittest.skipIf(mswindows or not hasattr(os, 'umask'),
1931 'POSIX umask() is not available.')
1932 def test_umask(self):
1933 tmpdir = None
1934 try:
1935 tmpdir = tempfile.mkdtemp()
1936 name = os.path.join(tmpdir, "beans")
1937 # We set an unusual umask in the child so as a unique mode
1938 # for us to test the child's touched file for.
1939 subprocess.check_call(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001940 [sys.executable, "-c", f"open({name!r}, 'w').close()"],
Gregory P. Smithf3751ef2019-10-12 13:24:56 -07001941 umask=0o053)
1942 # Ignore execute permissions entirely in our test,
1943 # filesystems could be mounted to ignore or force that.
1944 st_mode = os.stat(name).st_mode & 0o666
1945 expected_mode = 0o624
1946 self.assertEqual(expected_mode, st_mode,
1947 msg=f'{oct(expected_mode)} != {oct(st_mode)}')
1948 finally:
1949 if tmpdir is not None:
1950 shutil.rmtree(tmpdir)
1951
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001952 def test_run_abort(self):
1953 # returncode handles signal termination
Antoine Pitrou77e904e2013-10-08 23:04:32 +02001954 with support.SuppressCrashReport():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001955 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001956 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001957 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001958 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001959
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00001960 def test_CalledProcessError_str_signal(self):
1961 err = subprocess.CalledProcessError(-int(signal.SIGABRT), "fake cmd")
1962 error_string = str(err)
1963 # We're relying on the repr() of the signal.Signals intenum to provide
1964 # the word signal, the signal name and the numeric value.
1965 self.assertIn("signal", error_string.lower())
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)b4149062016-06-03 06:19:35 +00001966 # We're not being specific about the signal name as some signals have
1967 # multiple names and which name is revealed can vary.
1968 self.assertIn("SIG", error_string)
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00001969 self.assertIn(str(signal.SIGABRT), error_string)
1970
1971 def test_CalledProcessError_str_unknown_signal(self):
1972 err = subprocess.CalledProcessError(-9876543, "fake cmd")
1973 error_string = str(err)
1974 self.assertIn("unknown signal 9876543.", error_string)
1975
1976 def test_CalledProcessError_str_non_zero(self):
1977 err = subprocess.CalledProcessError(2, "fake cmd")
1978 error_string = str(err)
1979 self.assertIn("non-zero exit status 2.", error_string)
1980
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001981 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001982 # DISCLAIMER: Setting environment variables is *not* a good use
1983 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001984 p = subprocess.Popen([sys.executable, "-c",
1985 'import sys,os;'
1986 'sys.stdout.write(os.getenv("FRUIT"))'],
1987 stdout=subprocess.PIPE,
1988 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Victor Stinner7438c612016-05-20 12:43:15 +02001989 with p:
1990 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001991
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001992 def test_preexec_exception(self):
1993 def raise_it():
1994 raise ValueError("What if two swallows carried a coconut?")
1995 try:
1996 p = subprocess.Popen([sys.executable, "-c", ""],
1997 preexec_fn=raise_it)
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001998 except subprocess.SubprocessError as e:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001999 self.assertTrue(
2000 subprocess._posixsubprocess,
2001 "Expected a ValueError from the preexec_fn")
2002 except ValueError as e:
2003 self.assertIn("coconut", e.args[0])
2004 else:
2005 self.fail("Exception raised by preexec_fn did not make it "
2006 "to the parent process.")
2007
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002008 class _TestExecuteChildPopen(subprocess.Popen):
2009 """Used to test behavior at the end of _execute_child."""
2010 def __init__(self, testcase, *args, **kwargs):
2011 self._testcase = testcase
2012 subprocess.Popen.__init__(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08002013
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002014 def _execute_child(self, *args, **kwargs):
Gregory P. Smith12489d92012-11-11 01:37:02 -08002015 try:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002016 subprocess.Popen._execute_child(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08002017 finally:
2018 # Open a bunch of file descriptors and verify that
2019 # none of them are the same as the ones the Popen
2020 # instance is using for stdin/stdout/stderr.
2021 devzero_fds = [os.open("/dev/zero", os.O_RDONLY)
2022 for _ in range(8)]
2023 try:
2024 for fd in devzero_fds:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002025 self._testcase.assertNotIn(
2026 fd, (self.stdin.fileno(), self.stdout.fileno(),
2027 self.stderr.fileno()),
Gregory P. Smith12489d92012-11-11 01:37:02 -08002028 msg="At least one fd was closed early.")
2029 finally:
Richard Oudkerk0e547b62013-06-10 16:29:19 +01002030 for fd in devzero_fds:
2031 os.close(fd)
Gregory P. Smith12489d92012-11-11 01:37:02 -08002032
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002033 @unittest.skipIf(not os.path.exists("/dev/zero"), "/dev/zero required.")
2034 def test_preexec_errpipe_does_not_double_close_pipes(self):
2035 """Issue16140: Don't double close pipes on preexec error."""
2036
2037 def raise_it():
Gregory P. Smith65ee6ec2012-11-11 10:12:40 -08002038 raise subprocess.SubprocessError(
2039 "force the _execute_child() errpipe_data path.")
Gregory P. Smith12489d92012-11-11 01:37:02 -08002040
Gregory P. Smithc2c4cb62012-11-11 01:41:49 -08002041 with self.assertRaises(subprocess.SubprocessError):
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002042 self._TestExecuteChildPopen(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002043 self, ZERO_RETURN_CMD,
Gregory P. Smith12489d92012-11-11 01:37:02 -08002044 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2045 stderr=subprocess.PIPE, preexec_fn=raise_it)
2046
Gregory P. Smith32ec9da2010-03-19 16:53:08 +00002047 def test_preexec_gc_module_failure(self):
2048 # This tests the code that disables garbage collection if the child
2049 # process will execute any Python.
2050 def raise_runtime_error():
2051 raise RuntimeError("this shouldn't escape")
2052 enabled = gc.isenabled()
2053 orig_gc_disable = gc.disable
2054 orig_gc_isenabled = gc.isenabled
2055 try:
2056 gc.disable()
2057 self.assertFalse(gc.isenabled())
2058 subprocess.call([sys.executable, '-c', ''],
2059 preexec_fn=lambda: None)
2060 self.assertFalse(gc.isenabled(),
2061 "Popen enabled gc when it shouldn't.")
2062
2063 gc.enable()
2064 self.assertTrue(gc.isenabled())
2065 subprocess.call([sys.executable, '-c', ''],
2066 preexec_fn=lambda: None)
2067 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
2068
2069 gc.disable = raise_runtime_error
2070 self.assertRaises(RuntimeError, subprocess.Popen,
2071 [sys.executable, '-c', ''],
2072 preexec_fn=lambda: None)
2073
2074 del gc.isenabled # force an AttributeError
2075 self.assertRaises(AttributeError, subprocess.Popen,
2076 [sys.executable, '-c', ''],
2077 preexec_fn=lambda: None)
2078 finally:
2079 gc.disable = orig_gc_disable
2080 gc.isenabled = orig_gc_isenabled
2081 if not enabled:
2082 gc.disable()
2083
Martin Panterf7fdbda2015-12-05 09:51:52 +00002084 @unittest.skipIf(
2085 sys.platform == 'darwin', 'setrlimit() seems to fail on OS X')
Martin Panterafdd5132015-11-30 02:21:41 +00002086 def test_preexec_fork_failure(self):
2087 # The internal code did not preserve the previous exception when
2088 # re-enabling garbage collection
2089 try:
2090 from resource import getrlimit, setrlimit, RLIMIT_NPROC
2091 except ImportError as err:
2092 self.skipTest(err) # RLIMIT_NPROC is specific to Linux and BSD
2093 limits = getrlimit(RLIMIT_NPROC)
2094 [_, hard] = limits
2095 setrlimit(RLIMIT_NPROC, (0, hard))
2096 self.addCleanup(setrlimit, RLIMIT_NPROC, limits)
Martin Panter5cf791b2015-12-11 05:40:14 +00002097 try:
Martin Panterafdd5132015-11-30 02:21:41 +00002098 subprocess.call([sys.executable, '-c', ''],
2099 preexec_fn=lambda: None)
Martin Panter5cf791b2015-12-11 05:40:14 +00002100 except BlockingIOError:
2101 # Forking should raise EAGAIN, translated to BlockingIOError
2102 pass
2103 else:
2104 self.skipTest('RLIMIT_NPROC had no effect; probably superuser')
Martin Panterafdd5132015-11-30 02:21:41 +00002105
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002106 def test_args_string(self):
2107 # args is a string
Berker Peksag16a1f282015-09-28 13:33:14 +03002108 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002109 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00002110 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02002111 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002112 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
2113 sys.executable)
2114 os.chmod(fname, 0o700)
2115 p = subprocess.Popen(fname)
2116 p.wait()
2117 os.remove(fname)
2118 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002119
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002120 def test_invalid_args(self):
2121 # invalid arguments should raise ValueError
2122 self.assertRaises(ValueError, subprocess.call,
2123 [sys.executable, "-c",
2124 "import sys; sys.exit(47)"],
2125 startupinfo=47)
2126 self.assertRaises(ValueError, subprocess.call,
2127 [sys.executable, "-c",
2128 "import sys; sys.exit(47)"],
2129 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002130
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002131 def test_shell_sequence(self):
2132 # Run command through the shell (sequence)
2133 newenv = os.environ.copy()
2134 newenv["FRUIT"] = "apple"
2135 p = subprocess.Popen(["echo $FRUIT"], shell=1,
2136 stdout=subprocess.PIPE,
2137 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02002138 with p:
2139 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002140
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002141 def test_shell_string(self):
2142 # Run command through the shell (string)
2143 newenv = os.environ.copy()
2144 newenv["FRUIT"] = "apple"
2145 p = subprocess.Popen("echo $FRUIT", shell=1,
2146 stdout=subprocess.PIPE,
2147 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02002148 with p:
2149 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +00002150
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002151 def test_call_string(self):
2152 # call() function with string argument on UNIX
Berker Peksag16a1f282015-09-28 13:33:14 +03002153 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002154 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00002155 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02002156 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002157 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
2158 sys.executable)
2159 os.chmod(fname, 0o700)
2160 rc = subprocess.call(fname)
2161 os.remove(fname)
2162 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00002163
Stefan Krah9542cc62010-07-19 14:20:53 +00002164 def test_specific_shell(self):
2165 # Issue #9265: Incorrect name passed as arg[0].
2166 shells = []
2167 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
2168 for name in ['bash', 'ksh']:
2169 sh = os.path.join(prefix, name)
2170 if os.path.isfile(sh):
2171 shells.append(sh)
2172 if not shells: # Will probably work for any shell but csh.
2173 self.skipTest("bash or ksh required for this test")
2174 sh = '/bin/sh'
2175 if os.path.isfile(sh) and not os.path.islink(sh):
2176 # Test will fail if /bin/sh is a symlink to csh.
2177 shells.append(sh)
2178 for sh in shells:
2179 p = subprocess.Popen("echo $0", executable=sh, shell=True,
2180 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02002181 with p:
2182 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
Stefan Krah9542cc62010-07-19 14:20:53 +00002183
Florent Xicluna4886d242010-03-08 13:27:26 +00002184 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00002185 # Do not inherit file handles from the parent.
2186 # It should fix failures on some platforms.
Gregory P. Smithdee04342013-08-29 13:35:27 -07002187 # Also set the SIGINT handler to the default to make sure it's not
2188 # being ignored (some tests rely on that.)
2189 old_handler = signal.signal(signal.SIGINT, signal.default_int_handler)
2190 try:
2191 p = subprocess.Popen([sys.executable, "-c", """if 1:
2192 import sys, time
2193 sys.stdout.write('x\\n')
2194 sys.stdout.flush()
2195 time.sleep(30)
2196 """],
2197 close_fds=True,
2198 stdin=subprocess.PIPE,
2199 stdout=subprocess.PIPE,
2200 stderr=subprocess.PIPE)
2201 finally:
2202 signal.signal(signal.SIGINT, old_handler)
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00002203 # Wait for the interpreter to be completely initialized before
2204 # sending any signal.
2205 p.stdout.read(1)
2206 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00002207 return p
2208
Charles-François Natali53221e32013-01-12 16:52:20 +01002209 @unittest.skipIf(sys.platform.startswith(('netbsd', 'openbsd')),
2210 "Due to known OS bug (issue #16762)")
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002211 def _kill_dead_process(self, method, *args):
2212 # Do not inherit file handles from the parent.
2213 # It should fix failures on some platforms.
2214 p = subprocess.Popen([sys.executable, "-c", """if 1:
2215 import sys, time
2216 sys.stdout.write('x\\n')
2217 sys.stdout.flush()
2218 """],
2219 close_fds=True,
2220 stdin=subprocess.PIPE,
2221 stdout=subprocess.PIPE,
2222 stderr=subprocess.PIPE)
2223 # Wait for the interpreter to be completely initialized before
2224 # sending any signal.
2225 p.stdout.read(1)
2226 # The process should end after this
2227 time.sleep(1)
2228 # This shouldn't raise even though the child is now dead
2229 getattr(p, method)(*args)
2230 p.communicate()
2231
Florent Xicluna4886d242010-03-08 13:27:26 +00002232 def test_send_signal(self):
2233 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00002234 _, stderr = p.communicate()
2235 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002236 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00002237
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002238 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002239 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00002240 _, stderr = p.communicate()
Victor Stinner6cac1132019-12-08 08:38:16 +01002241 self.assertEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002242 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00002243
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002244 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002245 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00002246 _, stderr = p.communicate()
Victor Stinner6cac1132019-12-08 08:38:16 +01002247 self.assertEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002248 self.assertEqual(p.wait(), -signal.SIGTERM)
2249
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002250 def test_send_signal_dead(self):
2251 # Sending a signal to a dead process
2252 self._kill_dead_process('send_signal', signal.SIGINT)
2253
2254 def test_kill_dead(self):
2255 # Killing a dead process
2256 self._kill_dead_process('kill')
2257
2258 def test_terminate_dead(self):
2259 # Terminating a dead process
2260 self._kill_dead_process('terminate')
2261
Victor Stinnerdaf45552013-08-28 00:53:59 +02002262 def _save_fds(self, save_fds):
2263 fds = []
2264 for fd in save_fds:
2265 inheritable = os.get_inheritable(fd)
2266 saved = os.dup(fd)
2267 fds.append((fd, saved, inheritable))
2268 return fds
2269
2270 def _restore_fds(self, fds):
2271 for fd, saved, inheritable in fds:
2272 os.dup2(saved, fd, inheritable=inheritable)
2273 os.close(saved)
2274
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002275 def check_close_std_fds(self, fds):
2276 # Issue #9905: test that subprocess pipes still work properly with
2277 # some standard fds closed
2278 stdin = 0
Victor Stinnerdaf45552013-08-28 00:53:59 +02002279 saved_fds = self._save_fds(fds)
2280 for fd, saved, inheritable in saved_fds:
2281 if fd == 0:
2282 stdin = saved
2283 break
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002284 try:
2285 for fd in fds:
2286 os.close(fd)
2287 out, err = subprocess.Popen([sys.executable, "-c",
2288 'import sys;'
2289 'sys.stdout.write("apple");'
2290 'sys.stdout.flush();'
2291 'sys.stderr.write("orange")'],
2292 stdin=stdin,
2293 stdout=subprocess.PIPE,
2294 stderr=subprocess.PIPE).communicate()
Victor Stinner6cac1132019-12-08 08:38:16 +01002295 self.assertEqual(out, b'apple')
2296 self.assertEqual(err, b'orange')
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002297 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002298 self._restore_fds(saved_fds)
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002299
2300 def test_close_fd_0(self):
2301 self.check_close_std_fds([0])
2302
2303 def test_close_fd_1(self):
2304 self.check_close_std_fds([1])
2305
2306 def test_close_fd_2(self):
2307 self.check_close_std_fds([2])
2308
2309 def test_close_fds_0_1(self):
2310 self.check_close_std_fds([0, 1])
2311
2312 def test_close_fds_0_2(self):
2313 self.check_close_std_fds([0, 2])
2314
2315 def test_close_fds_1_2(self):
2316 self.check_close_std_fds([1, 2])
2317
2318 def test_close_fds_0_1_2(self):
2319 # Issue #10806: test that subprocess pipes still work properly with
2320 # all standard fds closed.
2321 self.check_close_std_fds([0, 1, 2])
2322
Gregory P. Smith53dd8162013-12-01 16:03:24 -08002323 def test_small_errpipe_write_fd(self):
2324 """Issue #15798: Popen should work when stdio fds are available."""
2325 new_stdin = os.dup(0)
2326 new_stdout = os.dup(1)
2327 try:
2328 os.close(0)
2329 os.close(1)
2330
2331 # Side test: if errpipe_write fails to have its CLOEXEC
2332 # flag set this should cause the parent to think the exec
2333 # failed. Extremely unlikely: everyone supports CLOEXEC.
2334 subprocess.Popen([
2335 sys.executable, "-c",
2336 "print('AssertionError:0:CLOEXEC failure.')"]).wait()
2337 finally:
2338 # Restore original stdin and stdout
2339 os.dup2(new_stdin, 0)
2340 os.dup2(new_stdout, 1)
2341 os.close(new_stdin)
2342 os.close(new_stdout)
2343
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002344 def test_remapping_std_fds(self):
2345 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03002346 temps = [tempfile.mkstemp() for i in range(3)]
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002347 try:
2348 temp_fds = [fd for fd, fname in temps]
2349
2350 # unlink the files -- we won't need to reopen them
2351 for fd, fname in temps:
2352 os.unlink(fname)
2353
2354 # write some data to what will become stdin, and rewind
2355 os.write(temp_fds[1], b"STDIN")
2356 os.lseek(temp_fds[1], 0, 0)
2357
2358 # move the standard file descriptors out of the way
Victor Stinnerdaf45552013-08-28 00:53:59 +02002359 saved_fds = self._save_fds(range(3))
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002360 try:
2361 # duplicate the file objects over the standard fd's
2362 for fd, temp_fd in enumerate(temp_fds):
2363 os.dup2(temp_fd, fd)
2364
2365 # now use those files in the "wrong" order, so that subprocess
2366 # has to rearrange them in the child
2367 p = subprocess.Popen([sys.executable, "-c",
2368 'import sys; got = sys.stdin.read();'
2369 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
2370 stdin=temp_fds[1],
2371 stdout=temp_fds[2],
2372 stderr=temp_fds[0])
2373 p.wait()
2374 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002375 self._restore_fds(saved_fds)
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002376
2377 for fd in temp_fds:
2378 os.lseek(fd, 0, 0)
2379
2380 out = os.read(temp_fds[2], 1024)
Victor Stinner6cac1132019-12-08 08:38:16 +01002381 err = os.read(temp_fds[0], 1024).strip()
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002382 self.assertEqual(out, b"got STDIN")
2383 self.assertEqual(err, b"err")
2384
2385 finally:
2386 for fd in temp_fds:
2387 os.close(fd)
2388
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002389 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
2390 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03002391 temps = [tempfile.mkstemp() for i in range(3)]
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002392 temp_fds = [fd for fd, fname in temps]
2393 try:
2394 # unlink the files -- we won't need to reopen them
2395 for fd, fname in temps:
2396 os.unlink(fname)
2397
2398 # save a copy of the standard file descriptors
Victor Stinnerdaf45552013-08-28 00:53:59 +02002399 saved_fds = self._save_fds(range(3))
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002400 try:
2401 # duplicate the temp files over the standard fd's 0, 1, 2
2402 for fd, temp_fd in enumerate(temp_fds):
2403 os.dup2(temp_fd, fd)
2404
2405 # write some data to what will become stdin, and rewind
2406 os.write(stdin_no, b"STDIN")
2407 os.lseek(stdin_no, 0, 0)
2408
2409 # now use those files in the given order, so that subprocess
2410 # has to rearrange them in the child
2411 p = subprocess.Popen([sys.executable, "-c",
2412 'import sys; got = sys.stdin.read();'
2413 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
2414 stdin=stdin_no,
2415 stdout=stdout_no,
2416 stderr=stderr_no)
2417 p.wait()
2418
2419 for fd in temp_fds:
2420 os.lseek(fd, 0, 0)
2421
2422 out = os.read(stdout_no, 1024)
Victor Stinner6cac1132019-12-08 08:38:16 +01002423 err = os.read(stderr_no, 1024).strip()
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002424 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002425 self._restore_fds(saved_fds)
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002426
2427 self.assertEqual(out, b"got STDIN")
2428 self.assertEqual(err, b"err")
2429
2430 finally:
2431 for fd in temp_fds:
2432 os.close(fd)
2433
2434 # When duping fds, if there arises a situation where one of the fds is
2435 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
2436 # This tests all combinations of this.
2437 def test_swap_fds(self):
2438 self.check_swap_fds(0, 1, 2)
2439 self.check_swap_fds(0, 2, 1)
2440 self.check_swap_fds(1, 0, 2)
2441 self.check_swap_fds(1, 2, 0)
2442 self.check_swap_fds(2, 0, 1)
2443 self.check_swap_fds(2, 1, 0)
2444
Alexey Izbyshev0e7144b2018-03-26 22:49:35 +03002445 def _check_swap_std_fds_with_one_closed(self, from_fds, to_fds):
2446 saved_fds = self._save_fds(range(3))
2447 try:
2448 for from_fd in from_fds:
2449 with tempfile.TemporaryFile() as f:
2450 os.dup2(f.fileno(), from_fd)
2451
2452 fd_to_close = (set(range(3)) - set(from_fds)).pop()
2453 os.close(fd_to_close)
2454
2455 arg_names = ['stdin', 'stdout', 'stderr']
2456 kwargs = {}
2457 for from_fd, to_fd in zip(from_fds, to_fds):
2458 kwargs[arg_names[to_fd]] = from_fd
2459
2460 code = textwrap.dedent(r'''
2461 import os, sys
2462 skipped_fd = int(sys.argv[1])
2463 for fd in range(3):
2464 if fd != skipped_fd:
2465 os.write(fd, str(fd).encode('ascii'))
2466 ''')
2467
2468 skipped_fd = (set(range(3)) - set(to_fds)).pop()
2469
2470 rc = subprocess.call([sys.executable, '-c', code, str(skipped_fd)],
2471 **kwargs)
2472 self.assertEqual(rc, 0)
2473
2474 for from_fd, to_fd in zip(from_fds, to_fds):
2475 os.lseek(from_fd, 0, os.SEEK_SET)
2476 read_bytes = os.read(from_fd, 1024)
2477 read_fds = list(map(int, read_bytes.decode('ascii')))
2478 msg = textwrap.dedent(f"""
2479 When testing {from_fds} to {to_fds} redirection,
2480 parent descriptor {from_fd} got redirected
2481 to descriptor(s) {read_fds} instead of descriptor {to_fd}.
2482 """)
2483 self.assertEqual([to_fd], read_fds, msg)
2484 finally:
2485 self._restore_fds(saved_fds)
2486
2487 # Check that subprocess can remap std fds correctly even
2488 # if one of them is closed (#32844).
2489 def test_swap_std_fds_with_one_closed(self):
2490 for from_fds in itertools.combinations(range(3), 2):
2491 for to_fds in itertools.permutations(range(3), 2):
2492 self._check_swap_std_fds_with_one_closed(from_fds, to_fds)
2493
Victor Stinner13bb71c2010-04-23 21:41:56 +00002494 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00002495 def prepare():
2496 raise ValueError("surrogate:\uDCff")
2497
2498 try:
2499 subprocess.call(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002500 ZERO_RETURN_CMD,
Victor Stinner4d078042010-04-23 19:28:32 +00002501 preexec_fn=prepare)
2502 except ValueError as err:
2503 # Pure Python implementations keeps the message
2504 self.assertIsNone(subprocess._posixsubprocess)
2505 self.assertEqual(str(err), "surrogate:\uDCff")
Gregory P. Smith8d07c262012-11-10 23:53:47 -08002506 except subprocess.SubprocessError as err:
Victor Stinner4d078042010-04-23 19:28:32 +00002507 # _posixsubprocess uses a default message
2508 self.assertIsNotNone(subprocess._posixsubprocess)
2509 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
2510 else:
Gregory P. Smith8d07c262012-11-10 23:53:47 -08002511 self.fail("Expected ValueError or subprocess.SubprocessError")
Victor Stinner4d078042010-04-23 19:28:32 +00002512
Victor Stinner13bb71c2010-04-23 21:41:56 +00002513 def test_undecodable_env(self):
2514 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner5323fb02013-11-19 23:46:06 +01002515 encoded_value = value.encode("ascii", "surrogateescape")
2516
Victor Stinner13bb71c2010-04-23 21:41:56 +00002517 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00002518 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002519 env = os.environ.copy()
2520 env[key] = value
Victor Stinner5323fb02013-11-19 23:46:06 +01002521 # Use C locale to get ASCII for the locale encoding to force
Michael Felt89d79b12018-08-26 19:29:36 +02002522 # surrogate-escaping of \xFF in the child process
Victor Stinnerebc78d22010-10-14 10:38:17 +00002523 env['LC_ALL'] = 'C'
Michael Felt89d79b12018-08-26 19:29:36 +02002524 decoded_value = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00002525 stdout = subprocess.check_output(
2526 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002527 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00002528 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01002529 self.assertEqual(stdout.decode('ascii'), ascii(decoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00002530
2531 # test bytes
2532 key = key.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00002533 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002534 env = os.environ.copy()
Victor Stinner5323fb02013-11-19 23:46:06 +01002535 env[key] = encoded_value
Victor Stinner13bb71c2010-04-23 21:41:56 +00002536 stdout = subprocess.check_output(
2537 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002538 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00002539 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01002540 self.assertEqual(stdout.decode('ascii'), ascii(encoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00002541
Victor Stinnerb745a742010-05-18 17:17:23 +00002542 def test_bytes_program(self):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002543 abs_program = os.fsencode(ZERO_RETURN_CMD[0])
2544 args = list(ZERO_RETURN_CMD[1:])
2545 path, program = os.path.split(ZERO_RETURN_CMD[0])
Victor Stinnerb745a742010-05-18 17:17:23 +00002546 program = os.fsencode(program)
2547
2548 # absolute bytes path
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002549 exitcode = subprocess.call([abs_program]+args)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002550 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002551
Victor Stinner7b3b20a2011-03-03 12:54:05 +00002552 # absolute bytes path as a string
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002553 cmd = b"'%s' %s" % (abs_program, " ".join(args).encode("utf-8"))
Victor Stinner7b3b20a2011-03-03 12:54:05 +00002554 exitcode = subprocess.call(cmd, shell=True)
2555 self.assertEqual(exitcode, 0)
2556
Victor Stinnerb745a742010-05-18 17:17:23 +00002557 # bytes program, unicode PATH
2558 env = os.environ.copy()
2559 env["PATH"] = path
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002560 exitcode = subprocess.call([program]+args, env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002561 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002562
2563 # bytes program, bytes PATH
2564 envb = os.environb.copy()
2565 envb[b"PATH"] = os.fsencode(path)
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002566 exitcode = subprocess.call([program]+args, env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002567 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002568
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002569 def test_pipe_cloexec(self):
2570 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
2571 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2572
2573 p1 = subprocess.Popen([sys.executable, sleeper],
2574 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2575 stderr=subprocess.PIPE, close_fds=False)
2576
2577 self.addCleanup(p1.communicate, b'')
2578
2579 p2 = subprocess.Popen([sys.executable, fd_status],
2580 stdout=subprocess.PIPE, close_fds=False)
2581
2582 output, error = p2.communicate()
2583 result_fds = set(map(int, output.split(b',')))
2584 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
2585 p1.stderr.fileno()])
2586
2587 self.assertFalse(result_fds & unwanted_fds,
2588 "Expected no fds from %r to be open in child, "
2589 "found %r" %
2590 (unwanted_fds, result_fds & unwanted_fds))
2591
2592 def test_pipe_cloexec_real_tools(self):
2593 qcat = support.findfile("qcat.py", subdir="subprocessdata")
2594 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
2595
2596 subdata = b'zxcvbn'
2597 data = subdata * 4 + b'\n'
2598
2599 p1 = subprocess.Popen([sys.executable, qcat],
2600 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2601 close_fds=False)
2602
2603 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
2604 stdin=p1.stdout, stdout=subprocess.PIPE,
2605 close_fds=False)
2606
2607 self.addCleanup(p1.wait)
2608 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08002609 def kill_p1():
2610 try:
2611 p1.terminate()
2612 except ProcessLookupError:
2613 pass
2614 def kill_p2():
2615 try:
2616 p2.terminate()
2617 except ProcessLookupError:
2618 pass
2619 self.addCleanup(kill_p1)
2620 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002621
2622 p1.stdin.write(data)
2623 p1.stdin.close()
2624
2625 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
2626
2627 self.assertTrue(readfiles, "The child hung")
2628 self.assertEqual(p2.stdout.read(), data)
2629
Victor Stinnerfaa8c132011-01-03 16:36:00 +00002630 p1.stdout.close()
2631 p2.stdout.close()
2632
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002633 def test_close_fds(self):
2634 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2635
2636 fds = os.pipe()
2637 self.addCleanup(os.close, fds[0])
2638 self.addCleanup(os.close, fds[1])
2639
2640 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002641 # add a bunch more fds
2642 for _ in range(9):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002643 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002644 self.addCleanup(os.close, fd)
2645 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002646
Victor Stinnerdaf45552013-08-28 00:53:59 +02002647 for fd in open_fds:
2648 os.set_inheritable(fd, True)
2649
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002650 p = subprocess.Popen([sys.executable, fd_status],
2651 stdout=subprocess.PIPE, close_fds=False)
2652 output, ignored = p.communicate()
2653 remaining_fds = set(map(int, output.split(b',')))
2654
2655 self.assertEqual(remaining_fds & open_fds, open_fds,
2656 "Some fds were closed")
2657
2658 p = subprocess.Popen([sys.executable, fd_status],
2659 stdout=subprocess.PIPE, close_fds=True)
2660 output, ignored = p.communicate()
2661 remaining_fds = set(map(int, output.split(b',')))
2662
2663 self.assertFalse(remaining_fds & open_fds,
2664 "Some fds were left open")
2665 self.assertIn(1, remaining_fds, "Subprocess failed")
2666
Gregory P. Smith8facece2012-01-21 14:01:08 -08002667 # Keep some of the fd's we opened open in the subprocess.
2668 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
2669 fds_to_keep = set(open_fds.pop() for _ in range(8))
2670 p = subprocess.Popen([sys.executable, fd_status],
2671 stdout=subprocess.PIPE, close_fds=True,
izbyshev2d8f0632017-12-19 03:26:49 +07002672 pass_fds=fds_to_keep)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002673 output, ignored = p.communicate()
2674 remaining_fds = set(map(int, output.split(b',')))
2675
izbyshev2d8f0632017-12-19 03:26:49 +07002676 self.assertFalse((remaining_fds - fds_to_keep) & open_fds,
Gregory P. Smith8facece2012-01-21 14:01:08 -08002677 "Some fds not in pass_fds were left open")
2678 self.assertIn(1, remaining_fds, "Subprocess failed")
2679
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002680
Gregory P. Smithd04f6992014-06-01 15:27:28 -07002681 @unittest.skipIf(sys.platform.startswith("freebsd") and
2682 os.stat("/dev").st_dev == os.stat("/dev/fd").st_dev,
2683 "Requires fdescfs mounted on /dev/fd on FreeBSD.")
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002684 def test_close_fds_when_max_fd_is_lowered(self):
2685 """Confirm that issue21618 is fixed (may fail under valgrind)."""
2686 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2687
Gregory P. Smith634aa682014-06-15 17:51:04 -07002688 # This launches the meat of the test in a child process to
2689 # avoid messing with the larger unittest processes maximum
2690 # number of file descriptors.
2691 # This process launches:
2692 # +--> Process that lowers its RLIMIT_NOFILE aftr setting up
2693 # a bunch of high open fds above the new lower rlimit.
2694 # Those are reported via stdout before launching a new
2695 # process with close_fds=False to run the actual test:
2696 # +--> The TEST: This one launches a fd_status.py
2697 # subprocess with close_fds=True so we can find out if
2698 # any of the fds above the lowered rlimit are still open.
2699 p = subprocess.Popen([sys.executable, '-c', textwrap.dedent(
2700 '''
2701 import os, resource, subprocess, sys, textwrap
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002702 open_fds = set()
2703 # Add a bunch more fds to pass down.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002704 for _ in range(40):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002705 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002706 open_fds.add(fd)
2707
2708 # Leave a two pairs of low ones available for use by the
2709 # internal child error pipe and the stdout pipe.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002710 # We also leave 10 more open as some Python buildbots run into
2711 # "too many open files" errors during the test if we do not.
2712 for fd in sorted(open_fds)[:14]:
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002713 os.close(fd)
2714 open_fds.remove(fd)
2715
2716 for fd in open_fds:
Gregory P. Smith634aa682014-06-15 17:51:04 -07002717 #self.addCleanup(os.close, fd)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002718 os.set_inheritable(fd, True)
2719
2720 max_fd_open = max(open_fds)
2721
Gregory P. Smith634aa682014-06-15 17:51:04 -07002722 # Communicate the open_fds to the parent unittest.TestCase process.
2723 print(','.join(map(str, sorted(open_fds))))
2724 sys.stdout.flush()
2725
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002726 rlim_cur, rlim_max = resource.getrlimit(resource.RLIMIT_NOFILE)
2727 try:
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002728 # 29 is lower than the highest fds we are leaving open.
2729 resource.setrlimit(resource.RLIMIT_NOFILE, (29, rlim_max))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002730 # Launch a new Python interpreter with our low fd rlim_cur that
2731 # inherits open fds above that limit. It then uses subprocess
2732 # with close_fds=True to get a report of open fds in the child.
2733 # An explicit list of fds to check is passed to fd_status.py as
2734 # letting fd_status rely on its default logic would miss the
2735 # fds above rlim_cur as it normally only checks up to that limit.
Gregory P. Smith634aa682014-06-15 17:51:04 -07002736 subprocess.Popen(
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002737 [sys.executable, '-c',
2738 textwrap.dedent("""
2739 import subprocess, sys
Gregory P. Smith634aa682014-06-15 17:51:04 -07002740 subprocess.Popen([sys.executable, %r] +
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002741 [str(x) for x in range({max_fd})],
Gregory P. Smithffd529c2014-06-01 13:46:54 -07002742 close_fds=True).wait()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002743 """.format(max_fd=max_fd_open+1))],
2744 close_fds=False).wait()
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002745 finally:
2746 resource.setrlimit(resource.RLIMIT_NOFILE, (rlim_cur, rlim_max))
Gregory P. Smith634aa682014-06-15 17:51:04 -07002747 ''' % fd_status)], stdout=subprocess.PIPE)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002748
2749 output, unused_stderr = p.communicate()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002750 output_lines = output.splitlines()
2751 self.assertEqual(len(output_lines), 2,
Gregory P. Smith9204e092014-06-15 20:16:01 -07002752 msg="expected exactly two lines of output:\n%r" % output)
Gregory P. Smith634aa682014-06-15 17:51:04 -07002753 opened_fds = set(map(int, output_lines[0].strip().split(b',')))
2754 remaining_fds = set(map(int, output_lines[1].strip().split(b',')))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002755
Gregory P. Smith634aa682014-06-15 17:51:04 -07002756 self.assertFalse(remaining_fds & opened_fds,
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002757 msg="Some fds were left open.")
2758
2759
Victor Stinner88701e22011-06-01 13:13:04 +02002760 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
2761 # descriptor of a pipe closed in the parent process is valid in the
2762 # child process according to fstat(), but the mode of the file
2763 # descriptor is invalid, and read or write raise an error.
2764 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002765 def test_pass_fds(self):
2766 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2767
2768 open_fds = set()
2769
2770 for x in range(5):
2771 fds = os.pipe()
2772 self.addCleanup(os.close, fds[0])
2773 self.addCleanup(os.close, fds[1])
Victor Stinnerdaf45552013-08-28 00:53:59 +02002774 os.set_inheritable(fds[0], True)
2775 os.set_inheritable(fds[1], True)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002776 open_fds.update(fds)
2777
2778 for fd in open_fds:
2779 p = subprocess.Popen([sys.executable, fd_status],
2780 stdout=subprocess.PIPE, close_fds=True,
2781 pass_fds=(fd, ))
2782 output, ignored = p.communicate()
2783
2784 remaining_fds = set(map(int, output.split(b',')))
2785 to_be_closed = open_fds - {fd}
2786
2787 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
2788 self.assertFalse(remaining_fds & to_be_closed,
2789 "fd to be closed passed")
2790
2791 # pass_fds overrides close_fds with a warning.
2792 with self.assertWarns(RuntimeWarning) as context:
2793 self.assertFalse(subprocess.call(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002794 ZERO_RETURN_CMD,
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002795 close_fds=False, pass_fds=(fd, )))
2796 self.assertIn('overriding close_fds', str(context.warning))
2797
Victor Stinnerdaf45552013-08-28 00:53:59 +02002798 def test_pass_fds_inheritable(self):
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002799 script = support.findfile("fd_status.py", subdir="subprocessdata")
Victor Stinnerdaf45552013-08-28 00:53:59 +02002800
2801 inheritable, non_inheritable = os.pipe()
2802 self.addCleanup(os.close, inheritable)
2803 self.addCleanup(os.close, non_inheritable)
2804 os.set_inheritable(inheritable, True)
2805 os.set_inheritable(non_inheritable, False)
2806 pass_fds = (inheritable, non_inheritable)
2807 args = [sys.executable, script]
2808 args += list(map(str, pass_fds))
2809
2810 p = subprocess.Popen(args,
2811 stdout=subprocess.PIPE, close_fds=True,
2812 pass_fds=pass_fds)
2813 output, ignored = p.communicate()
2814 fds = set(map(int, output.split(b',')))
2815
2816 # the inheritable file descriptor must be inherited, so its inheritable
2817 # flag must be set in the child process after fork() and before exec()
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002818 self.assertEqual(fds, set(pass_fds), "output=%a" % output)
Victor Stinnerdaf45552013-08-28 00:53:59 +02002819
2820 # inheritable flag must not be changed in the parent process
2821 self.assertEqual(os.get_inheritable(inheritable), True)
2822 self.assertEqual(os.get_inheritable(non_inheritable), False)
2823
Gregory P. Smithce344102018-09-10 17:46:22 -07002824
2825 # bpo-32270: Ensure that descriptors specified in pass_fds
2826 # are inherited even if they are used in redirections.
2827 # Contributed by @izbyshev.
2828 def test_pass_fds_redirected(self):
2829 """Regression test for https://bugs.python.org/issue32270."""
2830 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2831 pass_fds = []
2832 for _ in range(2):
2833 fd = os.open(os.devnull, os.O_RDWR)
2834 self.addCleanup(os.close, fd)
2835 pass_fds.append(fd)
2836
2837 stdout_r, stdout_w = os.pipe()
2838 self.addCleanup(os.close, stdout_r)
2839 self.addCleanup(os.close, stdout_w)
2840 pass_fds.insert(1, stdout_w)
2841
2842 with subprocess.Popen([sys.executable, fd_status],
2843 stdin=pass_fds[0],
2844 stdout=pass_fds[1],
2845 stderr=pass_fds[2],
2846 close_fds=True,
2847 pass_fds=pass_fds):
2848 output = os.read(stdout_r, 1024)
2849 fds = {int(num) for num in output.split(b',')}
2850
2851 self.assertEqual(fds, {0, 1, 2} | frozenset(pass_fds), f"output={output!a}")
2852
2853
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002854 def test_stdout_stdin_are_single_inout_fd(self):
2855 with io.open(os.devnull, "r+") as inout:
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002856 p = subprocess.Popen(ZERO_RETURN_CMD,
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002857 stdout=inout, stdin=inout)
2858 p.wait()
2859
2860 def test_stdout_stderr_are_single_inout_fd(self):
2861 with io.open(os.devnull, "r+") as inout:
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002862 p = subprocess.Popen(ZERO_RETURN_CMD,
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002863 stdout=inout, stderr=inout)
2864 p.wait()
2865
2866 def test_stderr_stdin_are_single_inout_fd(self):
2867 with io.open(os.devnull, "r+") as inout:
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002868 p = subprocess.Popen(ZERO_RETURN_CMD,
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002869 stderr=inout, stdin=inout)
2870 p.wait()
2871
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002872 def test_wait_when_sigchild_ignored(self):
2873 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
2874 sigchild_ignore = support.findfile("sigchild_ignore.py",
2875 subdir="subprocessdata")
2876 p = subprocess.Popen([sys.executable, sigchild_ignore],
2877 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
2878 stdout, stderr = p.communicate()
2879 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00002880 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00002881 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002882
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002883 def test_select_unbuffered(self):
2884 # Issue #11459: bufsize=0 should really set the pipes as
2885 # unbuffered (and therefore let select() work properly).
2886 select = support.import_module("select")
2887 p = subprocess.Popen([sys.executable, "-c",
2888 'import sys;'
2889 'sys.stdout.write("apple")'],
2890 stdout=subprocess.PIPE,
2891 bufsize=0)
2892 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02002893 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002894 try:
2895 self.assertEqual(f.read(4), b"appl")
2896 self.assertIn(f, select.select([f], [], [], 0.0)[0])
2897 finally:
2898 p.wait()
2899
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002900 def test_zombie_fast_process_del(self):
2901 # Issue #12650: on Unix, if Popen.__del__() was called before the
2902 # process exited, it wouldn't be added to subprocess._active, and would
2903 # remain a zombie.
2904 # spawn a Popen, and delete its reference before it exits
2905 p = subprocess.Popen([sys.executable, "-c",
2906 'import sys, time;'
2907 'time.sleep(0.2)'],
2908 stdout=subprocess.PIPE,
2909 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002910 self.addCleanup(p.stdout.close)
2911 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002912 ident = id(p)
2913 pid = p.pid
Victor Stinner5a48e212016-05-20 12:11:15 +02002914 with support.check_warnings(('', ResourceWarning)):
2915 p = None
2916
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +03002917 if mswindows:
2918 # subprocess._active is not used on Windows and is set to None.
2919 self.assertIsNone(subprocess._active)
2920 else:
2921 # check that p is in the active processes list
2922 self.assertIn(ident, [id(o) for o in subprocess._active])
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002923
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002924 def test_leak_fast_process_del_killed(self):
2925 # Issue #12650: on Unix, if Popen.__del__() was called before the
2926 # process exited, and the process got killed by a signal, it would never
2927 # be removed from subprocess._active, which triggered a FD and memory
2928 # leak.
2929 # spawn a Popen, delete its reference and kill it
2930 p = subprocess.Popen([sys.executable, "-c",
2931 'import time;'
2932 'time.sleep(3)'],
2933 stdout=subprocess.PIPE,
2934 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002935 self.addCleanup(p.stdout.close)
2936 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002937 ident = id(p)
2938 pid = p.pid
Victor Stinner5a48e212016-05-20 12:11:15 +02002939 with support.check_warnings(('', ResourceWarning)):
2940 p = None
2941
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002942 os.kill(pid, signal.SIGKILL)
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +03002943 if mswindows:
2944 # subprocess._active is not used on Windows and is set to None.
2945 self.assertIsNone(subprocess._active)
2946 else:
2947 # check that p is in the active processes list
2948 self.assertIn(ident, [id(o) for o in subprocess._active])
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002949
2950 # let some time for the process to exit, and create a new Popen: this
2951 # should trigger the wait() of p
2952 time.sleep(0.2)
Victor Stinnerb31206a2018-01-25 19:06:05 +01002953 with self.assertRaises(OSError):
Victor Stinner9a83f652017-08-21 23:51:31 +02002954 with subprocess.Popen(NONEXISTING_CMD,
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002955 stdout=subprocess.PIPE,
2956 stderr=subprocess.PIPE) as proc:
2957 pass
2958 # p should have been wait()ed on, and removed from the _active list
2959 self.assertRaises(OSError, os.waitpid, pid, 0)
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +03002960 if mswindows:
2961 # subprocess._active is not used on Windows and is set to None.
2962 self.assertIsNone(subprocess._active)
2963 else:
2964 self.assertNotIn(ident, [id(o) for o in subprocess._active])
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002965
Charles-François Natali249cdc32013-08-25 18:24:45 +02002966 def test_close_fds_after_preexec(self):
2967 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2968
2969 # this FD is used as dup2() target by preexec_fn, and should be closed
2970 # in the child process
2971 fd = os.dup(1)
2972 self.addCleanup(os.close, fd)
2973
2974 p = subprocess.Popen([sys.executable, fd_status],
2975 stdout=subprocess.PIPE, close_fds=True,
2976 preexec_fn=lambda: os.dup2(1, fd))
2977 output, ignored = p.communicate()
2978
2979 remaining_fds = set(map(int, output.split(b',')))
2980
2981 self.assertNotIn(fd, remaining_fds)
2982
Victor Stinner8f437aa2014-10-05 17:25:19 +02002983 @support.cpython_only
2984 def test_fork_exec(self):
2985 # Issue #22290: fork_exec() must not crash on memory allocation failure
2986 # or other errors
2987 import _posixsubprocess
2988 gc_enabled = gc.isenabled()
2989 try:
2990 # Use a preexec function and enable the garbage collector
2991 # to force fork_exec() to re-enable the garbage collector
2992 # on error.
2993 func = lambda: None
2994 gc.enable()
2995
Victor Stinner8f437aa2014-10-05 17:25:19 +02002996 for args, exe_list, cwd, env_list in (
2997 (123, [b"exe"], None, [b"env"]),
2998 ([b"arg"], 123, None, [b"env"]),
2999 ([b"arg"], [b"exe"], 123, [b"env"]),
3000 ([b"arg"], [b"exe"], None, 123),
3001 ):
Patrick McLean2b2ead72019-09-12 10:15:44 -07003002 with self.assertRaises(TypeError) as err:
Victor Stinner8f437aa2014-10-05 17:25:19 +02003003 _posixsubprocess.fork_exec(
3004 args, exe_list,
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03003005 True, (), cwd, env_list,
Victor Stinner8f437aa2014-10-05 17:25:19 +02003006 -1, -1, -1, -1,
3007 1, 2, 3, 4,
Patrick McLean2b2ead72019-09-12 10:15:44 -07003008 True, True,
Gregory P. Smithf3751ef2019-10-12 13:24:56 -07003009 False, [], 0, -1,
Patrick McLean2b2ead72019-09-12 10:15:44 -07003010 func)
3011 # Attempt to prevent
3012 # "TypeError: fork_exec() takes exactly N arguments (M given)"
3013 # from passing the test. More refactoring to have us start
3014 # with a valid *args list, confirm a good call with that works
3015 # before mutating it in various ways to ensure that bad calls
3016 # with individual arg type errors raise a typeerror would be
3017 # ideal. Saving that for a future PR...
3018 self.assertNotIn('takes exactly', str(err.exception))
Victor Stinner8f437aa2014-10-05 17:25:19 +02003019 finally:
3020 if not gc_enabled:
3021 gc.disable()
3022
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08003023 @support.cpython_only
3024 def test_fork_exec_sorted_fd_sanity_check(self):
3025 # Issue #23564: sanity check the fork_exec() fds_to_keep sanity check.
3026 import _posixsubprocess
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03003027 class BadInt:
3028 first = True
3029 def __init__(self, value):
3030 self.value = value
3031 def __int__(self):
3032 if self.first:
3033 self.first = False
3034 return self.value
3035 raise ValueError
3036
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08003037 gc_enabled = gc.isenabled()
3038 try:
3039 gc.enable()
3040
3041 for fds_to_keep in (
3042 (-1, 2, 3, 4, 5), # Negative number.
3043 ('str', 4), # Not an int.
3044 (18, 23, 42, 2**63), # Out of range.
3045 (5, 4), # Not sorted.
3046 (6, 7, 7, 8), # Duplicate.
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03003047 (BadInt(1), BadInt(2)),
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08003048 ):
3049 with self.assertRaises(
3050 ValueError,
3051 msg='fds_to_keep={}'.format(fds_to_keep)) as c:
3052 _posixsubprocess.fork_exec(
3053 [b"false"], [b"false"],
3054 True, fds_to_keep, None, [b"env"],
3055 -1, -1, -1, -1,
3056 1, 2, 3, 4,
Patrick McLean2b2ead72019-09-12 10:15:44 -07003057 True, True,
Gregory P. Smithf3751ef2019-10-12 13:24:56 -07003058 None, None, None, -1,
Patrick McLean2b2ead72019-09-12 10:15:44 -07003059 None)
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08003060 self.assertIn('fds_to_keep', str(c.exception))
3061 finally:
3062 if not gc_enabled:
3063 gc.disable()
Victor Stinner8f437aa2014-10-05 17:25:19 +02003064
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)2daf8e72016-06-05 02:57:47 +00003065 def test_communicate_BrokenPipeError_stdin_close(self):
3066 # By not setting stdout or stderr or a timeout we force the fast path
3067 # that just calls _stdin_write() internally due to our mock.
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003068 proc = subprocess.Popen(ZERO_RETURN_CMD)
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)2daf8e72016-06-05 02:57:47 +00003069 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
3070 mock_proc_stdin.close.side_effect = BrokenPipeError
3071 proc.communicate() # Should swallow BrokenPipeError from close.
3072 mock_proc_stdin.close.assert_called_with()
3073
3074 def test_communicate_BrokenPipeError_stdin_write(self):
3075 # By not setting stdout or stderr or a timeout we force the fast path
3076 # that just calls _stdin_write() internally due to our mock.
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003077 proc = subprocess.Popen(ZERO_RETURN_CMD)
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)2daf8e72016-06-05 02:57:47 +00003078 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
3079 mock_proc_stdin.write.side_effect = BrokenPipeError
3080 proc.communicate(b'stuff') # Should swallow the BrokenPipeError.
3081 mock_proc_stdin.write.assert_called_once_with(b'stuff')
3082 mock_proc_stdin.close.assert_called_once_with()
3083
3084 def test_communicate_BrokenPipeError_stdin_flush(self):
3085 # Setting stdin and stdout forces the ._communicate() code path.
3086 # python -h exits faster than python -c pass (but spams stdout).
3087 proc = subprocess.Popen([sys.executable, '-h'],
3088 stdin=subprocess.PIPE,
3089 stdout=subprocess.PIPE)
3090 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin, \
3091 open(os.devnull, 'wb') as dev_null:
3092 mock_proc_stdin.flush.side_effect = BrokenPipeError
3093 # because _communicate registers a selector using proc.stdin...
3094 mock_proc_stdin.fileno.return_value = dev_null.fileno()
3095 # _communicate() should swallow BrokenPipeError from flush.
3096 proc.communicate(b'stuff')
3097 mock_proc_stdin.flush.assert_called_once_with()
3098
3099 def test_communicate_BrokenPipeError_stdin_close_with_timeout(self):
3100 # Setting stdin and stdout forces the ._communicate() code path.
3101 # python -h exits faster than python -c pass (but spams stdout).
3102 proc = subprocess.Popen([sys.executable, '-h'],
3103 stdin=subprocess.PIPE,
3104 stdout=subprocess.PIPE)
3105 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
3106 mock_proc_stdin.close.side_effect = BrokenPipeError
3107 # _communicate() should swallow BrokenPipeError from close.
3108 proc.communicate(timeout=999)
3109 mock_proc_stdin.close.assert_called_once_with()
3110
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003111 @unittest.skipUnless(_testcapi is not None
3112 and hasattr(_testcapi, 'W_STOPCODE'),
3113 'need _testcapi.W_STOPCODE')
3114 def test_stopped(self):
Gregory P. Smith50e16e32017-01-22 17:28:38 -08003115 """Test wait() behavior when waitpid returns WIFSTOPPED; issue29335."""
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003116 args = ZERO_RETURN_CMD
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003117 proc = subprocess.Popen(args)
Victor Stinnercdee3f12017-06-26 17:23:03 +02003118
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003119 # Wait until the real process completes to avoid zombie process
Victor Stinner278c1e12020-03-31 20:08:12 +02003120 support.wait_process(proc.pid, exitcode=0)
Victor Stinnercdee3f12017-06-26 17:23:03 +02003121
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003122 status = _testcapi.W_STOPCODE(3)
Victor Stinner278c1e12020-03-31 20:08:12 +02003123 with mock.patch('subprocess.os.waitpid', return_value=(proc.pid, status)):
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003124 returncode = proc.wait()
Victor Stinnercdee3f12017-06-26 17:23:03 +02003125
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003126 self.assertEqual(returncode, -3)
Gregory P. Smith50e16e32017-01-22 17:28:38 -08003127
Victor Stinnere85a3052020-01-15 17:38:55 +01003128 def test_send_signal_race(self):
3129 # bpo-38630: send_signal() must poll the process exit status to reduce
3130 # the risk of sending the signal to the wrong process.
3131 proc = subprocess.Popen(ZERO_RETURN_CMD)
3132
3133 # wait until the process completes without using the Popen APIs.
Victor Stinner278c1e12020-03-31 20:08:12 +02003134 support.wait_process(proc.pid, exitcode=0)
Victor Stinnere85a3052020-01-15 17:38:55 +01003135
3136 # returncode is still None but the process completed.
3137 self.assertIsNone(proc.returncode)
3138
3139 with mock.patch("os.kill") as mock_kill:
3140 proc.send_signal(signal.SIGTERM)
3141
3142 # send_signal() didn't call os.kill() since the process already
3143 # completed.
3144 mock_kill.assert_not_called()
3145
3146 # Don't check the returncode value: the test reads the exit status,
3147 # so Popen failed to read it and uses a default returncode instead.
3148 self.assertIsNotNone(proc.returncode)
3149
Alex Rebertd3ae95e2020-01-22 18:28:31 -05003150 def test_communicate_repeated_call_after_stdout_close(self):
3151 proc = subprocess.Popen([sys.executable, '-c',
3152 'import os, time; os.close(1), time.sleep(2)'],
3153 stdout=subprocess.PIPE)
3154 while True:
3155 try:
3156 proc.communicate(timeout=0.1)
3157 return
3158 except subprocess.TimeoutExpired:
3159 pass
3160
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003161
Victor Stinner937ee9e2018-06-26 02:11:06 +02003162@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00003163class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00003164
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003165 def test_startupinfo(self):
3166 # startupinfo argument
3167 # We uses hardcoded constants, because we do not want to
3168 # depend on win32all.
3169 STARTF_USESHOWWINDOW = 1
3170 SW_MAXIMIZE = 3
3171 startupinfo = subprocess.STARTUPINFO()
3172 startupinfo.dwFlags = STARTF_USESHOWWINDOW
3173 startupinfo.wShowWindow = SW_MAXIMIZE
3174 # Since Python is a console process, it won't be affected
3175 # by wShowWindow, but the argument should be silently
3176 # ignored
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003177 subprocess.call(ZERO_RETURN_CMD,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003178 startupinfo=startupinfo)
3179
Subhendu Ghoshae160bb2017-02-25 20:29:05 +05303180 def test_startupinfo_keywords(self):
3181 # startupinfo argument
3182 # We use hardcoded constants, because we do not want to
3183 # depend on win32all.
3184 STARTF_USERSHOWWINDOW = 1
3185 SW_MAXIMIZE = 3
3186 startupinfo = subprocess.STARTUPINFO(
3187 dwFlags=STARTF_USERSHOWWINDOW,
3188 wShowWindow=SW_MAXIMIZE
3189 )
3190 # Since Python is a console process, it won't be affected
3191 # by wShowWindow, but the argument should be silently
3192 # ignored
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003193 subprocess.call(ZERO_RETURN_CMD,
Subhendu Ghoshae160bb2017-02-25 20:29:05 +05303194 startupinfo=startupinfo)
3195
Victor Stinner483422f2018-07-05 22:54:17 +02003196 def test_startupinfo_copy(self):
3197 # bpo-34044: Popen must not modify input STARTUPINFO structure
3198 startupinfo = subprocess.STARTUPINFO()
3199 startupinfo.dwFlags = subprocess.STARTF_USESHOWWINDOW
3200 startupinfo.wShowWindow = subprocess.SW_HIDE
3201
3202 # Call Popen() twice with the same startupinfo object to make sure
3203 # that it's not modified
3204 for _ in range(2):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003205 cmd = ZERO_RETURN_CMD
Victor Stinner483422f2018-07-05 22:54:17 +02003206 with open(os.devnull, 'w') as null:
3207 proc = subprocess.Popen(cmd,
3208 stdout=null,
3209 stderr=subprocess.STDOUT,
3210 startupinfo=startupinfo)
3211 with proc:
3212 proc.communicate()
3213 self.assertEqual(proc.returncode, 0)
3214
3215 self.assertEqual(startupinfo.dwFlags,
3216 subprocess.STARTF_USESHOWWINDOW)
3217 self.assertIsNone(startupinfo.hStdInput)
3218 self.assertIsNone(startupinfo.hStdOutput)
3219 self.assertIsNone(startupinfo.hStdError)
3220 self.assertEqual(startupinfo.wShowWindow, subprocess.SW_HIDE)
3221 self.assertEqual(startupinfo.lpAttributeList, {"handle_list": []})
3222
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003223 def test_creationflags(self):
3224 # creationflags argument
3225 CREATE_NEW_CONSOLE = 16
3226 sys.stderr.write(" a DOS box should flash briefly ...\n")
3227 subprocess.call(sys.executable +
3228 ' -c "import time; time.sleep(0.25)"',
3229 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003230
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003231 def test_invalid_args(self):
3232 # invalid arguments should raise ValueError
3233 self.assertRaises(ValueError, subprocess.call,
3234 [sys.executable, "-c",
3235 "import sys; sys.exit(47)"],
3236 preexec_fn=lambda: 1)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003237
Oren Milman0b3a87e2017-09-14 22:30:28 +03003238 @support.cpython_only
3239 def test_issue31471(self):
3240 # There shouldn't be an assertion failure in Popen() in case the env
3241 # argument has a bad keys() method.
3242 class BadEnv(dict):
3243 keys = None
3244 with self.assertRaises(TypeError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003245 subprocess.Popen(ZERO_RETURN_CMD, env=BadEnv())
Oren Milman0b3a87e2017-09-14 22:30:28 +03003246
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003247 def test_close_fds(self):
3248 # close file descriptors
3249 rc = subprocess.call([sys.executable, "-c",
3250 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003251 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003252 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003253
Segev Finerb2a60832017-12-18 11:28:19 +02003254 def test_close_fds_with_stdio(self):
3255 import msvcrt
3256
3257 fds = os.pipe()
3258 self.addCleanup(os.close, fds[0])
3259 self.addCleanup(os.close, fds[1])
3260
3261 handles = []
3262 for fd in fds:
3263 os.set_inheritable(fd, True)
3264 handles.append(msvcrt.get_osfhandle(fd))
3265
3266 p = subprocess.Popen([sys.executable, "-c",
3267 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3268 stdout=subprocess.PIPE, close_fds=False)
3269 stdout, stderr = p.communicate()
3270 self.assertEqual(p.returncode, 0)
3271 int(stdout.strip()) # Check that stdout is an integer
3272
3273 p = subprocess.Popen([sys.executable, "-c",
3274 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3275 stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
3276 stdout, stderr = p.communicate()
3277 self.assertEqual(p.returncode, 1)
3278 self.assertIn(b"OSError", stderr)
3279
3280 # The same as the previous call, but with an empty handle_list
3281 handle_list = []
3282 startupinfo = subprocess.STARTUPINFO()
3283 startupinfo.lpAttributeList = {"handle_list": handle_list}
3284 p = subprocess.Popen([sys.executable, "-c",
3285 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3286 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
3287 startupinfo=startupinfo, close_fds=True)
3288 stdout, stderr = p.communicate()
3289 self.assertEqual(p.returncode, 1)
3290 self.assertIn(b"OSError", stderr)
3291
3292 # Check for a warning due to using handle_list and close_fds=False
3293 with support.check_warnings((".*overriding close_fds", RuntimeWarning)):
3294 startupinfo = subprocess.STARTUPINFO()
3295 startupinfo.lpAttributeList = {"handle_list": handles[:]}
3296 p = subprocess.Popen([sys.executable, "-c",
3297 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3298 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
3299 startupinfo=startupinfo, close_fds=False)
3300 stdout, stderr = p.communicate()
3301 self.assertEqual(p.returncode, 0)
3302
3303 def test_empty_attribute_list(self):
3304 startupinfo = subprocess.STARTUPINFO()
3305 startupinfo.lpAttributeList = {}
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003306 subprocess.call(ZERO_RETURN_CMD,
Segev Finerb2a60832017-12-18 11:28:19 +02003307 startupinfo=startupinfo)
3308
3309 def test_empty_handle_list(self):
3310 startupinfo = subprocess.STARTUPINFO()
3311 startupinfo.lpAttributeList = {"handle_list": []}
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003312 subprocess.call(ZERO_RETURN_CMD,
Segev Finerb2a60832017-12-18 11:28:19 +02003313 startupinfo=startupinfo)
3314
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003315 def test_shell_sequence(self):
3316 # Run command through the shell (sequence)
3317 newenv = os.environ.copy()
3318 newenv["FRUIT"] = "physalis"
3319 p = subprocess.Popen(["set"], shell=1,
3320 stdout=subprocess.PIPE,
3321 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02003322 with p:
3323 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00003324
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003325 def test_shell_string(self):
3326 # Run command through the shell (string)
3327 newenv = os.environ.copy()
3328 newenv["FRUIT"] = "physalis"
3329 p = subprocess.Popen("set", shell=1,
3330 stdout=subprocess.PIPE,
3331 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02003332 with p:
3333 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003334
Steve Dower050acae2016-09-06 20:16:17 -07003335 def test_shell_encodings(self):
3336 # Run command through the shell (string)
3337 for enc in ['ansi', 'oem']:
3338 newenv = os.environ.copy()
3339 newenv["FRUIT"] = "physalis"
3340 p = subprocess.Popen("set", shell=1,
3341 stdout=subprocess.PIPE,
3342 env=newenv,
3343 encoding=enc)
3344 with p:
3345 self.assertIn("physalis", p.stdout.read(), enc)
3346
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003347 def test_call_string(self):
3348 # call() function with string argument on Windows
3349 rc = subprocess.call(sys.executable +
3350 ' -c "import sys; sys.exit(47)"')
3351 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003352
Florent Xicluna4886d242010-03-08 13:27:26 +00003353 def _kill_process(self, method, *args):
3354 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00003355 p = subprocess.Popen([sys.executable, "-c", """if 1:
3356 import sys, time
3357 sys.stdout.write('x\\n')
3358 sys.stdout.flush()
3359 time.sleep(30)
3360 """],
3361 stdin=subprocess.PIPE,
3362 stdout=subprocess.PIPE,
3363 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02003364 with p:
3365 # Wait for the interpreter to be completely initialized before
3366 # sending any signal.
3367 p.stdout.read(1)
3368 getattr(p, method)(*args)
3369 _, stderr = p.communicate()
Victor Stinner6cac1132019-12-08 08:38:16 +01003370 self.assertEqual(stderr, b'')
Victor Stinner7438c612016-05-20 12:43:15 +02003371 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00003372 self.assertNotEqual(returncode, 0)
3373
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003374 def _kill_dead_process(self, method, *args):
3375 p = subprocess.Popen([sys.executable, "-c", """if 1:
3376 import sys, time
3377 sys.stdout.write('x\\n')
3378 sys.stdout.flush()
3379 sys.exit(42)
3380 """],
3381 stdin=subprocess.PIPE,
3382 stdout=subprocess.PIPE,
3383 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02003384 with p:
3385 # Wait for the interpreter to be completely initialized before
3386 # sending any signal.
3387 p.stdout.read(1)
3388 # The process should end after this
3389 time.sleep(1)
3390 # This shouldn't raise even though the child is now dead
3391 getattr(p, method)(*args)
3392 _, stderr = p.communicate()
Victor Stinner6cac1132019-12-08 08:38:16 +01003393 self.assertEqual(stderr, b'')
Victor Stinner7438c612016-05-20 12:43:15 +02003394 rc = p.wait()
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003395 self.assertEqual(rc, 42)
3396
Florent Xicluna4886d242010-03-08 13:27:26 +00003397 def test_send_signal(self):
3398 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00003399
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003400 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00003401 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00003402
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003403 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00003404 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00003405
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003406 def test_send_signal_dead(self):
3407 self._kill_dead_process('send_signal', signal.SIGTERM)
3408
3409 def test_kill_dead(self):
3410 self._kill_dead_process('kill')
3411
3412 def test_terminate_dead(self):
3413 self._kill_dead_process('terminate')
3414
Martin Panter23172bd2016-04-16 11:28:10 +00003415class MiscTests(unittest.TestCase):
Gregory P. Smithf4d644f2018-01-29 21:27:39 -08003416
3417 class RecordingPopen(subprocess.Popen):
3418 """A Popen that saves a reference to each instance for testing."""
3419 instances_created = []
3420
3421 def __init__(self, *args, **kwargs):
3422 super().__init__(*args, **kwargs)
3423 self.instances_created.append(self)
3424
3425 @mock.patch.object(subprocess.Popen, "_communicate")
3426 def _test_keyboardinterrupt_no_kill(self, popener, mock__communicate,
3427 **kwargs):
3428 """Fake a SIGINT happening during Popen._communicate() and ._wait().
3429
3430 This avoids the need to actually try and get test environments to send
3431 and receive signals reliably across platforms. The net effect of a ^C
3432 happening during a blocking subprocess execution which we want to clean
3433 up from is a KeyboardInterrupt coming out of communicate() or wait().
3434 """
3435
3436 mock__communicate.side_effect = KeyboardInterrupt
3437 try:
3438 with mock.patch.object(subprocess.Popen, "_wait") as mock__wait:
3439 # We patch out _wait() as no signal was involved so the
3440 # child process isn't actually going to exit rapidly.
3441 mock__wait.side_effect = KeyboardInterrupt
3442 with mock.patch.object(subprocess, "Popen",
3443 self.RecordingPopen):
3444 with self.assertRaises(KeyboardInterrupt):
3445 popener([sys.executable, "-c",
3446 "import time\ntime.sleep(9)\nimport sys\n"
3447 "sys.stderr.write('\\n!runaway child!\\n')"],
3448 stdout=subprocess.DEVNULL, **kwargs)
3449 for call in mock__wait.call_args_list[1:]:
3450 self.assertNotEqual(
3451 call, mock.call(timeout=None),
3452 "no open-ended wait() after the first allowed: "
3453 f"{mock__wait.call_args_list}")
3454 sigint_calls = []
3455 for call in mock__wait.call_args_list:
3456 if call == mock.call(timeout=0.25): # from Popen.__init__
3457 sigint_calls.append(call)
3458 self.assertLessEqual(mock__wait.call_count, 2,
3459 msg=mock__wait.call_args_list)
3460 self.assertEqual(len(sigint_calls), 1,
3461 msg=mock__wait.call_args_list)
3462 finally:
3463 # cleanup the forgotten (due to our mocks) child process
3464 process = self.RecordingPopen.instances_created.pop()
3465 process.kill()
3466 process.wait()
3467 self.assertEqual([], self.RecordingPopen.instances_created)
3468
3469 def test_call_keyboardinterrupt_no_kill(self):
3470 self._test_keyboardinterrupt_no_kill(subprocess.call, timeout=6.282)
3471
3472 def test_run_keyboardinterrupt_no_kill(self):
3473 self._test_keyboardinterrupt_no_kill(subprocess.run, timeout=6.282)
3474
3475 def test_context_manager_keyboardinterrupt_no_kill(self):
3476 def popen_via_context_manager(*args, **kwargs):
3477 with subprocess.Popen(*args, **kwargs) as unused_process:
3478 raise KeyboardInterrupt # Test how __exit__ handles ^C.
3479 self._test_keyboardinterrupt_no_kill(popen_via_context_manager)
3480
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003481 def test_getoutput(self):
3482 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
3483 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
3484 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00003485
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003486 # we use mkdtemp in the next line to create an empty directory
3487 # under our exclusive control; from that, we can invent a pathname
3488 # that we _know_ won't exist. This is guaranteed to fail.
3489 dir = None
3490 try:
3491 dir = tempfile.mkdtemp()
3492 name = os.path.join(dir, "foo")
Tim Goldene0041752013-11-03 12:53:17 +00003493 status, output = subprocess.getstatusoutput(
Victor Stinner937ee9e2018-06-26 02:11:06 +02003494 ("type " if mswindows else "cat ") + name)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003495 self.assertNotEqual(status, 0)
3496 finally:
3497 if dir is not None:
3498 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00003499
Gregory P. Smithace55862015-04-07 15:57:54 -07003500 def test__all__(self):
3501 """Ensure that __all__ is populated properly."""
Patrick McLean2b2ead72019-09-12 10:15:44 -07003502 intentionally_excluded = {"list2cmdline", "Handle", "pwd", "grp"}
Gregory P. Smithace55862015-04-07 15:57:54 -07003503 exported = set(subprocess.__all__)
3504 possible_exports = set()
3505 import types
3506 for name, value in subprocess.__dict__.items():
3507 if name.startswith('_'):
3508 continue
3509 if isinstance(value, (types.ModuleType,)):
3510 continue
3511 possible_exports.add(name)
3512 self.assertEqual(exported, possible_exports - intentionally_excluded)
3513
3514
Martin Panter23172bd2016-04-16 11:28:10 +00003515@unittest.skipUnless(hasattr(selectors, 'PollSelector'),
3516 "Test needs selectors.PollSelector")
3517class ProcessTestCaseNoPoll(ProcessTestCase):
3518 def setUp(self):
3519 self.orig_selector = subprocess._PopenSelector
3520 subprocess._PopenSelector = selectors.SelectSelector
3521 ProcessTestCase.setUp(self)
3522
3523 def tearDown(self):
3524 subprocess._PopenSelector = self.orig_selector
3525 ProcessTestCase.tearDown(self)
3526
Gregory P. Smithd06fa472009-07-04 02:46:54 +00003527
Victor Stinner937ee9e2018-06-26 02:11:06 +02003528@unittest.skipUnless(mswindows, "Windows-specific tests")
Tim Golden126c2962010-08-11 14:20:40 +00003529class CommandsWithSpaces (BaseTestCase):
3530
3531 def setUp(self):
3532 super().setUp()
Berker Peksag16a1f282015-09-28 13:33:14 +03003533 f, fname = tempfile.mkstemp(".py", "te st")
Tim Golden126c2962010-08-11 14:20:40 +00003534 self.fname = fname.lower ()
3535 os.write(f, b"import sys;"
3536 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
3537 )
3538 os.close(f)
3539
3540 def tearDown(self):
3541 os.remove(self.fname)
3542 super().tearDown()
3543
3544 def with_spaces(self, *args, **kwargs):
3545 kwargs['stdout'] = subprocess.PIPE
3546 p = subprocess.Popen(*args, **kwargs)
Victor Stinner7438c612016-05-20 12:43:15 +02003547 with p:
3548 self.assertEqual(
3549 p.stdout.read ().decode("mbcs"),
3550 "2 [%r, 'ab cd']" % self.fname
3551 )
Tim Golden126c2962010-08-11 14:20:40 +00003552
3553 def test_shell_string_with_spaces(self):
3554 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00003555 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
3556 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00003557
3558 def test_shell_sequence_with_spaces(self):
3559 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00003560 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00003561
3562 def test_noshell_string_with_spaces(self):
3563 # call() function with string argument with spaces on Windows
3564 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
3565 "ab cd"))
3566
3567 def test_noshell_sequence_with_spaces(self):
3568 # call() function with sequence argument with spaces on Windows
3569 self.with_spaces([sys.executable, self.fname, "ab cd"])
3570
Brian Curtin79cdb662010-12-03 02:46:02 +00003571
Georg Brandla86b2622012-02-20 21:34:57 +01003572class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00003573
3574 def test_pipe(self):
3575 with subprocess.Popen([sys.executable, "-c",
3576 "import sys;"
3577 "sys.stdout.write('stdout');"
3578 "sys.stderr.write('stderr');"],
3579 stdout=subprocess.PIPE,
3580 stderr=subprocess.PIPE) as proc:
3581 self.assertEqual(proc.stdout.read(), b"stdout")
Victor Stinner6cac1132019-12-08 08:38:16 +01003582 self.assertEqual(proc.stderr.read(), b"stderr")
Brian Curtin79cdb662010-12-03 02:46:02 +00003583
3584 self.assertTrue(proc.stdout.closed)
3585 self.assertTrue(proc.stderr.closed)
3586
3587 def test_returncode(self):
3588 with subprocess.Popen([sys.executable, "-c",
3589 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07003590 pass
3591 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00003592 self.assertEqual(proc.returncode, 100)
3593
3594 def test_communicate_stdin(self):
3595 with subprocess.Popen([sys.executable, "-c",
3596 "import sys;"
3597 "sys.exit(sys.stdin.read() == 'context')"],
3598 stdin=subprocess.PIPE) as proc:
3599 proc.communicate(b"context")
3600 self.assertEqual(proc.returncode, 1)
3601
3602 def test_invalid_args(self):
Victor Stinnerb31206a2018-01-25 19:06:05 +01003603 with self.assertRaises(NONEXISTING_ERRORS):
Victor Stinner9a83f652017-08-21 23:51:31 +02003604 with subprocess.Popen(NONEXISTING_CMD,
Brian Curtin79cdb662010-12-03 02:46:02 +00003605 stdout=subprocess.PIPE,
3606 stderr=subprocess.PIPE) as proc:
3607 pass
3608
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003609 def test_broken_pipe_cleanup(self):
3610 """Broken pipe error should not prevent wait() (Issue 21619)"""
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003611 proc = subprocess.Popen(ZERO_RETURN_CMD,
Victor Stinner20f4bd42015-03-05 02:38:41 +01003612 stdin=subprocess.PIPE,
Victor Stinner20f4bd42015-03-05 02:38:41 +01003613 bufsize=support.PIPE_MAX_SIZE*2)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003614 proc = proc.__enter__()
3615 # Prepare to send enough data to overflow any OS pipe buffering and
3616 # guarantee a broken pipe error. Data is held in BufferedWriter
3617 # buffer until closed.
3618 proc.stdin.write(b'x' * support.PIPE_MAX_SIZE)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003619 self.assertIsNone(proc.returncode)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003620 # EPIPE expected under POSIX; EINVAL under Windows
Serhiy Storchakacf265fd2015-02-28 13:27:54 +02003621 self.assertRaises(OSError, proc.__exit__, None, None, None)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003622 self.assertEqual(proc.returncode, 0)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003623 self.assertTrue(proc.stdin.closed)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003624
Brian Curtin79cdb662010-12-03 02:46:02 +00003625
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003626if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04003627 unittest.main()